# ALLT I PROGRAMMET SKA ALLTID VARA PÅ ENGELSKA - ALDRIG SVENSKA!
# ALL CONTENT IN THIS PROGRAM MUST ALWAYS BE IN ENGLISH - NEVER SWEDISH!

# ==============================================================================
# F(re)email.py  —  A clean Gmail frontend (Thunderbird-inspired dark theme)
# Author : Lars "Issu" Olsson
# ==============================================================================
#
# ToDo / Road-map (what is done and what Claude Code should finish):
#
#  DONE (this file):
#   [x] Full two-panel Thunderbird-style layout (sidebar + message list)
#   [x] Account/folder sidebar (left panel)
#   [x] Message list (centre panel) with mock data
#   [x] Message view popup (Toplevel, opens on click — replaces fixed right panel)
#   [x] Compose window (Toplevel, full-featured)
#   [x] Toolbar with New / Reply / Forward / Delete / Refresh buttons
#   [x] Dark colour theme (navy/slate, accent blue)
#   [x] No blinking cursors anywhere (insertofftime=0, insertontime=9999999)
#   [x] Crash catcher + diagnostic log
#   [x] Persistent settings (window size, sash positions, last account, etc.)
#   [x] Auto-disappearing success popups (1 second)
#   [x] Scrollbars + mouse-wheel everywhere
#   [x] About dialog (Lars "Issu" Olsson, donate links)
#   [x] Help dialog (hardcoded English, ESC closes)
#   [x] Icon via Icons/Freemail.ico  (external file, not embedded)
#   [x] AppUserModelID set before tk.Tk()
#   [x] Helpfiles/ structure — ALL data in Helpfiles/Freemail/ (DEL 04g2:
#       settings.json, Accounts/, Cache/, Drafts/, Deleted/, Outbox/, Notes/,
#       Archive/, Backups/); LOG alone in Helpfiles/0---Empty/Freemail.log.
#       Old scattered data (loose settings.json + Helpfiles/Accounts/) is moved
#       in on first run by _migrate_to_freemail_dir() — content-checked for
#       settings, exact-name for Accounts stores, and PATTERN-based for the
#       working folders so a folder shared with another program (e.g.
#       Helpfiles/Notes is also Notes.py's) keeps everything that isn't ours.
#   [x] Button colours clearly named as constants for easy editing
#   [x] ENTER works in compose subject/to fields
#   [x] "All Accounts" virtual account — unified inbox/sent/trash across every account
#   [x] Compose From: dropdown — defaults to receiving account, switchable to any other
#
#  ============================================================================
#  SAFETY PRINCIPLE (read this first — non-negotiable)
#  ----------------------------------------------------------------------------
#  Nothing this program does may ever make mail disappear from Gmail.
#  We roll out real Gmail access in two strictly separated phases:
#
#    PHASE 1 — READ-ONLY (current target):
#      • Connect to Gmail and FETCH mail only.
#      • IMAP mailboxes are opened with readonly=True so the server itself
#        refuses any flag change / expunge — a hard guarantee, not a promise.
#      • "Delete", "move", "mark read on server", "sort/label" are DISABLED
#        (or act only on the local in-memory copy, never on Gmail).
#      • Sending a NEW message / reply is additive (it cannot erase anything),
#        so SMTP send MAY be enabled in this phase — but kept clearly opt-in.
#
#    PHASE 2 — WRITE (only after Phase 1 is verified safe by the user):
#      • Flip a single, explicit "allow server-side changes" switch.
#      • Only THEN may F(re)email delete, move to Trash, mark read/unread,
#        apply/remove labels, mark spam, etc. on the actual Gmail account.
#  ============================================================================
#
#  TODO (for Claude Code to wire up):
#
#   --- PHASE 1: make it a REAL, working mail program (read-only first) -------
#   [x] Account login — app password over IMAP/SMTP (DEL 04b/04c). DPAPI-
#       encrypted secrets in Helpfiles/Accounts/. Accounts menu Add/Remove.
#   [x] Real fetch — _fetch_folder() opens readonly=True + BODY.PEEK[] (hard
#       Phase-1 safety). Gmail folders auto-discovered via SPECIAL-USE flags,
#       so localized (e.g. Swedish) folder names work too.
#   [x] Real send — ComposeWindow / SmartReplyWindow call app.queue_send()
#       → the outbox → _smtp_send() via Gmail SMTP (additive; worker thread).
#       That is the ONLY send path; see the note where send_mail() used to be.
#   [x] Multiple accounts — per-account fetch + merge for ALL_ACCOUNTS_ID.
#   [x] Crash-safe — all fetch/send happen off the main thread (root.after).
#   [x] Clickable column-header sorting (_sort_by/_apply_sort), remembered.
#   [x] External icon Icons/Freemail.ico generated (real .ico, not embedded).
#   [x] Per-message machine date msg["_dt"] (ISO) — feeds attachment {YYYY-MM}.
#   NOTE: full next-week work order + HTTP-Claude/Claude-Code split is in
#         F(re)email_NEXTWEEK.md (next to this file).
#   [~] Search — currently a LOCAL filter of the loaded folder (read-only,
#       instant). TODO: optional live IMAP SEARCH for the whole mailbox.
#   [x] Auto-check interval — PER ACCOUNT (Tools -> Auto-check dialog):
#       each account has its own timer/interval (Off/1/5/10/15/30/60 min) with
#       a global default fallback; read-only background refresh
#       (_poll_account/_reschedule_autocheck), remembered, no stacking.
#   [x] Local message cache (Thunderbird-style) — Helpfiles/Cache/<acct>/<folder>
#       keeps each .eml once; refresh only downloads NEW uids + re-syncs flags
#       (_fetch_folder_cached), so updating an inbox is fast. Toggle + Clear in
#       the same dialog; cache_enabled in settings. Read-only, UIDVALIDITY-safe.
#   [x] Paging — a "Load N older messages" row grows _fetch_limit by FETCH_LIMIT
#       and re-fetches (read-only); resets per folder. (Lazy body fetch still
#       open as a perf optimization, but not required.)
#
#   --- COMPOSING / REPLYING (Issu's feature requests) -----------------------
#   [x] While composing a reply, the RECEIVED message shows in a side box
#       (left, read-only) next to a CLEAN answer box (right). "Quote original
#       on send" checkbox (default OFF) appends a single-round quote.
#   [x] Inline "answer under their text" mode (Smart Reply, DEL 06b):
#       write directly under each paragraph; the one you leave auto-hides and
#       the one you enter expands (answers preserved). Navigate by click OR
#       Ctrl+Down / Ctrl+Up (no mouse), and collapsed rows open on focus.
#       (Possible later polish: caret-position-driven switching while typing.)
#   [ ] Keep only LAST ROUND as the base — never a growing multi-level quote
#       chain. Just my started reply + the single message I'm replying to.
#       (Already true in Smart Reply _collect_body + reading pane "latest
#        round only"; keep this guarantee when wiring real send.)
#   [ ] Reader checkbox (DEFAULT OFF) to include the previous text or show
#       only the latest. (Already present: "Include previous round" in Smart
#        Reply + "Show full thread history" in the reading pane — keep both.)
#
#   --- ATTACHMENTS (Issu's feature requests) --------------------------------
#   [x] Auto-save attachments from SELECTED senders to either a common default
#       folder OR a sender-specific sub-folder. Per-sender rule list in
#       Helpfiles/Accounts/autosave_rules.json; editor under Accounts menu;
#       runs on every fetch (off the GUI thread), idempotent.
#   [x] Rename / "prefix" saved files with rule tokens {YYYY-MM} {YYYY-MM-DD}
#       {sender} {account} {subject}. e.g. "GELF---Sandtorp 32---{YYYY-MM}---"
#       → "GELF---Sandtorp 32---2026-05---<originalname>.pdf" (uses the EMAIL's
#       own month via msg["_dt"], not today's). See _autosave_run/_expand_prefix.
#   [x] Open attachments / PDFs in a POPUP — reading-pane attachment names are
#       clickable. Images open in an in-app preview popup (_show_image_popup,
#       scaled to fit); everything else opens in the OS default viewer
#       (separate window), never inside the main pane. Compose has 📎 Attach.
#
#   --- SENDING: SCHEDULE + UNDO (DEL 04d/06c/09b) ---------------------------
#   [x] Send later / schedule — every outgoing message goes through an OUTBOX
#       queue (Helpfiles/Accounts/outbox.json) with a send_at timestamp. The
#       compose window has "🕒 Send later…" (in N minutes / hours / a specific
#       date+time). File → Outbox lists everything queued: send now, edit the
#       time, or cancel back to a draft. Survives a restart (queue is on disk);
#       anything whose time passed while the program was closed is sent on the
#       next scheduler tick. NOTE: the program must be running at send time.
#   [x] "✉🔒 Send and save" (DEL 09p) — a THIRD Send button beside Send and
#       Send later. Sends through the same outbox with the same undo window,
#       and PROTECTS the copy in Sent: a delete taking several messages at
#       once skips it silently (the status bar says how many), and deleting it
#       on its own asks first, with the safe answer on both Enter and Escape.
#       The mark rides in the message (X-Freemail-Protected header), so it
#       survives a reinstall, another machine and any rule that moves the
#       mail; protected.json additionally carries mail protected by hand
#       (right-click → 🔒 Protect / 🔓 Unprotect) and the deliberate releases.
#       A padlock shows in the list and in the reading pane.
#   [x] Undo send — DEFAULT ON, default 10 s, adjustable up to 10 minutes
#       (Tools → Sending). Uses the same outbox. A small toast appears in the
#       bottom-right with a big Cancel button — one click, no dialog, no
#       confirmation. Optional live countdown (DEFAULT OFF). Cancelling
#       reopens the compose window with everything intact.
#
#   --- COMPOSE QUALITY-OF-LIFE (DEL 04d/06) ---------------------------------
#   [x] Signatures per account, shareable — named signatures in
#       signatures.json; each account is ASSIGNED one, and several accounts may
#       point at the SAME signature (edit once, changes everywhere). Inserted
#       after a "-- " separator and swapped live when you change From:.
#   [x] Crash-safe drafts — every compose/Smart Reply window autosaves to
#       Helpfiles/Drafts/ a few seconds after you stop typing, so nothing is
#       lost on a crash or a power cut. On start-up any leftover drafts are
#       offered for restore. A sent message's draft is kept a short while
#       (Tools → Sending, default 10 min) and then deleted automatically.
#   [x] Forgotten-attachment warning — if the text says you are attaching
#       something (attach/attached/enclosed/bifogar/bifogat/bilaga, or
#       "skickar" + "fil" on the same line) but nothing is attached, you get
#       one Yes/No question before the message leaves.
#   [x] Templates — reusable canned texts (templates.json, Tools → Templates)
#       inserted from the compose toolbar; same {tokens} as the autosave rules.
#
#   --- MAILBOX TOOLS (DEL 04e/09b) ------------------------------------------
#   [x] Search across ALL folders (and optionally all accounts) at once — the
#       search box has a scope selector: This folder / All folders / All
#       folders + all accounts / All except… . Wide scopes run a real read-only
#       IMAP SEARCH on a worker thread and show a merged, folder-labelled
#       result list.
#   [x] AUTO-READ FOLDERS (Issu 2026-08-17) — right-click a folder → "Mail that
#       lands here reads itself". Marked read on arrival, no notification, no
#       unread badge, and (with Server changes on) the \Seen flag set on Gmail
#       too. A property of the FOLDER, so every rule aiming at it and every
#       move you make by hand behave alike. cfg auto_read_folders.
#   [x] THE "FASTNAR I UPDATING/LOADING" BUG, and why the filters looked asleep
#       (Issu 2026-08-17, found in his own Freemail.log). One account timed out
#       22 times in two hours, always at the 30 s socket timeout and usually
#       TWICE per attempt — the cached fetch stalled and the code immediately
#       re-tried a FULL fetch over the same dead socket. In the All Accounts
#       view a refresh joins every account before drawing, so that was a solid
#       minute of "updating…" each time. And because the auto-check is every
#       60 s, each refresh was superseded before it finished — and `done()`
#       dropped superseded results wholesale, INCLUDING the filter run that
#       only ever happens inside _apply_messages. Result: between 07:15 and
#       08:05 not one rule ran, and nothing was filed until he opened a folder
#       by hand. Three fixes: rules now run even on a superseded fetch (the
#       list is still not drawn); a stalled fetch is not re-tried as a full
#       fetch; and a stalling account is stood down for 2–10 minutes for
#       AUTOMATIC passes only, keeping its mail on screen and saying so in the
#       status line.
#   [x] "All except…" (Issu 2026-08-17) — the widest search there is, MINUS the
#       folders and whole accounts you have told it to leave out in
#       Tools → "Search: what to leave out…". Unlike the other wide scopes it
#       also walks your OWN labels, which is the whole point: leaving out
#       "0---Frakt & kvitto" is only meaningful if that folder would otherwise
#       have been searched.
#   [x] Mail filters — rule list in filters.json (Tools → Mail filters),
#       matched against EVERY fetched message in EVERY folder. Phase-1-safe
#       actions only: colour-mark, mark read locally, hide from the list,
#       star locally, snooze, notify / never notify. Server-side moves stay
#       Phase 2.
#   [x] Snooze — CHANGED 2026-11-24 (Issu: "det ska inte gömmas några
#       meddelanden ... men efter X tid får jag en notis"). Snooze no longer
#       hides anything: the mail stays as it is and a pop-up comes at the time
#       you pick - minutes to YEARS (1 week / 2 months / 1 year presets, "In N
#       <unit>", or an exact date). It is a one-shot follow-up of kind "snooze"
#       (followups.json); old snooze.json entries are converted on start-up.
#       Local only, nothing on Gmail is touched.
#   [x] New-mail notification — a bottom-right toast (and optional beep) when
#       a background auto-check finds mail you have not seen. Click it to jump
#       straight to the message. Tools → Notifications.
#   [x] Save as PDF — any message can be written to a real PDF file straight
#       from the reading pane (built-in writer, no external dependency).
#   [x] Backup — Tools → Backup now: one .zip of every setting, rule,
#       signature, template, contact and draft (app passwords stay DPAPI-
#       encrypted inside it). Optional automatic backup on exit, keeping the
#       last N backups. Restore is a guided dialog.
#
#   --- SAFETY / ANTI-JUNK (DEL 04e/09b) -------------------------------------
#   [x] Phishing warning — every opened message is analysed for the classic
#       tells: display name pretending to be another address, Reply-To on a
#       different domain than From, link TEXT showing one domain while the
#       link GOES to another, raw-IP and punycode (xn--) links, dangerous or
#       double-extension attachments, and urgency/credential wording near a
#       link. A red banner explains exactly what was found; nothing is hidden
#       from you and nothing is deleted.
#   [x] Unsubscribe — reads the List-Unsubscribe header (and, failing that,
#       finds an unsubscribe link in the body) and offers FOUR choices:
#         1. Unsubscribe only
#         2. Unsubscribe + block sender (local block list)
#         3. Unsubscribe + mark as spam (local in Phase 1)
#         4. Unsubscribe + create my own filter rule (opens the rule editor
#            prefilled with this sender)
#       (DEL 04e2, 2026-08-29) …plus RFC 8058 one-click (one POST, no page and
#       no browser at all), a built-in mini web view for the pages that do
#       need clicking — no JavaScript, no images, no cookies kept, nothing
#       sent until you press the page's own button — a per-rule "unsubscribe
#       from what this rule catches" action, and a log so a list is never
#       asked to stop twice.
#       mailto: unsubscribes are sent through the outbox (additive, safe);
#       http(s) unsubscribes always show you the exact URL and wait for your
#       confirmation before the browser is opened.
#   [x] Default mail client on Windows — Tools → Set as default mail client
#       registers a mailto: handler under HKEY_CURRENT_USER (nothing outside
#       your own user account) and then opens Windows' Default apps page,
#       where YOU do the final confirmation — Windows 11 does not allow a
#       program to take the default over by itself. "Unregister" removes it
#       again. Starting F(re)email with a mailto: URL opens a prefilled
#       compose window.
#
#   --- TAGS (DEL 04k) -------------------------------------------------------
#   [x] Thunderbird-style tags: your own mark on ONE message, with a name,
#       colour and icon. Nine defaults (Important, Work, Personal, To do,
#       Later, Bill, Shipping, Keep, Junk); press 1-9 on the selected message
#       or use 🏷 Tags… in the reading pane. Icons show in the list, the
#       first tag's colour tints the row, and a hand-applied tag beats a
#       filter colour (you meant it personally). View → Tags to edit them.
#       Local only: Gmail labels are a server write nobody asked for, and a
#       tag you can lose to a bad sync is worse than one in a file you own.
#       NOTE what already existed and is NOT this: contact colours (by
#       SENDER), filter colours (by RULE), star/priority/spam (fixed flags).
#
#   --- AUTOMATIC DATED FOLDERS (DEL 04l) ------------------------------------
#   [x] Folder plans: "on the 3rd of every month, make 08-Augusti inside
#       D:\Frakt and move last month's files into it" (Accounts → Automatic
#       folders). Name tokens {MM} {M} {YYYY} {YY} {MonthName} {Q} {DD};
#       every N months; move last month / this month / an exact date range.
#       Month names live in the PLAN, so the folders can be Swedish while the
#       program stays English.
#   [x] A file's date comes from a date in its NAME first (your own prefix
#       rules put one there) and only then from its timestamp — copying files
#       between drives rewrites timestamps, but the name is what you meant.
#   [x] Preview shows exactly what would be created and moved before anything
#       happens; files are never overwritten (clashes get "(1)") and
#       sub-folders are never moved. Runs once per period, and catches up if
#       the computer was off on the day.
#   [x] FILES ON DISK ONLY. Moving MAIL between folders on Gmail is a server
#       write and is not done automatically anywhere — see DEL 04h.
#
#   --- FOLLOW-UPS: "I am not finished with this mail" (DEL 04j) -------------
#   Deliberately NOT the calendar (which is about events at a time) and NOT
#   snooze (which HIDES a message). A follow-up leaves the mail where it is
#   and keeps coming back to poke you until you have dealt with it.
#   [x] "🔔 Remind me…" in the reading pane marks a message as unfinished,
#       with an optional note about what is actually left to do.
#   [x] TWO independent intervals, which is what was asked for: the wait
#       before the FIRST reminder (in 1 h / 3 h / tomorrow / 3 days / a week
#       / an exact time) is set separately from the rhythm AFTERWARDS (once
#       only / 30 min / hourly / 3-hourly / daily / 2 days / weekly).
#   [x] THREE ways for it to end: only N times, never after a given date, or
#       neither — in which case it nags until you press "Stop reminding" in
#       the popup itself.
#   [x] THE LAST REMINDER LOOKS MARKEDLY DIFFERENT: different colour, thicker
#       border, "⚠ LAST REMINDER" heading and a sentence saying in as many
#       words that you will not hear about this again. Being told it is the
#       final one is the entire reason for setting an end, so it must not
#       look like the others. It also swaps "Stop reminding" for "Keep
#       reminding me", which drops the ending and carries on until stopped.
#   [x] Virtual "Follow-ups" folder listing everything outstanding, sorted by
#       when it fires next, with the about-to-end ones starred; and a 🔔 in
#       front of the message itself in the ordinary list.
#   [x] Catch-up without a flood: if the program was closed for three days,
#       a daily reminder fires ONCE and then continues on schedule, instead
#       of firing three times in a row.
#   [x] FLOAT TO THE TOP (2026-11-23, Issu: "kolla med dem om drygt 2 månader,
#       om de inte har återkommit"). A follow-up can ALSO bring the mail back
#       when its time comes: the mail turns UNREAD (local only, like the "kept
#       unread" senders - nothing is ever pushed to Gmail as unread), gets a
#       🔔 and is lifted to the TOP of its folder list whatever the sort order
#       is, and STAYS there until "✔ Done" is pressed (reading pane, reminder
#       popup, Follow-ups folder or right-click) or a NEW reminder is set on
#       it (that replaces the old one and the mail goes back to its place).
#       Item fields: float (the choice), surfaced (when it came up), resolved
#       (Done pressed). "In 1 / 2 / 3 months" (09:00) were added for the long
#       waits. The follow-up data lives only on the PC (followups.json).
#
#   --- NOTES: local mail to myself (DEL 04g) --------------------------------
#   [x] Notes — a "mail to myself" that never goes near a server. 🗒 New Note
#       (Ctrl+T) opens the ordinary compose window with the sending machinery
#       replaced by "write a file": signature, crash-safe draft and
#       attachments all work, but nothing can leave the machine.
#   [x] Stored as real .eml files in a folder you choose (File → Change the
#       Notes folder; default Helpfiles/Notes). .eml because notes must
#       survive this program — open them in Thunderbird, back them up, read
#       them in Notepad. The FOLDER is the truth: there is no index that can
#       drift, so notes copied in or deleted outside simply appear or vanish.
#   [x] "🗒 Save to Notes" in the reading pane copies any received message —
#       attachments and all — into that folder. This is the "forward someone
#       else's mail to my own pile" case, except nothing is forwarded
#       anywhere: the copy is written straight to disk and survives whatever
#       later happens to the original on the server.
#   [x] Virtual "Notes" folder in the sidebar, sorted and searched like any
#       other. Deleting a note deletes THAT FILE — a local file you made,
#       never anything on a server.
#
#   [x] Notes review pass — three gaps found and closed after the feature was
#       first written:
#         • Delete (button or Del key) on a note only HID it, leaving the file
#           on disk so it came back the moment you left the folder. Delete now
#           removes the file — notes are the one thing here Delete really
#           deletes, and never anything on a server.
#         • The wide search never looked at Notes: they are on disk, so no
#           IMAP SEARCH can reach them, and "All folders" was quietly skipping
#           the folder you are surest about (_notes_search).
#         • A mail filter with "hide" could swallow a note. Rules may colour
#           or star a note but can never hide it — something you deliberately
#           saved to your own disk must not vanish behind a rule meant for
#           incoming mail.
#
#   --- "CONTROL": KEEP ON SERVER / DELETE AFTER N DAYS? (DEL 04h) -----------
#   The familiar "leave a copy on the server, remove it after 14 days" is a
#   POP3 setting. POP3 DOWNLOADS mail to your machine, so the server copy is a
#   leftover you must decide about. This program speaks IMAP, where the
#   mailbox on the server IS the mail and what you see is a view of it —
#   there is no separate local copy, so the question has nothing to refer to.
#   [x] Local archive — the real want behind that question is OWNERSHIP: a
#       copy that is mine whatever happens to the account. File → Local
#       archive writes faithful .eml copies (the ORIGINAL bytes as the server
#       sent them, kept in msg["_raw"]) into account/folder/YYYY-MM
#       sub-folders, optionally automatic on every fetch (default OFF — it
#       uses your disk, so it is your call). Idempotent on Message-ID, so a
#       message is written once however often it is re-fetched.
#   [ ] NOT OFFERED ON PURPOSE: "delete from the server after N days". A
#       timer that deletes mail while nobody is watching is how mail is lost
#       for good, and on Gmail it is sharper still — one message carries
#       several labels, so a rule aimed at Sent also strips it from the Inbox
#       and All Mail. If Phase 2 is ever unlocked, deletion stays a manual
#       act with a confirmation naming exactly what disappears. Never a timer.
#
#   --- THE GMAIL SINGLE-COPY TRAP (read before touching Phase 2) ------------
#   Gmail does not store folders; it stores ONE message with labels. A mail
#   you send to yourself is therefore a single message wearing BOTH the Inbox
#   and the Sent label — not two copies. Trash it "from Sent" and it leaves
#   the Inbox too, because there was only ever one of it. Thunderbird shows
#   the same message twice and makes this look like a program bug; it is not.
#   [x] Messages to yourself now say so in the reading pane, in plain words,
#       with a pointer to Notes as the safe alternative (_is_self_message).
#   [ ] PHASE-2 HARD REQUIREMENT: when server-side delete is unlocked, a
#       message that is its own sender MUST get an explicit, separate
#       confirmation naming every label/folder it would disappear from. No
#       silent "move to Trash" for self-messages, ever. Same for any message
#       carrying more than one Gmail label.
#
#   --- PHASE 2: server-side changes (DEL 04i) -------------------------------
#   Issu asked for this explicitly ("I want to delete via the program too —
#   Thunderbird can delete on Google as well"). Deleting mail from your own
#   client is ordinary; the care goes into HOW.
#   [x] Single explicit "allow server-side changes" switch, DEFAULT OFF
#       (Tools → Server changes). A fresh install, or a restored backup,
#       cannot delete on the server.
#   [x] Delete → UID MOVE to [Gmail]/Trash, where Gmail keeps it 30 days.
#       Fallback COPY + \Deleted + UID EXPUNGE (RFC 4315 — limited to that
#       one UID). NEVER a bare EXPUNGE, which would also erase messages
#       another client flagged days ago.
#   [x] Delete FROM the Trash = PERMANENT (DEL 04s, Issu's request): a real
#       UID EXPUNGE of that one message, but ONLY after a hidden local copy is
#       written to Helpfiles/Deleted (kept deleted_keep_days, default 30) that
#       the "Deleted" virtual folder shows and can restore (IMAP APPEND) or
#       forward. ONE batch confirmation, never one popup per message. Still
#       never a bare EXPUNGE; still gated behind Server changes.
#   [x] The confirmation names every Gmail LABEL the message would vanish
#       from (X-GM-LABELS is parsed into msg["_labels"]), with a louder
#       warning for self-addressed mail — the hard requirement written down
#       before this was built, now met.
#   [x] Archives the message locally first, when auto-archive is on, so a
#       deleted message still exists as a file you own.
#   [x] Never automatic: no filter action, rule or timer can reach this code.
#       Audited — exactly ONE readonly=False in the whole program, one caller
#       chain, and it starts at a human clicking Delete.
#   NOTE: the IMAP write path itself could NOT be tested here — that needs a
#       real account, and testing it means deleting real mail. The gating,
#       the label/impact logic and the confirmation text ARE tested. Try it
#       first on a throwaway message.
#   [ ] Mark-as-read / unread on server, star, spam, move-to-folder.
#   [ ] Labels / tags panel (apply/remove Gmail labels).
#   [ ] Real server-side spam/block once wanted (today the Unsubscribe
#       dialog's "spam" and "block" choices are local only).
#   [ ] STILL REFUSED BY DESIGN: any timed or rule-driven deletion. See the
#       end of DEL 04h for why.
#
#   --- RULES PANEL + HIDE PART OF A MESSAGE (DEL 04t) ------------------------
#   [x] A small collapsible panel at the TOP of every opened message that says,
#       at a glance, which rules act on it — split into two clearly-labelled
#       columns: "For THIS message" (its own tags, follow-up, snooze, applied
#       filters, hidden parts) and "For THIS sender" (the standing filter /
#       attachment / spam / trust rules that hit every mail they send). Each
#       column has quick buttons (Tag…, Remind me…, Snooze / Edit sender
#       rules…, All from sender). Default expanded (Issu's request); the
#       ▾/▸ twisty state is remembered in cfg["rules_panel_expanded"].
#   [x] Hide / unhide PART of a message: the body is now a read-only Text, so
#       you can select a piece you have dealt with and press "✂ Hide selection"
#       to fold it away. A hidden piece shows as an inline "⟨hidden — click to
#       show⟩" marker; "↺ Show all hidden" brings everything back. 100% LOCAL
#       and reversible — the text on Gmail is never touched, nothing deleted.
#       Persisted per message (Accounts/hidden_parts.json, keyed by _msg_key),
#       so a folded mail stays folded across a re-fetch and restart.
#
#   --- READING-PANE TOOLBAR + FIXES (DEL 04t, 2nd pass) ---------------------
#   [x] The reader row now has three remembered toggles: "Show full thread
#       history", "Rules acting on this mail", "Message actions" — the last two
#       OFF by default, so the message is what you see. Rules panel and the
#       action buttons (Save as PDF, Make appointment, …) now render at the TOP
#       of the message, and the actions are split across two rows.
#   [x] The reading pane reopens the LAST message you had open on start-up
#       (cfg["last_msg_key"], matched by _msg_key).
#   [x] Deleting a COLLAPSED conversation row asks "all N or just the newest?"
#       instead of silently deleting one and letting the sibling take its place.
#   [x] Right-click a message in Trash → "Restore from Trash (back to Inbox)".
#   [x] "Rules for sender…" is taller, matches attachments by substring OR
#       wildcard (*.png), and can file into a Custom folder (e.g.
#       0---Frakt & Kvitto/{YYYY-MM}) with the base folder settable inline.
#       "All from sender" relabelled "Show all from this sender (just lists)".
#   [x] SASH MEMORY FIX: the reading-pane divider is now saved when you DRAG it
#       (bind on the paned windows + a final capture on exit), not only when the
#       whole window is resized — so it no longer snaps back to "one message".
#   [x] CONNECTION REUSE (DEL 04v): one pooled IMAP connection per account,
#       behind a per-account lock, reused across fetch / unread-count / quota.
#       That reuses the login AND caps each account at a single connection, so
#       the "Too many simultaneous connections" stalls between folders should be
#       gone. Stale connections are detected with NOOP and replaced; a 30 s
#       socket timeout stops a dead one hanging the lock. cfg["imap_reuse"]
#       (default ON) can turn it off. Write paths (delete/move) are unchanged.
#       NOTE: verified by unit tests with a fake connection; the LIVE speed-up
#       still needs Issu's real Gmail to confirm.
#   [x] NO-FLASH READ: turning a mail read no longer rebuilds the whole list
#       (that was the flash Issu saw). _apply_read / _ctx_mark_read now recolour
#       just that row in place via _repaint_row_read (bg + subject dot/font +
#       correspondent). Clicking a row also stopped doing a full _render_msg_list
#       — _repaint_selection alone recolours. Row entries are now 4-item lists
#       [msg, widgets, bg, meta] with a mutable bg so hover/selection stay right.
#   [x] CLICKABLE LINKS: http/https URLs in the message body are now clickable
#       (open through _open_url, so the right browser profile still applies) —
#       no more copy-pasting a link out of a plain message (DEL 04w).
#   --- MAIL FILTERS, richer (DEL 04x) ---------------------------------------
#   [x] Taller Mail-filters dialog (Save/New/Delete row fully visible).
#   [x] Each text criterion (From / Subject / Body) has a tick-to-use box AND a
#       match operator: contains / doesn't contain / is / is not / begins with /
#       ends with. Unticked = the line is ignored. (_op_match, op_from/subject/
#       body on the filter.)
#   [x] "Account is" is a dropdown of your accounts + "(any account)".
#   [x] "Create mail filter from this message…" (right-click, and the Mail
#       filters… button on Rules-for-sender) pre-fills sender / subject /
#       account, each ticked but editable.
#   [x] Auto vs Only-manual per rule (run_on_fetch): Auto runs on every check
#       AND on a manual run; Only-manual runs solely via "Run filters now".
#       _apply_filters/_apply_local_state take manual=; _run_filters_now().
#   [x] Reorderable rule list — ⤒ ↑ ↓ ⤓ buttons under the list (filters run
#       top-to-bottom, so order matters). Persisted immediately.
#   [x] Filter log — "Filter log…" button shows every rule action this session
#       (newest first, deduped per rule+message), and the same lines go to
#       Freemail.log (the rule-activity logging Issu wanted earlier).
#   --- SERVER-SIDE FILTER ACTIONS (DEL 04y) — Issu opted in 2026-07-26 --------
#   [x] Filters can now act on Gmail itself (only when Server changes is ON):
#       Move to folder/label (creates it if missing), Delete → Gmail Trash
#       (recoverable; a hidden local copy is saved first so it stays in the
#       Deleted folder and can be restored), Mark read on Gmail (adds \Seen),
#       Star on Gmail (adds \Flagged). All additive/recoverable.
#   [x] Auto-trash NEVER touches a message you sent to yourself (Gmail's one-
#       message-many-labels trap) — it is skipped and logged. Permanent erase
#       stays a manual, one-at-a-time action; no filter can expunge.
#   [x] Server actions run off the GUI thread, deduped per (rule, message) so a
#       re-fetch can't repeat them, and every one is written to the filter log +
#       Freemail.log. Saving a rule with a Gmail action offers to turn Server
#       changes on inline.
#   --- MULTI-ROW CONDITIONS + MANUAL MOVE (DEL 04z) -------------------------
#   [x] Thunderbird-style conditions: pick Match ALL / ANY / every-message,
#       then any number of condition rows — each [field ▾ (From/Account/Subject/
#       Body/Folder)] [operator ▾] [value] with + / − to add or remove. Stored
#       as conditions[] + match_mode; old flat-field filters auto-migrate on
#       load and keep working. An empty rule now matches NOTHING (safer).
#   [x] Right-click a message → "Move to folder…" — pick an existing label or
#       type a new one; moves it on Gmail (same engine as the filter move).
#   --- FILTER RESTS DONE (DEL 04z2) -----------------------------------------
#   [x] "Body has" full-message word picker: in the filter editor, "📄 Pick
#       words from the open message…" opens the selected message's full text;
#       highlight words (or double-click one), choose field+operator, and it
#       becomes a live condition row. _body_word_picker().
#   [x] Run-on-a-chosen-folder: each rule has "Only in folders:" (comma-list,
#       empty = everywhere; quick-add buttons). Gated in _filter_matches via
#       _filter_folder_ok — a scope on top of the conditions, not a match.
#   [x] Apply-when triggers: "Also run [ ] when I archive a message  [ ] right
#       after a message is sent" per rule (run_on_archive / run_on_sent). The
#       engine takes trigger= (fetch/manual/archive/sent, _filter_runs_on);
#       hooks in _archive_out_of_inbox and the outbox send-success path call
#       _run_filters_on(). Server actions stay gated by "Server changes" (no
#       new risk); a sent message has no UID so its server actions no-op.
#       "Auto / Only-manual" already covered the periodic case.
#   --- BADGE COLOUR + FILTER SCROLL-TO-TOP (DEL 04z3) ------------------------
#   [x] Taskbar unread badge is now two-colour: RED when there is genuine new
#       mail, BLUE-PURPLE when the only unread left is "kept" (always-unread
#       senders you've already read). The number still shows the total. Kept
#       mail is \Seen on Gmail, so genuine = _folder_unread − _folder_kept;
#       _unread_kind() decides, _reconcile_folder_badge() tracks kept,
#       _make_badged_icon_file(colour_key) / _apply_taskbar_icon(count,colour).
#   [x] Clicking a SHOW/quick-filter (Unread/Starred/Files/Tagged/Follow-up)
#       jumps the message list back to the top (_scroll_msg_list_top), so the
#       first matches are visible instead of staying scrolled down.
#   --- ALWAYS-UNREAD MANAGEMENT + "MARK AS UNREAD" FILTER (DEL 04z4) ---------
#   [x] "Mark as unread" is now a LOCAL filter action (action_unread) — the
#       Thunderbird parity Issu missed. On an auto-run rule it keeps matching
#       mail standing out. (Local actions: colour / read / UNREAD / star / hide
#       / snooze / notify / tag. "Move to folder" and "Delete→Trash" live under
#       "on Gmail" because Freemail's folders ARE Gmail's — there is no separate
#       local folder store; "Hide from the message list" is the local delete.)
#   [x] Always-unread senders are now MANAGED in Tools → "Blocked / trusted /
#       kept-unread senders…": the always_unread list is shown (● icon) with a
#       "Keep unread…" add button + right-click-message shortcut noted. (Before,
#       the dialog only showed blocked/spam/trusted, so the always-unread list
#       Issu built via right-click was invisible — "var ställer jag in?".)
#   [x] Blue-purple badge now PERSISTS: _refresh_unread_counts adds the kept
#       (always-unread, read → \Seen so invisible to IMAP STATUS) Inbox count
#       back on top of the server UNSEEN numbers, so the purple badge no longer
#       vanishes a moment after it appears ("jag har inte sett något lila än").
#   [ ] STILL OPEN: permanently-deleted Trash mail can reappear from the local
#       cache until pruned (should improve now that expunge is less likely to
#       fail on the connection limit, but not fully fixed). Rule/move logging to
#       Freemail.log is also not done yet.
#
#   --- ATTACHMENTS: SAVE / SAVE ALL / OPEN WITH (DEL 04u) --------------------
#   [x] Left-click an attachment still opens it (image popup / OS default).
#   [x] "💾 Save all…" button next to the attachment list writes every file to
#       a folder you pick, never overwriting (adds " (2)", " (3)" …).
#   [x] Right-click an attachment → Save as… / Save all… / Open with… — pick
#       any program (.exe or a .py, run through pythonw) and it is remembered
#       PER FILE EXTENSION, so e.g. a .png offers "Open with QR-code-text" as a
#       one-click choice from then on. cfg["open_with_apps"], "Forget…" clears.
#
#   --- CALENDAR (DEL 04f/06d/09d) -------------------------------------------
#   [x] Calendar with reminders, Thunderbird-style. Own store
#       (Accounts/calendar.json), three views — Month (overview), Week (one
#       column per day) and Agenda (the next 60 days as a flat list) — with
#       ◀ / Today / ▶, arrow keys, click a day to select, double-click to
#       create. Ctrl+K or the 📅 toolbar button opens it; it is a normal
#       window, not a modal, so mail stays readable beside it.
#   [x] Repeating events — daily / weekly / monthly / yearly, every Nth time,
#       weekly on chosen weekdays, ending never / after N times / on a date.
#       Month-end is clamped the way every calendar does it (31 Jan + 1 month
#       = 28 Feb).
#   [x] Reminders — several per event (at the time, 5/15/30 min, 1/2 h,
#       1/2 days, 1 week). A popup appears bottom-right with Snooze 5 min /
#       15 min / 1 h and Dismiss. Already-shown reminders are remembered, so
#       a restart does not repeat them; one that fell due while the program
#       was closed is still shown if it is less than an hour old.
#   [x] .ics import/export — a meeting invitation in a mail (text/calendar
#       part OR an .ics attachment) gets a "📅 Add to calendar" button in the
#       reading pane; any other message can be turned into an appointment
#       with "📅 Make appointment". Whole .ics files can be imported and the
#       calendar exported, with UID-based de-duplication so re-importing the
#       same invitation does not double it.
#   NOTE: reminders need the program to be RUNNING, exactly like scheduled
#       send. There is no background service and no CalDAV/Google sync —
#       syncing would mean writing to a server, which Phase 1 forbids.
#   --- EVENT EDITOR, FRIENDLIER (DEL 04f2) ----------------------------------
#   [x] End is OPTIONAL: "Set an end" checkbox, OFF by default (most people only
#       need the start). Greys out the end time + end date; _fmt_event_time then
#       shows just the start ("10:00", not "10:00–11:00"). Stored has_end.
#   [x] Date fields have an almanac: a 📅 button opens a small month calendar
#       (_pick_date) on Date and End date; click a day to fill YYYY-MM-DD.
#   [x] Repeating + accelerating reminders: "…and keep reminding me — starting
#       [1 day before ▾] every [3 hours ▾]  [ ] getting more frequent (snowball)".
#       Stored as reminder_series{enabled,lead_min,interval_min,accelerate};
#       _reminder_series_offsets generates the fire-times (accelerate = gap
#       doubles every two reminders moving away from the event), merged with the
#       fixed ticks by _event_reminder_minutes and fired by _due_reminders. A
#       live preview spells out exactly when it will fire.
#   [x] Auto date/time IN the title: "Add date & time to the title" checkbox
#       (default ON) + format (name "Friday 10.00 (14 August)" / numeric "14/08
#       (Friday) 10.00"). Type just "Doctor" → stored "Doctor, Friday 10.00 (14
#       August)". Clean base kept in title_base so editing never doubles it;
#       skipped for repeating events (one title, many dates). English names per
#       the English-only rule (_FULL_WEEKDAYS/_FULL_MONTHS, _event_title_suffix).
#   --- CALENDAR BUGFIX + ALERTS + QUICK TIMER (DEL 04f3) ---------------------
#   [x] BUGFIX: the calendar showed only bare coloured bars, no event text
#       ("bara en ljusblå rad"). _event_chip built the text label as a child of
#       the CELL but packed it in_= the colour frame; the colour frame, created
#       after it, sat on top in the sibling stacking order and hid the text.
#       The label is now a child of the colour frame → it draws on top.
#   [x] Reminder ALERTS: reminders were silent and never flashed. Each event has
#       an alert style (silent / sound / insistent) — _show_reminder now calls
#       _alert_now → a taskbar flash + beeps, and "insistent" ESCALATES the
#       nearer the event (1 beep far out … 8 at the event time; _alert_beeps).
#       The popup also shows the ACTUAL time left, not the configured offset.
#   [x] QUICK TIMER ("kortlarm"): Calendar menu → "⏱ Quick timer…" sets a
#       countdown (stand up / oven off) with one-click 5/10/20/30m·1/2h presets
#       + a label; persisted in timers.json so it survives a restart (re-armed
#       on start-up, fires once if it lapsed while closed) and fires an
#       insistent reminder. _start/_arm/_fire/_cancel_timer, _quick_timer_dialog.
#
#   --- REVIEW-PASS FIXES (do not re-break these) ----------------------------
#   [x] A queued message used to exist BOTH in the outbox and as an unsent
#       draft, so the start-up restore could reopen it and you could send the
#       same mail twice. A draft is now marked "queued" when the outbox takes
#       it, "sent" only when SMTP confirms, and the restore skips both.
#   [x] Attachments of a scheduled message are COPIED into Helpfiles/Outbox.
#       A mail scheduled for tomorrow used to reference the original path, so
#       a temp file or a tidied-up download meant it went out without its
#       attachment, hours later, silently. Copies are removed after send or
#       cancel, and orphans are pruned at start-up.
#   [x] Snooze reused the send-later picker and therefore said "Send this
#       message later" / "Schedule". The picker now takes a purpose.
#   [x] Multi-day events (a two-week holiday) only appeared on their FIRST
#       day in the month and week grids. _events_by_day now spreads an event
#       over every day it covers, marking days 2+ with "→", while the agenda
#       still lists it once. A one-hour meeting still occupies one day.
#   [x] Stacked toasts (two reminders at the same minute, several new-mail
#       notifications) computed their offset from winfo_height(), which is 1
#       for a window Tk has not mapped yet — so they stacked 9 px apart, i.e.
#       still on top of each other. They now use their own known height.
#   [x] Snoozed mail never came back when auto-check was OFF (the default),
#       because the due-check hung off the auto-check poll. It now runs on the
#       always-on calendar ticker and redraws the list, so a message that
#       "comes back by itself" actually does.
#   [x] Restoring a backup was undone on exit: the running program wrote its
#       old in-memory settings straight back over the restored settings.json.
#       A restore now suppresses that save (_settings_restored).
#   [x] Save-as-PDF turned every curly quote, en/em dash, ellipsis and bullet
#       into "?" — the fonts are WinAnsi, whose 0x80–0x9F punctuation is NOT
#       in latin-1, which is what the encoder was using. Real mail is full of
#       exactly those characters.
#   [x] The phishing scan re-ran over the whole HTML on every reading-pane
#       redraw (i.e. every click); the verdict is now cached on the message.
#       _events_by_day looked back a fixed 370 days on every calendar render;
#       it now looks back only as far as the longest event needs.
#
#   --- SAFETY / CONVENIENCE ADDED IN THE SAME PASS ---------------------------
#   [x] Trusted senders — the phishing banner has "✔ Not phishing — trust
#       this sender". A warning you cannot answer is one you learn to ignore,
#       so a recurring false positive can be silenced per SENDER ADDRESS (not
#       per domain). Warnings about executable or disguised attachments are
#       NEVER suppressed: if a trusted sender's account is taken over, that
#       is precisely the warning that matters. Undo in Tools → Blocked &
#       trusted senders.
#   [x] Attachment size — the compose window shows the total and what it will
#       weigh once base64-encoded, amber near Gmail's 25 MB limit and red
#       over it. Checked when you press Send (not at SMTP time), because with
#       "send later" the rejection would otherwise turn up hours later. A
#       file that has disappeared since you attached it is reported too.
#
#   --- SMART REPLY PARITY + WHOLE-MAILBOX SWEEP (DEL 05b/04-sweep, 2026-08-01) -
#   [x] Compose and Smart Reply now SHARE their recipient handling: the new
#       _RecipientFields mixin (DEL 05b) owns the 📖 address-book picker and the
#       address sanitiser, so a fix can never again land in one window only.
#       Smart Reply gained Cc: + Bcc: rows, both pickers, the "🔒 Send to me
#       only" privacy switch, the address cleaning and the contact auto-save;
#       its Send and Send-later are one _gather()/_queue() path instead of two
#       near-copies (they used to differ).
#   [x] WHOLE-MAILBOX SWEEP — "Run filters now" only ever saw the ~40 loaded
#       messages per folder, which is useless for "delete every mail this
#       sender has ever sent me". Tools → "Clean the whole mailbox with a
#       rule…" (also a 🧹 button in the filter editor and in the 🚫 Junk filter
#       dialog) asks GMAIL for everything ONE rule matches:
#         • _sweep_plan(flt) works out the IMAP search — FROM/SUBJECT/BODY with
#           positive operators. It REFUSES rather than half-runs: a "matches
#           every message" rule, an "any" rule with a condition the server
#           cannot search, or a negative BODY test all come back with the
#           reason shown next to the rule name.
#         • _imap_sweep_search() is READ-ONLY (select(readonly=True) +
#           BODY.PEEK[HEADER]) and downloads headers only, so a 2 000-message
#           sweep takes seconds. "any" mode searches per condition and records
#           WHICH one hit, so body conditions can be trusted per message.
#         • _sweep_keep() re-checks every hit locally, because IMAP SEARCH is
#           always a substring match — "is" / "begins with" / "ends with" are
#           enforced here, as are folder scope and has_attachment.
#         • Trashing is the separate second step: _imap_trash_uids() moves them
#           in batches over ONE connection (UID MOVE, else COPY + \Deleted +
#           UID EXPUNGE — never a bare EXPUNGE), gated on Server changes, with
#           one confirmation naming the count and folders. Self-addressed mail
#           is skipped (the Gmail one-message-many-labels trap).
#   [x] Settings that were only editable in settings.json now have real
#       controls: delete_undo_seconds in Tools → "Sending & deleting", the two
#       contact auto-save switches at the bottom of the Address book, and
#       always_html_view in Tools → Reading (kept in step with the tick-box in
#       the reading pane).
#   [x] Tools → Blocked/trusted/kept-unread got a "Trust…" button, so a sender
#       OR A WHOLE DOMAIN can be trusted by hand (domains were already stored
#       and removable there — the dialog just never said so).
#   --- ADDRESS CORRUPTION (#14): CAUGHT IN THE ACT + SHUT OUT ----------------
#   The root cause of "issusbarn@♣gmail.com" was never found, so instead of
#   guessing again the program now (a) makes it impossible to enter, (b) covers
#   every send path, and (c) writes down what the character WAS:
#   [x] `_guard_address_entry` (in the _RecipientFields mixin) puts a Tk
#       validatecommand on To:/Cc:/Bcc: in BOTH windows. It refuses only
#       Unicode categories Cc/Cf/Co/Cs/Cn/So — control, invisible and "other
#       symbol" (♣ ★ ☺, emoji) — so letters of ANY script still type normally
#       and a display name can still be "Ärna Öberg". Validation runs on
#       INSERT only (%d == "1"): validating deletes as well would have made a
#       bad character already in the field impossible to remove — a bug the
#       tests caught before it shipped. A paste containing one bad character
#       keeps the address and drops the character, re-inserted via after_idle
#       because Tk turns validation off for good if the validate command edits
#       the widget itself.
#   [x] `_sanitize_payload_addresses` runs inside `queue_send` — the ONE path
#       everything leaves by — so the unsubscribe mailer, a bounce retry, a
#       restored draft and anything added later are covered without having to
#       remember. It cleans silently and logs; there is nobody to ask at that
#       point. The compose windows still ask about lookalike domains earlier.
#   [x] `_addr_forensics` spells out every illegal character as
#       "position 10: U+2663 BLACK CLUB SUIT" — a log full of unrenderable
#       glyphs would have been no help. Every clean/refusal logs the original
#       repr, the result and WHICH path it came down. Next occurrence names
#       itself instead of starting another hunt.
#   [x] Contacts are cleaned on the way into the address book (`_merge_contacts`
#       — vCard, CSV and the auto-save of people you write to all land there),
#       and the address book has "🩺 Check addresses" to mend ones already
#       stored. That closes the loop where one corrupt contact would otherwise
#       be handed back out by autocomplete for years.
#
#   --- WHY NOTHING MOVED: FILTERS, MOVE, NAVIGATION (2026-08-03) -------------
#   [x] THE MOVE BUG, found at last. Every "move to folder" was handed the
#       DECODED folder name the sidebar shows — "Temporär/0---Frakt & Kvitto" —
#       but IMAP only answers to the raw modified-UTF-7 name,
#       "Tempor&AOQ-r/0---Frakt &- Kvitto". Two separate failures came of it:
#       imaplib encodes command arguments as ASCII, so a Swedish letter raised
#       UnicodeEncodeError before the command left the machine; and an
#       ASCII-but-ampersand name quietly addressed (or CREATED) a different
#       label. New `_imap_utf7_encode`, `_mb_arg` (bytes, quoted) and
#       `_resolve_mailbox` (logical name / decoded path / raw name → raw,
#       creating it on request, one LIST per connection). Used by
#       _imap_move_message, _imap_append_message and the sweep.
#   [x] FILTER DIAGNOSTICS — the log Issu asked for. `_filter_explain` re-runs
#       one rule against one message keeping the text it compared, so the log
#       and the new "Why didn't my rule fire?" window (Tools, and a button in
#       the filter editor) show: which rules exist, which RAN for this trigger
#       and why not, which matched IN FULL, and which came CLOSE — with a ✔/✖
#       per condition and what the message actually said. A manual run explains
#       every message; a background run writes only the per-rule summary.
#       "Filters ran — nothing matched" now OFFERS that window.
#   [x] Rules that could be merged — `_merge_groups` offers only "any"-mode
#       rules with identical actions, triggers and folder scope, because ANDing
#       two "all" rules would make a THIRD, stricter rule. Also warns when the
#       same sender appears in more than one rule.
#   [x] Filter editor: rule names lost the "Rule for " prefix (it ate the part
#       of the address you need); the Match row gained a 1/2/3 number box
#       (1 = all of, the default · 2 = any of · 3 = all messages) wired both
#       ways to the radio buttons.
#   [x] FOLDER PICKER rebuilt (both of them — the plain one AND the
#       account+folder one the filter editor uses when you have two accounts,
#       which is why the collapse and the favourites looked missing): a
#       COLLAPSIBLE tree that remembers what you folded, a Find box, and FIVE
#       favourite slots — 1–4 permanent (✕ to free one), 5 rolling.
#   [x] KEYBOARD: Up/Down move inside the pane that has the arrows, Left/Right
#       hand them to the folder pane / the message pane (a 2-pixel accent edge
#       shows which), Shift+Up/Down grow AND shrink the message selection from
#       its anchor. The reason none of this worked: the reading pane is a
#       read-only tk.Text, so clicking a message to read it made
#       _typing_focused() answer "yes, typing" and killed every shortcut.
#       Widgets that only display text now carry _nav_passthrough.
#   [x] Tk's own dialogs said "Ja / Nej / Avbryt" in an English-only program —
#       its buttons come from the SYSTEM message catalogue. `ask_yes_no_cancel`
#       is our own themed three-button dialog (buttons say what they DO), and
#       `_force_english_dialogs` sets msgcat to English for everything else.
#   [x] Every corner toast now shares ONE stack (`_corner_stack`): send-undo,
#       delete-undo, notifications, calendar and follow-up reminders used to
#       stack only against their own kind, so a Send toast sat exactly on top
#       of a Delete toast. "Message sent!" moved out of the middle of the
#       screen into that stack.
#
#   --- CONDITION SECTIONS + FOLDER HOUSEKEEPING (2026-08-03, later) ----------
#   [x] A rule could only AND everything or OR everything, so "From MUST be
#       dhl.com AND the subject is EITHER 'Ditt kvitto' OR 'Inlämningskvitto'"
#       was unsayable — hence one near-identical rule per subject line. Every
#       condition now carries a SECTION (_split_conditions):
#         group "all" — MUST match, every row          (AND)
#         group "any" — at least ONE row               (OR)
#       and the rule fires when both hold. An empty section drops out, so a
#       rule with only "all" rows is the old match-all and one with only "any"
#       rows is the old match-any — which is what makes the migration in
#       _load_filters a no-op for every rule already saved. match_mode is now
#       only "groups" or "every".
#       _filter_describe() prints the rule as one English sentence, live in the
#       editor and in the diagnosis, because a two-section form is easy to
#       misread and a sentence is not.
#       The sweep follows: _sweep_plan returns a LIST of searches (the MUST
#       terms ANDed into each, one per either/or row) and _imap_sweep_search
#       unions them; each search records which conditions it proved, so
#       _sweep_keep knows exactly which BODY tests it may take on trust.
#   [x] The 1/2/3 box no longer switches a rule's mode. It is a SAVED DEFAULT
#       (cfg filter_default_section) deciding which section a suggested
#       condition lands in and where a new rule starts — it never moves while
#       you edit a rule.
#   [x] Folder housekeeping, right-click a folder: "Mark everything as read"
#       (_imap_mark_folder_read — adds \Seen, never removes) and "Delete the
#       folder" (_imap_folder_stats + _imap_delete_folder). An EMPTY folder is
#       deleted with no question at all; one holding mail asks once and says
#       the truth — a Gmail folder is a LABEL, so deleting it unlabels, it does
#       not delete mail. Standard mailboxes are never offered. A just-deleted
#       folder is parked in cfg hidden_folders and left out of the sidebar
#       until Gmail's LIST stops reporting it, then forgotten.
#   [x] Empty Trash is per ACCOUNT (all of them only in the All Accounts view).
#       The old fallback that widened to every account when the current one
#       could not be resolved is gone — a destructive action must never widen
#       its own scope.
#   [x] Filter editor is roomier (clamped to 92 % of the screen), and has an
#       UPDATE button that saves without the "shall I run the filters?"
#       question — for renaming or merging, where nothing about which mail
#       matches has changed. It also keeps the saved rule selected, so pressing
#       Update twice edits it twice instead of making a duplicate.
#   [x] Shift+arrow keeps ONE row of headroom in the direction of travel
#       (_scroll_msg_into_view(lookahead=)), so you can see the message you are
#       about to select before you select it.
#
#   --- MOVE/READ/MUTE + THE MARK-READ BUG (2026-08-03, later still) ----------
#   [x] THE MARK-READ BUG. A rule that both MOVED a message and marked it read
#       queued the move first; UID MOVE took the message out of the Inbox and
#       the following STORE \Seen then hit a UID no longer there — the mail
#       landed in the target folder still unread (Issu: "4 mail olästa trots
#       Mark as read + on Gmail"). On Gmail \Seen is a per-MESSAGE flag shared
#       by every label, so the batched dispatcher now runs "seen"/"flag" BEFORE
#       "move"/"trash" (_KIND_ORDER), setting the flag while the message is
#       still in the Inbox.
#   [x] Bulk "📁 Move to…" on the multi-select bar — Gmail has no drag-and-drop
#       and labels are not folders, so tick-then-Move is the way. Reuses
#       _move_messages → the collapsible-tree picker → the batched UID MOVE.
#   [x] "✓ Read all" in the quick-filter row marks the WHOLE open folder read
#       on the server (_mark_current_folder_read → _imap_mark_folder_read),
#       every account's copy in the All Accounts view. Hidden on the local
#       (virtual) folders.
#   [x] Per-folder unread-count MUTE (cfg muted_count_folders, keyed per
#       account like the mini-hide set). _folder_count / _account_inbox_unread /
#       _unread_kind all skip a muted (account,folder), so it adds no sidebar
#       badge and nothing to the taskbar total — but its mail still shows as
#       unread when opened. A 🔕 marks a muted folder; right-click toggles it.
#       This is Issu's "det ska inte stå hur många olästa i den katalogen".
#
#   --- SMART REPLY REBUILT (2026-08-03, later still) ------------------------
#   [x] The writing box was inline and scrolled away; it is now DOCKED at the
#       bottom of the window (a vertical PanedWindow: sender paragraphs above,
#       your box below, always visible). Click a paragraph — or Ctrl+↑/↓ — to
#       answer it; ● marks answered ones and each shows a preview of your
#       answer. Switching never loses text.
#   [x] Every reply now sends TWO parts, always: "My reply" (just your answers)
#       and "The full message" (the original text with your answers interleaved
#       where you wrote them). A checkbox "My answers at the top" (default ON,
#       remembered) picks the order; a separator sits between them and a
#       one-line hint gives the exact line the other part starts on (plain-text
#       line numbers are deterministic). Built by the pure _smart_reply_bodies.
#   [x] The message is sent as multipart/alternative — plain text AND HTML
#       (_smtp_send html_body=, queue_send carries body_html, the outbox passes
#       it). The HTML copy adds clickable jump anchors and can style the
#       sender's old text (Their text: none/grey/italic/bold/quote-bar,
#       remembered). Plain text always uses "> ". A text-only client still gets
#       the whole message from the plain part.
#       New cfg: smart_reply_answers_top, smart_reply_quote_style.
#
#   --- SMART REPLY: PARAGRAPHS + REPLY-TO-SELF (2026-08-03, later still) -----
#   [x] The body was split on blank lines only, so a message with none (and
#       anything you typed yourself) became ONE paragraph — pointless for a
#       point-by-point reply. `_split_reply_paragraphs` now falls back to one
#       paragraph per line, and the docked box has "✂ Split into lines" and
#       "⬆ Merge up" so you shape the paragraphs yourself (answers kept through
#       both — see _split_here / _merge_up; _load_dock split off from
#       _select_paragraph so a rebuild can't write a stale box over an answer).
#   [x] A reply came back addressed From == To == me, with a copy in my own
#       inbox. `_reply_to_address(msg, my_emails)` fixes it: Reply-To else the
#       sender, but if that is one of YOUR OWN accounts (replying to your own
#       message or a self-thread), reply to the ORIGINAL recipients instead —
#       never to yourself. Used by BOTH ComposeWindow and SmartReplyWindow.
#
#   --- BATCH 19 (Issu 2026-08-08) -------------------------------------------
#   [x] SEND WAS BLOCKED OUTRIGHT. Three real replies to Mirall sat in the
#       outbox marked "failed" with "Header values may not contain linefeed or
#       carriage return characters". It was NOT the subject (one of them was
#       just "order 1237"): the References: header is copied off the message
#       being answered, and on a long thread it arrives FOLDED
#       ("<id-1@x>\r\n <id-2@x>"), which the email package refuses.
#       `_hdr_safe()` unfolds EVERY header value (From/To/Cc/Subject/
#       In-Reply-To/References) at three points — when the reply is built, at
#       the queue_send choke point, and again in _smtp_send. `_load_outbox()`
#       also REPAIRS the queue on start-up: it unfolds anything already stored
#       and re-queues messages that failed with exactly that error, so the
#       three stuck replies go out by themselves. Nothing to re-type.
#   [x] "The message is in tools/outbox" sent Issu hunting for a folder on
#       disk. It is FILE → Outbox, a window in this program. The wording says
#       so now, out loud.
#   [x] COMPOSE AND SMART REPLY ARE NO LONGER MODAL. grab_set() froze the main
#       window: you could move the mouse and highlight rows but clicking a
#       folder or a message did nothing ("meningslöst"). Both are ordinary
#       independent windows now; Escape steps back to the mailbox instead of
#       throwing the message away (_to_background), and closing a Smart Reply
#       with answers in it asks first.
#   [x] "MAILET FÖRSVANN." A shipping receipt opened in the Inbox and vanished;
#       it turned up in the rule's target folder, vanished again, and finally
#       sat on "Loading" for ever. Cause: a filter MOVES the message, and a UID
#       is only valid in the mailbox it was in — so the on-demand body fetch
#       came back empty and the pane had no way out. Now:
#         • `_find_message_anywhere()` asks Gmail where it went
#           (X-GM-RAW rfc822msgid:, one query across All Mail) and the fetch
#           FOLLOWS it, saying which folder it opened from;
#         • a fetch that still fails shows "Could not open this message" with
#           Try again / Refresh — never an endless "Loading…";
#         • a message that leaves the folder while you are reading it now says
#           WHICH of your rules moved it (_explain_vanished);
#         • a moved message is recognised by Message-ID on the next refresh
#           (_reply_key), so the reading pane no longer blanks.
#   [x] "Många dubletter med tomma meddelanden" — `_dedupe_messages()`: same
#       Message-ID = same mail, and the copy WITH a body wins over the empty
#       header-only stub.
#   [x] "Drafts säger (2) men är tomt, och (2) kommer tillbaka." Gmail leaves
#       drafts unflagged, so STATUS (UNSEEN) counted them for ever while the
#       folder showed nothing. Drafts is now counted by MESSAGES
#       (_COUNT_BY_MESSAGES) in both the background pass and the on-screen
#       reconcile — and your own unsent LOCAL drafts finally appear in the
#       Drafts folder (they were on disk, visible nowhere), rendered instantly
#       from disk instead of behind a "loading…".
#   [x] REPLIES WENT OUT WITH NO ORIGINAL TEXT. Not about the extra recipient
#       at all: `_ensure_full_body` REPLACED the message dict when the body
#       landed, so a reply window opened a second earlier kept a stub with
#       body == "" and quoted nothing. It now updates the dict IN PLACE, Reply/
#       Smart Reply/Forward wait for the body (`_body_ready`), and an empty
#       quote asks before going out.
#   [x] Smart Reply, four changes Issu asked for:
#         • the message no longer opens with "You'll find my reply first… begins
#           on line 11" — it starts with CONTENT, and the one explaining
#           sentence sits BETWEEN the two copies where it is actually needed;
#         • `<a href="#…">` both ways AND per paragraph: every answer links to
#           the paragraph it answers and back again ([1] [2] … in plain text,
#           so the same navigation survives without HTML);
#         • "Indent theirs: 0 / 5 / 10" pushes every line the sender wrote to
#           the right, in plain text and HTML, so the two voices are two
#           columns (the same setting also indents a normal reply's quote);
#         • it REMEMBERS a half-finished reply (reply_progress.json, keyed on
#           Message-ID so it survives being moved), reopens on the first
#           unanswered paragraph, and paragraphs can be SET ASIDE (⊘) by hand
#           or in bulk ("set aside the answered ones") — set-aside paragraphs
#           are left out of the sent message entirely.
#   [x] SENDING is back INSIDE the window. The "Sending… [Cancel]" toast was a
#       floating always-on-top popup again; it is now a bar in the message-list
#       row next to the delete-undo bar, with steady states and no per-second
#       countdown.
#   [x] Contacts sits on the main toolbar, just before Refresh.
#   [x] NEW: 🧾 Log button — an activity log kept ON DISK (activity_log.json)
#       of what happened to your mail: which account it arrived in, which rule
#       fired, what the rule did. The old Filter log died with the session,
#       which is useless for "the phone buzzed this morning, where did that
#       mail go?". Filterable by kind, searchable.
#   [x] Mail filters: pressing + puts the cursor straight in the new
#       condition's box and scrolls it into view; New rule puts it in the rule
#       name and scrolls back to the top.
#
#   --- BATCH 19c: THE 30-SECOND "LOADING" (Issu 2026-08-08) -----------------
#   He clicked a new mail and waited about half a minute. Measured from his own
#   Freemail.log + settings, the cause was a QUEUE, not a slow server:
#     • the auto-check re-fetches the open folder every ~63 s,
#     • the unread-count pass STATUSes 21 mailboxes on issusbarn@gmail.com in
#       the same cycle (7 standard + 14 of his own labels),
#     • the quota check joins in every 15 minutes,
#   and ALL of it went through the ONE pooled connection per account, behind
#   one lock. Clicking a message simply took its turn at the back.
#   [x] TWO LANES. `_imap_acquire(..., lane=)` keeps a separate pooled
#       connection for "ui" (you clicked something) and "bg" (everything
#       automatic), so a click never waits for a background pass. Measured with
#       a fake 200 ms-per-command server: 4.3 s → 0.4 s. The ui connection is
#       closed again after 5 minutes idle (`_imap_reap_idle`, called from the
#       calendar ticker) so it costs nothing when unused — that also keeps us
#       clear of Gmail's simultaneous-connection limit, which the pre-pool code
#       used to hit ("Too many simultaneous connections" is in his log).
#   [x] READ AHEAD — his own suggestion, "kan inte programmet jobba med nya
#       saker i bakgrunden, och läsa in lokalt?". `_prefetch_bodies()` +
#       `_start_prefetch()`: after the list lands, the bodies of the newest
#       `prefetch_count` (12) uncached messages come down quietly on the bg
#       lane, one at a time, so opening one is a LOCAL read. It yields to any
#       click (`_background_yield`), stops when you change folder or close the
#       program (the `stop` callback watches `_fetch_token` / `_closing`), and
#       swallows every error — a prefetch that fails must never be visible.
#       Switch and count live in Tools → Reading.
#   [x] The per-folder cache lock is no longer held across the network in
#       `_fetch_single_full_body` — only around the few milliseconds of disk
#       work. Opening a message while that folder was refreshing used to mean
#       waiting for the whole refresh first.
#   [x] The unread-count pass walks the CUSTOM labels only every 5th time (and
#       skips ones whose count is muted): 126 STATUS commands per six minutes
#       → 70, with the standard folders still counted every pass.
#
#   --- BATCH 19d: FOLDERS (Issu 2026-08-08) ---------------------------------
#   [x] "Går till 0---Frakt & kvitto … det är tomt och den säger att det inte
#       finns några. Efter en lång stund kommer de in." Two causes, both fixed:
#       (a) a HEADER-only fetch was never written to disk, so a folder whose
#       bodies had never been downloaded (his Trash and Spam hold index entries
#       and not one .eml) had nothing to render and went blank. Headers are now
#       cached as <uid>.hdr and the instant render uses them — a complete,
#       correct list in milliseconds, bodies filling in behind. (b) an empty
#       list said "No messages in this folder." even while fetching; it now
#       says it is still fetching (`_fetch_in_flight`).
#   [x] "All accounts … Spam är loading" — the five accounts were fetched ONE
#       AFTER ANOTHER. Now one thread per account: measured 6.6 s → 1.6 s. And
#       a folder YOU open goes on the "ui" lane (`interactive=` through
#       _fetch_folder_smart / _fetch_folder_cached / _fetch_folder), so it no
#       longer queues behind the auto-check and the read-ahead either.
#   [x] Right-click a folder → "New folder inside…" (there was a Delete but no
#       Create) via `_imap_create_folders` + the new `_ask_line` prompt.
#   [x] Right-click → "Don't show unread counts for X AND its N sub-folders" —
#       `_subfolders_of` + `_toggle_count_mute_tree`, for a parent like
#       Temporär with a dozen labels under it.
#   [x] Right-click → "📅 Month folders in X…": creates a folder per month,
#       named 01/02…, 2026-01/2026-02… or 2026/01 (his choice, remembered in
#       cfg["date_folder_style"]), from this month, as many forward and back as
#       you like, with a live preview. NEVER overwrites — a folder that exists
#       is skipped. "Create, then file what is here" then moves the messages
#       already in the folder into the month their OWN Date: header falls in
#       (`_month_folder_for_message`), showing the full plan and asking first.
#   [x] "Jag vill bara inte att mail hoppar omkring." → PROTECTED FOLDERS.
#       Right-click → 🔒 Protect. `_dispatch_filter_server_actions` — the one
#       place every server-side filter action passes through — refuses any move
#       or trash OUT of a protected folder, whatever any rule says, now or
#       later, and writes the refusal to the activity log. Mail can still
#       ARRIVE (so a rule can still file things there), and you can still move
#       or delete it BY HAND; only the automatic path is closed. A 🔒 in the
#       sidebar shows which folders are protected. cfg["protected_folders"].
#
#   --- BATCH 19e: THE SEARCH WINDOW (Issu 2026-08-08) -----------------------
#   [x] Search now has a WINDOW of its own (DEL 06f, `SearchWindow`), opened
#       with the 🔎… button beside the search box, View → Search window, or
#       Ctrl+Shift+F, and carrying whatever is already typed in the box.
#       NOT modal: the main window stays fully usable beside it, and Escape
#       steps back to the mailbox rather than closing it. Only ever one.
#   [x] Results are YOUR FOLDER TREE, not a flat list — account, then folder,
#       and a folder appears ONLY if it contains a match. That answers the
#       question you usually have ("where did that receipt end up?") instead
#       of merely proving the mail exists somewhere.
#   [x] Choose what to search: Subject / Sender / To-Cc / Message text, any
#       combination at once (`_SEARCH_FIELDS`). Each is a SEPARATE IMAP SEARCH
#       (`_search_one_field`), so every hit knows which fields matched it —
#       shown as coloured chips on the row, colours in `_SEARCH_FIELD_COLOURS`,
#       matching the tick-boxes. The choices are remembered.
#   [x] `_search_account_by_field` reports folder by folder through an
#       `on_folder` callback, so the tree fills in while the rest is still
#       running; accounts run in parallel; Stop keeps what was found. HEADERS
#       ONLY are fetched — a search across every folder of five accounts must
#       not drag bodies over the wire.
#   [x] Exclude a hit ("lyx att kunna exkludera funna Searched") — per ROW, so
#       excluding a message under one label leaves the same message under
#       another alone (Gmail: one message, many labels). "✕ exclude these" on
#       a folder does the bulk case; "↺ Bring back all" undoes the lot.
#   [x] From inside the window: Open it (jumps the MAIN window to the folder it
#       really lives in — `open_message_from_search`), Move to… (for something
#       filed in the wrong place), and 🔒 Protect that folder so nothing
#       automatic moves it out again.
#   [x] BUG THE TESTS CAUGHT, worth remembering: `folders_for()` read a Tk
#       BooleanVar from a WORKER thread → "main thread is not in main loop",
#       swallowed by the worker's own except, and the search came back silently
#       EMPTY. Every Tk variable is now read on the main thread in run() and
#       passed in as a plain value.
#
#   --- BATCH 19f: THE MONTH-FOLDER REGRESSION (Issu 2026-08-08) -------------
#   "Jag kollade i augustikatalogen, och där fanns mail, i 1 sekund… innan de
#   försvann. Nu verkar alla mail vara tillbaka i den roten."
#   [x] CAUSE — a pre-existing hole that the month folders walked straight
#       into. His shipping rules move mail to "INBOX/Temporär/0---Frakt &
#       Kvitto". Once the mail had been filed on into ".../2026-08", opening
#       that month folder ran the rules over it again (run_on_fetch), they
#       still matched (the sender has not changed), and every message was
#       moved back UP to the parent. Nothing checked whether a message was
#       already AT its destination.
#   [x] FIX — `_already_filed_there(msg_folder, target)` (with `_folder_norm`,
#       which decodes modified-UTF-7 so the raw name a message carries and the
#       decoded path a rule stores compare equal). A move is skipped when the
#       message is at the target OR inside a sub-folder of it; the filter log
#       says "move skipped — already filed in X". Same account only: a
#       cross-account rule genuinely has somewhere else to put it. Verified
#       against his REAL filters and 40 REAL cached messages: 40 moves before,
#       0 after, and the same messages sitting in the Inbox still queue 40.
#   [x] "Det finns ingen flytta" — filing was only reachable inside the create
#       dialog, and only while standing in the folder. It now has a right-click
#       item of its own ("📅 File the mail in X into its month folders…"),
#       fetches the folder itself when it is not the one on screen, creates any
#       missing month folder first, and ignores anything already filed into a
#       month sub-folder.
#
#   --- BATCH 20 (Issu 2026-08-08, evening) ----------------------------------
#   [x] "VAR LIGGER DET HÄR MAILET?" — right-click any message → every copy of
#       it, in every folder of EVERY account, with the Gmail labels it carries
#       (`_locate_message`, `_where_is_dialog`). The sibling of
#       _find_message_anywhere, which stops at the first hit; this one keeps
#       looking, because on Gmail the honest answer is usually "in several
#       places at once". Accounts are searched in parallel; read-only.
#   [x] RULE HEALTH (Tools → Rule health, and a button beside Filter log).
#       `rule_stats.json` counts what each rule actually does, across restarts.
#       For a rule catching nothing, `_rule_blocking_conditions` says WHICH
#       row is to blame — and, crucially, considers a whole EITHER/OR SECTION
#       as well as single rows: his DHL rule is "From @dhl.com AND (Subject
#       'Ditt kvitto' OR Subject 'Inlämningskvitto')", where dropping one
#       subject row changes nothing and a row-by-row analysis reports all
#       clear. Dropping the section is what unblocks it — measured on his real
#       mail: 0 matches → 14. One button does it, after a confirmation naming
#       every row it will remove.
#   [x] LONG RECIPIENT LISTS FOLD (his mail "with + 49 more"). Above
#       cfg["recipients_max"] (5) the To:/Cc: line collapses to one line with
#       a "▾ show all"; right-click it to change the threshold or to say
#       "never show recipients from THIS sender"
#       (cfg["hide_recipients_from"]).
#   [x] THE LOG NO LONGER DROWNS ITSELF. Measured: 24.1 MB / 201,614 lines, of
#       which 80% was the once-a-minute filter dump. Now (a) the file rotates
#       at 4 MB keeping 3 old ones — a hard 16 MB ceiling — and (b) a
#       BACKGROUND run that matched nothing writes ONE line. Standing warnings
#       ("Server changes is off", "this rule has no action") are written when
#       they CHANGE, not every minute (`_diag_sig`). Measured over an
#       hour of once-a-minute checks: 1800 lines → 102. A manual run still
#       writes everything, and the in-memory diagnosis is untouched, so "Why
#       didn't my rule fire?" is exactly as detailed as before.
#   [x] OUTBOX NAG — `_nag_stuck_outbox` at start-up: a toast (not a modal) if
#       anything has been queued or failed for more than an hour, saying how
#       long and opening the Outbox on click. His three failed replies sat
#       there from 2026-08-07 and nothing ever mentioned them again.
#   [x] STORAGE (Tools → Storage) — what this program is using, per folder,
#       with the two that grow without limit called out: his cache had reached
#       42 MB / 776 files and the Deleted archive 26 MB / 1412. Trim the cache
#       by age (or entirely — the mail is on Gmail), and set the Deleted
#       archive's keep-days. Accounts/rules are never touched.
#
#   --- BATCH 21: BACKUP THAT RESTORES, AND TIDYING DRAFTS -------------------
#   Issu 2026-08-08: "kan jag spara mail så att jag kan exportera en fil…
#   sedan importera och oavsett vad jag gjort i Gmail under tiden, återställa,
#   och Gmail krånglar inte?"
#   [x] EXPORT (File → Export mail to a file…) — one .zip: manifest.json plus
#       the byte-exact .eml of every message. The manifest carries what the
#       .eml itself does NOT and what a restore is useless without: the
#       INTERNALDATE, the \Seen/\Flagged flags, every Gmail LABEL, and the
#       Message-ID. Without the date a year of mail comes back stamped today;
#       without the flags 4 000 messages come back unread, on his phone too.
#   [x] RESTORE (File → Restore mail from a file…) — `_restore_messages_zip`
#       with `_imap_append_full` (APPEND *with* flags and internaldate; the
#       older _imap_append_message could carry neither). It LOOKS FIRST: each
#       Message-ID is searched for in All Mail and anything still there is
#       skipped untouched. That is the whole of "Gmail krånglar inte" —
#       **the restore is safe to repeat**, and restoring a year-old backup
#       over a mailbox he has kept using puts back only what is genuinely
#       gone. "🔍 Check first" does the same look-up and uploads nothing.
#       Labels are restored by appending into each one. Additive only: nothing
#       is moved, changed or deleted on Gmail, ever.
#       HONEST LIMIT, said in the dialog rather than discovered later: Gmail
#       assigns conversation ids, so a restored message may sit in a thread of
#       its own. The mail is all there; the grouping may differ.
#   [x] TIDY DRAFTS (File → Tidy drafts…) — his "kolla Drafts om meddelanden
#       sedan skickats". Reads the Sent folder and pairs drafts up with
#       messages that already went out (finished on the phone, or sent before
#       this program started marking them). `_draft_looks_sent` is
#       deliberately CONSERVATIVE — same subject once Re:/Sv:/Fwd: and case
#       are stripped (`_norm_subject`), AND at least one recipient in common,
#       AND the Sent copy not older than the draft; an empty subject or no
#       recipient never matches. Everything is shown with the reason and
#       ticked by you before anything is deleted.
#
#   --- BATCH 22: THE SHIPPING-MAIL MESS (Issu 2026-08-16) -------------------
#   "Freemail är rörigt. Filter verkar inte fungera… de skickas runt… blir
#    kopior och en del av dem verkar tappa sitt body-innehåll. Min frakt och
#    kvitto-mail, från ALLA konton, ska hamna i den katalogen i Main-kontot."
#
#   Four separate faults, all landing on the same journey. Each was measured
#   against his real mailbox before and after, not reasoned about:
#
#   [x] 1. THE BODY-LESS COPIES. `_fetch_folder_cached` lists a folder by
#       fetching BODY.PEEK[HEADER] for messages it has not seen, and parks
#       those header bytes in msg["_raw"] until the body is really wanted. The
#       cross-account move uploaded THAT to the other account — and then
#       trashed the original. Verified in his own cache: 56 of 252 receipts in
#       0---Frakt & Kvitto are 4–5 KB, one part, ZERO body. Only the ones the
#       12-message prefetch had reached survived intact, which is exactly why
#       "en del av dem" and not all.
#       FIX — `_raw_is_headers_only()` + `FreemailApp._full_raw_for()`: the
#       bytes are CHECKED, and a missing body is fetched (message dict → disk
#       cache → server, in that order). If it still cannot be had, the
#       delivery is REFUSED, nothing is uploaded and — this is the important
#       half — THE SOURCE IS NOT TRASHED. The mail stays put and the next
#       check tries again. Never trade a real message for an empty envelope.
#   [x] 2. THE COPIES. The "have we delivered this already?" check looked in
#       ONE folder. File a delivered receipt on into .../2026-08 (the whole
#       point of the month folders) and the check saw an empty parent, so the
#       source — still sitting in the other account's Trash, still matching
#       its rule on every check — was copied again. His activity log has 144
#       such rescues in a week, and the cache holds 17 duplicate Message-IDs.
#       FIX — `_imap_message_id_in_account()` asks All Mail (plus Trash and
#       Spam, so something you deliberately binned stays binned), and above
#       that a ledger on disk, `delivered.json` (DEL 04y2), remembers every
#       cross-account delivery ever made. It survives restarts, it is checked
#       before the network is, and Tools → "Cross-account delivery log…"
#       shows it and can forget a line if you want a message sent again.
#   [x] 3. "FILTER VERKAR INTE FUNGERA" — and it did not, for four of his five
#       accounts. `_poll_account` fetched each account on its own timer and
#       then ran the rules ONLY if that account happened to be on screen.
#       Everything else was counted, toasted and left exactly where it landed
#       until he opened it by hand — at which point the rules all fired at
#       once and looked intermittent. The scheduled check now runs the rules
#       for EVERY account, which is what "från ALLA konton" has to mean.
#       (Redraws are still suppressed unless the visible list really changed,
#       so a rule filing mail in another account cannot blank the message you
#       are reading.)
#   [x] 4. PROTECTED FOLDERS WERE HALF OFF. `_is_protected` compared raw
#       strings, but the same folder is stored in two spellings — the decoded
#       path a rule writes and the modified-UTF-7 name a message carries. His
#       settings.json holds both, and 2026-06/07/08 are in there TWICE. Every
#       month folder protected in the "wrong" spelling was silently
#       unprotected. `_protected_key()` normalises through `_folder_norm`, so
#       both spellings are one folder; switching protection off now clears
#       every spelling instead of leaving one behind.
#   [x] BONUS, found on the way: a rule that tests the message BODY (or wants
#       "only with an attachment") was judged against a message whose body had
#       not been downloaded — an empty string and an empty list — and reported
#       "no match" as though it had looked. Such a rule could never fire on
#       new mail at all. `_filter_needs_body()` now DEFERS instead: the body
#       is fetched (`_finish_deferred_rules`, bounded, once per message) and
#       the rule is judged properly, and "Why didn't my rule fire?" says so
#       plainly rather than claiming a verdict it could not reach.
#   [x] The delivered copy now keeps its OWN date and read state
#       (`_imap_append_full` instead of `_imap_append_message`), so filed
#       receipts stop arriving as unread mail stamped "today".
#   [x] CLEANING UP WHAT IS ALREADY THERE — Tools → "Mail with no body…".
#       Scans a folder and its sub-folders and measures each message's body
#       (BODY.PEEK[TEXT]<0.256> — a fact, not a size heuristic), then repairs:
#       where an intact original still exists, in this account or the one the
#       copy came from, it is uploaded into the same folder with its real date
#       and the empty one goes to the Trash. It PROVES the good copy landed
#       (`_folder_has_intact_copy`) before removing anything, because Gmail can
#       refuse a second message carrying a Message-ID it already holds and an
#       unverified "OK" would turn a repair into a deletion. Anything that
#       cannot be repaired is listed and left completely alone.
#
#   --- BATCH 23: AUTO-HIDING BOILERPLATE (Issu 2026-08-16) ------------------
#   "Att kunna autodölja saker i meddelanden … Resten kommer i alla de
#    meddelanden och kan döljas helt, alltid."
#
#   [x] DEL 04t2/04t3 — STANDING HIDE RULES. DEL 04t already folded a
#       hand-picked selection in ONE message; this is the rule version, folding
#       the same boilerplate in every message that carries it. Four kinds:
#       line / block / tail / strip. Built-ins ship for BoardGameGeek's
#       GeekMarket paragraph, its MessageCenter footer, its [geekurl]/[q]
#       markup, and Tradera's footer — seeded once (cfg["trim_seeded"]), then
#       ordinary editable rules.
#       DISPLAY ONLY, and that is load-bearing: Tradera's footer carries
#       "Behåll detta i mailet när du svarar [[id:…]]", so hiding it must not
#       remove it from a REPLY. `_trim_hidden_parts` is pure and never touches
#       msg["body"]; the renderer is the only consumer. Asserted by test.
#       Reversible per message from the marker (`_trim_revealed`, session-only
#       — looking at a footer once is not a decision to stop hiding it).
#   [x] "MED MÖJLIGHET FÖR MIG ATT LÄGGA TILL NYA SAKER" — select the junk,
#       right-click → "Always hide text like this (from this sender)". Scoped
#       to the sender's domain, shown for approval first. The editor
#       (Tools → Hide boilerplate…) has a LIVE PREVIEW of the open message,
#       because a hiding rule you cannot see the effect of is one you will not
#       trust.
#   [x] TWO BUGS THE FIRST BUILD HAD, both caught by testing against his real
#       mail rather than by reading the code:
#         • CRLF. Chunks were built with body.splitlines() + "\n".join(), which
#           is NOT a substring of a CRLF body — so every "line" rule silently
#           did nothing while the strip rules (which slice the body directly)
#           worked. Now sliced by offset; line endings cannot drift.
#         • A marker per stripped tag. One BGG mail produced FOURTEEN
#           "⟨1 line hidden⟩" markers, mostly for [/q]. Markup is noise, not
#           withheld content, so "strip" hits are silent now (see `silent` in
#           _trim_hidden_parts); the message-level "↺ Show boilerplate" still
#           brings everything back.
#       Also worth remembering: BGG mangles its own markup — message 99110
#       contains a bare  q="Hyperides"]  with the "[" missing, so the pattern
#       matches what ARRIVES, not what the format says.
#   [x] A "PLAIN TEXT" PART THAT IS REALLY HTML. DHL's "Frakt bokad…" declares
#       text/plain and puts a whole HTML document in it: 3441 characters of
#       <!DOCTYPE>, <style> and tables, with the one thing that mattered — the
#       parcel's hamta.dhl.com link — buried in an href where it was neither
#       visible nor clickable. `_demote_html_masquerading_as_text` detects a
#       real document (never a sentence that merely mentions "<html>") and
#       renders it as text: 3441 → 355 characters, sender name and tracking
#       link intact. NOT a per-sender rule — every sender that mislabels a part
#       is fixed by the same check. `_html_to_text` also learned to drop HTML
#       COMMENTS (Outlook's <!--[if mso]--> block was leaving a bare "96" at
#       the top of the message) and to normalise CRLF before its whitespace
#       cleanup, without which a table-based mail opened on a screenful of
#       space-only lines.
#   [x] FILE-BY-MONTH FILED ONLY WHAT WAS ON SCREEN. If the folder happened to
#       be OPEN it filed `self._messages` — the loaded ~40 — so filing his
#       0---Frakt & Kvitto moved thirty and left the rest, and because the list
#       refills with older mail it looked done. A folder-wide job now always
#       asks the server (limit 2000, headers only).
#
#   --- BATCH 23b: TRADERA, BLANK LINES, HTML BUTTONS (Issu 2026-08-16) ------
#   [x] TRADERA RULE. "Tradera har jobbiga mail... inte mycket är specifikt för
#       mitt spel där." Measured on a real "din vara är såld": 27 985 chars of
#       HTML → 2 330 of text → 985 SHOWN, 44 lines → 22. Everything specific
#       survives — the headline, Ordernummer, the item title and its link,
#       Objektnr, price, Frakt, "Kontakta köparen"; the shop navigation, social
#       icons, app-store links and footer are folded.
#       Patterns are anchored ^\s* on purpose: a bare tracking URL alone on a
#       line is navigation, while the SAME URL in parentheses after the item
#       title is the link to his own sale. The anchor is the only thing that
#       tells them apart.
#   [x] THE BLANK-LINE FLOOD, and its real cause. "Fler än 2 tomma rader visas
#       som 1 tom rad(?)" — yes, but the reason there were hundreds is that
#       they were NOT blank: &nbsp; unescapes to \xa0, which [ \t] does not
#       match, so the existing \n{3,} collapse could never join the runs those
#       lines broke. His Tradera mail: 714 lines, 410 visually blank. Fixed at
#       the source (\xa0 → space in _html_to_text) and generally at display
#       time (`_collapse_blank_runs`, cfg["collapse_blank_lines"], default on,
#       switchable in Tools → Reading). Display only, like all of DEL 04t2.
#   [x] "View formatted (HTML)" + "Always" MOVED to the top, under the message
#       actions (`_render_html_row`). They used to render BELOW the body: on a
#       long HTML newsletter — precisely the mail you want the formatted view
#       for — you had to scroll through the whole thing you were trying not to
#       read in order to reach the button that would have shown it properly.
#
#   --- BATCH 28: THE LINK THAT WENT WITH THE FOOTER (Issu 2026-08-17) -------
#   "Länken göms också. Just den länken vill jag kunna se i freemail" — about
#   BoardGameGeek's  https://boardgamegeek.com/geekmail/message/137599071 .
#
#   [x] THE BUILT-IN HID THE LABEL. bgg-messagecenter was named "(keeps the
#       link)" and carried a comment saying the URL line was deliberately left
#       alone — while its pattern list held "Link to the original message:".
#       The URL itself did survive, but stripped of the words that made it a
#       link and sitting directly under a fold marker, it reads as part of what
#       was hidden. Now only the sentence that says nothing is folded, and the
#       label + URL stay together. The copy already seeded into his
#       trim_rules.json is repaired on start-up (_TRIM_REPAIRS, gated by the
#       new cfg["trim_seed_version"] so it happens exactly once and never
#       resurrects a rule he deleted).
#   [x] NO RULE MAY HIDE A LINK IT DID NOT ASK FOR. General guard, not another
#       special case: a rule whose own patterns say nothing about links cannot
#       fold a line carrying one (_trim_rule_targets_links). Tradera's rule
#       lists its URLs in full, so it is trusted and keeps working exactly as
#       before; a rule built from a selection can no longer take a link away
#       with the boilerplate around it. "strip" hits obey it too — a
#       [geekurl=https://…] wrapper is left on screen rather than removed
#       silently, since strip leaves no marker to click. cfg["trim_keep_links"],
#       default on, switchable in Tools → Reading.
#   [x] THE READING PANE WAS ONE LINE SHORT — ALWAYS. `count -displaylines`
#       counts the boundaries CROSSED between two indices, so measuring "1.0"
#       to "end - 1c" answers N-1, and every body Text was built one display
#       line too short. Where the mail ended with a blank line the missing line
#       was blank and nobody noticed; where it did not, the LAST line was cut
#       off — and a geekmail's last line is its link. Measured on Tk 8.6, not
#       reasoned about: "line1\nline2" → 1, "a\nb\nc\n" → 3.
#   [x] A THREADED CONVERSATION HID THE SAME LINK ON PURPOSE. The older
#       messages above the one you open are drawn as a 240-character summary,
#       and that truncation was final — the rest of that message existed
#       nowhere on screen. For BGG that is exactly the wrong 240: everything
#       worth having sits at the bottom. "▾ Show the whole message" now opens
#       one out in full, in the same read-only Text the opened message uses, so
#       its links are clickable rather than merely visible. Session-only, per
#       message, like every other reveal here.
#   [x] "NEVER SHOW THIS LINE AGAIN…" — right-click the line itself; no
#       selecting first. One window asks how far the rule should reach (only
#       this address · everyone at that domain · every sender), offers to treat
#       the numbers in it as "any number" (without which a rule made from "On
#       Today 09:16, Peter Olsson wrote:" would match exactly one message
#       ever), and shows what it would hide in the message in front of you
#       before you keep it. The domain is pre-picked when the sender looks
#       machine-generated — BGG writes from reply+1101f4fh6pu@mail.boardgame…,
#       a new address every time.
#   [x] LINKS THAT SWALLOWED THE BRACKET NEXT TO THEM. Found by sweeping all
#       497 cached messages while testing the guard above, not by reading the
#       code: _URL_RE allowed "[" and "]", so 48 links in his own mail were
#       drawn — and made CLICKABLE — with markup glued to the end. Among them
#       his PostNord tracking links (…?id=LY021950964SE]) and an Amazon line
#       where a markdown-style "](" welded two different addresses into one.
#       Brackets are out. A bracket is legal in a URL only as an IPv6 literal
#       host (http://[::1]/), which no mail here contains — and an unclickable
#       IPv6 link beats a tracking link that opens the wrong page.
#   [x] "THEY WROTE … BUT NOTHING". A fifth rule kind, "orphan": fold the
#       matching line ONLY when everything below it is blank (bare > markers
#       count as blank). An attribution over a quote that arrived is worth
#       reading; over an empty one it is noise, and no pattern on the line
#       alone can tell those apart. Ships as a built-in for wrote:/skrev: (seed
#       version 2, so it reaches this installation once), and the right-click
#       dialog can scope the same thing to one sender.
#
#   --- BATCH 29: RULES THAT WAIT (Issu 2026-08-17) --------------------------
#   "Jag vill ha en möjlighet att göra delay på filterregler. Det ska vara
#    undantag men möjligt. T.ex. 'I'm interested in…'-mailen från/via BGG. De
#    kan med fördel skickas till Temporär/Köpare, efter 26 timmar MEN, där så
#    måste alla olästa kvarstå som olästa."
#
#   [x] DEL 04z3 — "⏳ WAIT BEFORE ACTING", per rule, default 0 (= act at once,
#       exactly as every existing rule always has: "undantag men möjligt").
#       Edited as a number + minutes/hours/days, because "26 hours" is how he
#       says it and 1560 is not; stored as minutes (delay_min).
#       THE DELAY IS A MATCH CONDITION, NOT A QUEUE. The rule does not match a
#       message younger than the wait; on a later check the same message is old
#       enough and it fires normally. That one decision buys everything else:
#       no pending-jobs file to keep in step with reality, nothing to replay
#       after a restart, and no queued action left pointing at mail he has
#       meanwhile read, moved or deleted by hand — the rule is re-judged
#       against the mailbox as it actually is, every time. A week with the
#       program closed simply means everything now overdue is filed on the
#       next check.
#       Counted from the MESSAGE'S OWN date (_parse_msg_dt — timezone-aware
#       header vs naive local clock, the trap that only shows up on real mail).
#       No readable date → act now AND log it: a rule that silently never fires
#       is the worse failure.
#   [x] "MEN, DÄR SÅ MÅSTE ALLA OLÄSTA KVARSTÅ SOM OLÄSTA" — delay_keep_unread,
#       on by default whenever a wait is set. The rule's own mark-read is
#       refused both locally and on Gmail (\Seen is never queued), and the mail
#       it files is exempt from the destination folder's auto-read property via
#       msg["_keep_unread"]. It NEVER makes already-read mail unread again —
#       what is unread stays unread, until he opens it himself.
#       Two features could contradict each other here (the folder says "mail
#       here reads itself", the rule says "these stay unread"). The rule wins
#       at runtime, and saving such a rule onto an auto-read destination says
#       so and offers to take the folder off that list — silently winning is
#       how a setting becomes a mystery.
#   [x] A WAITING RULE NO LONGER LOOKS BROKEN. It sets no _filter_names, so
#       "Run filters now" used to report the flatly untrue "nothing matched"
#       and send him hunting for a fault. It now reports how many are waiting
#       and when the next one is due; the run summary gains "N still waiting";
#       "Why didn't my rule fire?" shows ⏳ WAITING with the exact act-at time
#       rather than counting it as a non-match; and the rule summary in the log
#       reads "after 26 h (keeps it unread), move → …".
#   [x] Tests scratchpad/test_delay.py, 28 checks green against a REAL "I'm
#       interested in…" geekmail out of his cache, re-dated either side of the
#       26-hour line: 2 h old does nothing and reports the wait, 27 h old
#       queues the move and the mail is still unread, mark-read is refused,
#       read mail is never un-read, an undelayed rule is bit-for-bit
#       unaffected, and 25 h 59 m / 26 h 01 m sit on the right sides of the
#       boundary. **Test lesson: build the test message with a DECODED subject
#       — the raw header is "=?utf-8?Q?[BGG]=20I'm=20interested=20in…?=", so a
#       "contains" condition on the raw string matches nothing.** And find the
#       sample mail BY CONTENT: his cache churns while the program runs, and
#       the uid this batch started from was gone from disk two hours later.
#
#   --- BATCH 32: NINE SMALL THINGS (Issu 2026-08-22) ------------------------
#   [x] MOVE TO FOLDER — "alternativen rymmer bara 3, sedan tar popup-bredden
#       slut". Two faults, not one. The five favourite chips were packed side
#       by side and pack() does not wrap, so on a 580-px dialog with real Gmail
#       label paths slots 4 and 5 were literally off the edge — they now WRAP,
#       three to a row, and the dialog is 620 wide. And there is a proper
#       dropdown (DEL 09i, _folder_dropdown_row) listing EVERY folder, ordered
#       by cfg["move_folder_counts"] — how many times mail has really gone
#       there — with a type-to-narrow box. Counts, not recency: recency kept
#       demoting the folder he uses constantly the moment he filed one thing
#       somewhere else.
#   [x] THE SUBJECT WITH A BLANK ROW IN IT. A long header travels FOLDED
#       ("…PostNord\r\n och kan…") and the fold survived _dh untouched whenever
#       the subject was plain text rather than RFC2047-encoded — which is why
#       it looked random. Tk then draws the "\n" as a line break AND the "\r"
#       as a line of its own: measured, one label, same text — 23 px on one
#       line, 40 px with "\n", 57 px with "\r\n". That third, empty line was
#       what he was looking at. _dh now unfolds, collapsing the break AND the
#       continuation line's leading space into ONE space (collapsing only the
#       CR/LF leaves "PostNord  och", which would then be wrong in every
#       search and every subject filter).
#   [x] ⚡ DO IT (DEL 09j) — a red button beside every Undo button. The undo
#       window exists so a mistake can be taken back; when you already know the
#       delete was right, waiting out the timer is dead time. Undo cancels, Do
#       commits. Same pair on the send bar: ✖ Cancel send / ⚡ Send now.
#   [x] REMINDERS THAT SCALE (DEL 04f3). Not fixed before — the event EDITOR
#       was made adaptive in August, the reminder POP-UP was not, and the
#       pop-up is the one he meets. Its three buttons were the constants
#       5/15/60. They are now a share of the time actually LEFT: 24 h out
#       offers 3 h / 8 h / 12 h, a week out offers 1/2/3 days, three hours out
#       never offers a day, and nothing offered can fire AFTER the event.
#   [x] FIVE TOOLBAR COLOURS THAT MEAN SOMETHING: ↻ Refresh green, ↩ Reply
#       orange, 📌 Notes the fifth colour (teal — green went to Refresh),
#       beside the blue New Message and the red Delete.
#   [x] 📌 POST-IT BOARD (DEL 04g3) — "Notes-systemet känns lite
#       överkomplicerat… ha något liknande i Freemail". The old notes are .eml
#       files written in a full compose window: right for "save this MESSAGE
#       to my own disk", all cost for "milk, eggs, ring the dentist". So the
#       small kind now exists beside it, built like his own Notes.py: ONE
#       readable text file (Helpfiles/Freemail/Notes/postit.txt), a board of
#       coloured cards, no field you must fill in, no Save button — it saves
#       itself about a second after you stop typing, and an empty title is
#       filled from the first line. Ctrl+Shift+T; the long note keeps Ctrl+T.
#   [x] "BLIR DET PROBLEM ATT GÖRA SAKER SAMTIDIGT SOM DET ÄR UNDO-PERIOD?"
#       It could, and the fault was not the Move — it was any RELOAD during the
#       limbo. A message in limbo is out of the list but still on Gmail, so a
#       failed move (which reloads), ↻ Refresh, a folder switch or the
#       auto-check handed it straight back, and Undo then added a SECOND copy.
#       DEL 09k: _pending_delete_keys is the memory of "gone, pending"; the
#       list filters those keys out however it was rebuilt (before the threads
#       are grouped, so an expanded conversation cannot show them either), and
#       Undo restores by KEY — never twice, and never into a folder he has
#       since walked away from.
#   [x] THE LOG NOW HAS MOVE (DEL 09l) — "så att jag kan se om något inte MOVE
#       och i så fall varför". It only ever logged moves a RULE made. Three
#       kinds now: "move-try" (what was asked for), "moved" (what went), and
#       "move-failed" — one line per message, carrying the server's own words.
#       Covers the by-hand move, the cross-account move, and "Server changes is
#       off and you said no". The Log window gained a "Moves (all three)" scope
#       and a red colour for the ones that did not happen.
#   [x] Tests: scratchpad/smoke_freemail.py — 9 checks, green, run against the
#       real program in demo mode. It caught a crash worth remembering: a
#       widget's own `pady` takes ONE distance, and `pady=(0, 6)` (fine on
#       pack/grid) raises TclError: bad screen distance "0 6" — which would
#       have killed the post-it board the second time it was opened.
#
#   --- BATCH 33: WHICH PARCEL IS THIS? (Issu 2026-08-23) --------------------
#   [x] THE PROBLEM, in his words: three Tradera receipts arrived within two
#       minutes (two for BGGGeekmarket, one for issusbarn) and collapsed into
#       one row. "Jag ser inte produktens namn eller mottagarens stad. Jag ser
#       mottagarens namn." Same subject to the letter, same sender, three QR
#       codes called QrCode-<number>.png. Nothing on screen said which was
#       which.
#   [x] THE TOWN AND THE TITLE ARE NOT IN THE MAIL. Checked before writing a
#       line: the HTML body of every one of his shipping receipts contains
#       "Zwickau" exactly zero times. The title is in the body; the ADDRESS
#       only ever exists inside the attached Kvitto.pdf, and the COUNTRY only
#       inside Fraktsedel.pdf. So the program had to learn to read a PDF —
#       stdlib only (DEL 09m, "3b. Minimal PDF READER"), same rule as the PDF
#       writer beside it: one .py, one EXE, nothing pip-installed. zlib
#       unpacks the content streams, the text operators are walked, and each
#       font's /ToUnicode CMap translates the codes: a carrier label uses
#       subset fonts where "SWEDEN" is stored as "6:('(1".
#       Two traps, both cost an hour: the CMap must be resolved PER RESOURCE
#       DICTIONARY (one merged name→font table let the page's Helvetica "/F1"
#       win over the label's subset "/F1", and the receipt came out as
#       mojibake), and a line may NOT be broken on every Td — PostNord places
#       each GLYPH with its own "<n> 0 Td", so "Kvitto" arrived as six
#       one-letter lines. Only a move that changes Y starts a line.
#   [x] WHERE THE FACTS SHOW UP. The list row replaces the worthless subject
#       with "📦 Tyskland · Tärning, svaga siffror" (display only — search,
#       filters and rules still see the real subject). The opened message gets
#       a green strip: town/country, title, buyer + alias, carrier, amount,
#       tracking and item number. Facts are cached in Accounts/shipping.json,
#       so the rows are filled the moment the program starts, before any body
#       has been downloaded again.
#   [x] "00-STAD---TITEL---" — his own filename format, on the attachment
#       right-click and as a one-click button on the strip:
#       "00-Tyskland---Tärning, svaga siffror---QrCode-3505190755.png", plus
#       "Save all of them with that prefix…" for the whole set. The "00-"
#       is load-bearing: it sorts the parcels still to be handed in to the top
#       of the folder. Title capped at 60 characters and every character
#       Windows forbids scrubbed, so the path cannot blow the 260 limit.
#   [x] "OM INTE SVERIGE, SÅ LANDET" — his rule, and the better one: Zwickau
#       tells him nothing, "Tyskland" tells him customs paperwork. Sweden →
#       the town; abroad → the country. When the country cannot be
#       established the TOWN is used; the program never guesses "Sweden".
#       Labels state the country three ways and all three are read: a name
#       ("SWEDEN"), a bare code on its own line ("DE"), and a code glued to
#       the postcode ("ES-46183 LA ELIANA", "SE 726 31 Skultuna"). Every
#       label also carries the SENDER's Swedish address, so SE can only win
#       when nothing else appears at all.
#   [x] "DON'T MERGE IN THIS FOLDER" — asked for again, and it has existed
#       since 2026-08-19 on the FOLDER's own right-click, which is not where
#       anyone looks. It is now on the MESSAGE row's right-click too, because
#       the collapsed row of look-alikes is where you meet the problem. Same
#       setting, same folder, both directions. (His no_merge_folders list was
#       still empty and thread_view still on, which is why they collapsed.)
#   [x] Tests: scratchpad/test_ship.py — 43 checks green against the real
#       program and his real cache, plus a second pass on the row menu. It
#       runs the extractor over EVERY Tradera receipt on disk: 63 of 63
#       resolved, back to March, including parcels to Germany, France, Spain,
#       Lithuania, Hungary, Austria, Czechia, Ireland, Belgium, Switzerland,
#       the UK and the US. The one shipping mail that yields nothing is a
#       "your parcel was too heavy" notice with no attachments at all.
#
#   --- BATCH 34: THE MAIL RELOCATOR (Issu 2026-08-23, DEL 51) ---------------
#   [x] "Jag vill ha in en relocator-funktion … som skiljer sig från filter.
#       Jag matar in, som i de andra programmen … och de som jag väljer (som i
#       file manager … ett eller alla) körs och flyttar mail från olika/samma
#       konton till bestämda ställen. Filter kör vanligtvis vid hämtning …
#       Detta ska vara separat sak … körs enbart manuellt."
#   [x] So: File_manager's ⤴ Relocator, for mail. Tools → "⤴ Relocator — move
#       mail by rule… (manual only)". Rules live in Accounts/relocator.json,
#       NOT in filters.json, and nothing in DEL 51 is ever called by a fetch,
#       a timer or the filter dispatcher. That separation IS the feature.
#   [x] BUILT ON THE SWEEP, NOT BESIDE IT. A Relocator rule compiles to the
#       same `plan` _imap_sweep_search already understands, so it inherits the
#       read-only search, the batched _imap_move_uids, _split_protected and
#       the Gmail-label de-duplication instead of growing a second copy of
#       each. _reloc_plan is twenty lines where _sweep_plan is a hundred,
#       because a Relocator rule has no either/or sections — one search, all
#       terms ANDed.
#   [x] TWO SMALL THINGS THE SEARCH NEEDED. A bare SEARCH key (ALL, UNSEEN,
#       SEEN) takes NO argument, and sending an empty one makes the server
#       answer BAD — _args_for now skips it, and _term_show renders it for the
#       log. That is what lets "unread only" and "everything older than a
#       year" be asked of the server instead of downloading the folder.
#   [x] EVERY SAFEGUARD BORROWED FROM CODE THAT EARNED IT: ▶ searches first
#       and shows the count, the folders and the destination before anything
#       moves; 🔍 Count them all is read-only; Server changes must be on
#       (offered inline, and answering No leaves it off); a 🔒 protected
#       folder is never emptied; a message already in the destination is
#       skipped rather than moved onto itself, in either spelling of the
#       folder name; a rule with no destination — or one that says nothing
#       about WHICH mail — is refused rather than run, because it would move
#       a whole folder.
#   [x] DE-DUPLICATION IS PER ACCOUNT, never across them. Inside one account
#       the same Gmail message really does come back from Inbox and All Mail;
#       two accounts that both received the same mail hold two SEPARATE
#       messages, and collapsing those would move one and quietly leave the
#       other — exactly the class of bug batch 22 spent a day on.
#   [x] Cross-account rules go through _deliver_cross_account (fetching whole
#       messages, plan["full"]), so they cannot upload a header-only copy and
#       cannot deliver the same message twice — the two faults behind the
#       folder of empty receipts in August.
#   [x] Tests: scratchpad/test_reloc.py — 65 checks green, with the IMAP calls
#       and _save_settings replaced by recorders, so it proves the dangerous
#       half without touching Gmail: that No moves nothing, that a protected
#       folder is skipped while its neighbours still move, that mark-read runs
#       BEFORE the move (afterwards those uids no longer exist in the source
#       folder), that ▶▶ skips a switched-off rule, and that the question he
#       is asked names the real number and the real destination.
#
#   --- BATCH 35: WHICH OPERATOR (Issu 2026-08-23) ---------------------------
#   [x] "Få in i qr-kod-grejen, vilken operatör som det är (Post (i stället
#       för Postnord), DSV, DHL)." The filename is now
#       00-DSV---Tyskland---Tärning, svaga siffror---QrCode-3505190755.png.
#   [x] THE CARRIER GOES FIRST, and that is the point of it: the carrier is
#       the ERRAND. DSV goes to ICA Kvantum, DHL goes to Pressbyrån — sorting
#       the folder by name now puts one trip's parcels together. His
#       spelling, not the carrier's: PostNord is "Post", and DB Schenker is
#       "DSV" — "Schenker har bytt namn till DSV", so January's receipts and
#       August's name the same company and the same counter, and the folder
#       must not sort one errand into two piles. _SHIP_FACTS_V went to 3 so
#       the receipts already cached as "Schenker" are read again.
#   [x] FOUR SOURCES, and the order matters. The MAIL BODY first, because it
#       is the one he read: an older Tradera receipt says "DB Schenker" in
#       the Kvitto PDF where the mail itself, and Tradera's own screen, say
#       DSV — same counter, and the mail is what he saw. Then the Kvitto's
#       "DSV, 1 kg" line; then the first carrier NAME in the papers; then the
#       sender's domain. Deliberately NOT the label's own branding: the
#       German parcel's label is GLS end to end, but it is handed in at DSV.
#   [x] Address lines are skipped in the name scan. Every PostNord receipt
#       ends "kundservice.digital.se@postnord.com", which is not evidence of
#       anything and would out-vote a real carrier line on somebody else's
#       receipt.
#   [x] A CARRIER ALONE IS ENOUGH FOR A FILENAME. A DHL or PostNord
#       "inlämningskvitto" is a QR code and nothing else — no town, no title
#       — and now saves as "00-DHL---qr-9601755102.png" instead of keeping
#       its meaningless name. The green strip still stays away from those:
#       carrier-only facts would draw a 📦 and nothing after it.
#   [x] shipping.json entries carry a version (_SHIP_FACTS_V). Without it the
#       receipts cached an hour ago would have served a carrier-less name for
#       ever, since the cache is what the list and the menu read.
#   [x] Dead code removed: _ship_summary was written for the reading pane and
#       never called — the strip builds its own text.
#   [x] Tests: 53 checks (was 43), including that the body outranks the
#       Kvitto, that the sender is the last resort, and that "Post" is the
#       spelling however PostNord wrote itself. All 65 Tradera receipts on
#       disk resolve; across everything in the receipts folders the carrier
#       is now known for every single one, and it is exactly the three names
#       he asked for — DHL 68, DSV 55, Post 34.
#
#   --- BATCH 37: THE RELOCATOR GROWS UP (Issu 2026-08-23) -------------------
#   [x] "Gör som med filter att jag kan lägga till flera saker, t.ex. 3 olika
#       subjects och 2 olika From, och att jag väljer om det räcker med en,
#       eller om någon ska ha kriteriet att det ska vara X OCH Y." So a
#       Relocator rule now carries a LIST of conditions in the filter
#       engine's own shape — {field, op, value, group} with group "all"
#       (MUST) or "any" (one of these will do). Sharing the shape is the
#       point: _split_conditions, _sweep_plan, _sweep_keep and
#       _filter_describe all work on a Relocator rule unchanged, so the two
#       rule kinds can never drift apart on what AND means. Three subjects as
#       alternatives become three server searches, each ANDed with the MUST
#       rows, unioned — which is how a two-section rule is asked of a server
#       with no reliable OR.
#   [x] "I många fall så vill jag bara kunna radera alla matchande mail, på en
#       och samma gång - efter X timmar/dagar." A rule now has an ACTION:
#       ⤴ move, or 🗑 delete. The delete is _imap_trash_uids, the same batched
#       path the whole-mailbox sweep uses, and it asks its own question —
#       "Delete 34 message(s)?" with the folders listed and the Gmail Trash's
#       30 days spelled out. Name the rule "Delete old receipts" and it is a
#       delete button for one kind of mail. A 🔒 protected folder is not
#       emptied by a delete rule either.
#   [x] AGE IS IN HOURS NOW, days being 24 of them. IMAP SEARCH only speaks
#       whole days, so BEFORE is given the whole cut-off day (a superset) and
#       _reloc_keep does the real comparison against the message's own time.
#       A too-narrow search would silently miss mail; a few extra headers cost
#       nothing. Rules saved yesterday migrate: from/to/subject/body become
#       conditions, older_days becomes older_h × 24, attach_only becomes
#       has_attachment.
#   [x] ⤴ ON THE TOOLBAR, immediately left of the 🔎 — "jag ser gärna
#       Relocate-ikonen innan förstoringsglaset". With side="right" the first
#       one packed sits furthest out, so it is packed AFTER the magnifier.
#   [x] A NARROWER TOOLBAR: "Contacts, refresh, Log o.s.v. — de knapparna kan
#       bli mindre breda så att programmet inte måste vara så bred." Padding
#       10 → 5 inside and 4 → 2 between: measured, the toolbar went from about
#       1575 px to 1365, so the window can be ~200 px narrower than the 1643
#       he has been running. The TEXT is untouched — a button you cannot read
#       is not narrower, it is gone.
#       Measured and NOT done: moving the expanding spacer to the end of the
#       method. It looks like it ought to stop the search box collapsing on a
#       narrow window and it does not — when the toolbar wants more than the
#       window has, Tk drops the last-packed children to one pixel whichever
#       order they were packed in. Only FITTING keeps them on screen.
#   [x] A NEW CONDITION ROW STARTS AS "any one of" + SUBJECT (Issu, same day,
#       after using it): that is the row you add most — one more subject line
#       for the same sender. The "one sender → their own folder" starter says
#       MUST + From instead, through the rule's "_new_row" key, because a rule
#       about one sender should not open on a subject box.
#   [x] Tests: scratchpad/test_reloc.py — 101 checks, green. Among them: three
#       alternatives really produce three searches each carrying the MUST
#       row; "is" is re-checked locally because IMAP only does "contains";
#       older-than-48-h keeps a 100-hour-old message and drops a 10-hour-old
#       one; a delete rule trashes and never moves; No deletes nothing; a
#       protected folder is skipped while its neighbours still go; and a rule
#       saved by yesterday's version still runs.
#
#   --- BATCH 38: THE APOSTROPHE (Issu 2026-08-23) ---------------------------
#   [x] "Något är konstigt med min 'Potentiella köpare'-regel. Jag har flera
#       som är minst ett dygn gamla… och jag har testat med både [BGG] I'm
#       och I'm interested in. Apostrof-problem?" Yes — but not his typing,
#       and not our quoting. His own log settles it, same folder, same minute:
#
#         SUBJECT "Sålt objekt"       → 3 uid(s)
#         SUBJECT "Skickade: \""      → 1 uid(s)
#         SUBJECT "Beställt:"         → answered
#         SUBJECT "I'm interested in" → 0 uids   (×5 accounts, every run)
#         SUBJECT "[BGG] I'm"         → 0 uids   (×5 accounts, every run)
#
#       Colons, quotes, brackets and å/ä/ö are all fine. ONLY the apostrophe
#       comes back empty — while fifteen matching geekmails sit in his Inbox
#       with "[BGG] I'm interested in …" in the subject. Gmail's IMAP SEARCH
#       is served by Gmail's own word index, which folds the apostrophe away
#       ("I'm" → "im"), so a phrase carrying one matches no word at all.
#       There is no quoting that fixes it — it is not syntax, the server
#       simply has no such token.
#   [x] THE FIX: ask for less, check it here. _search_soften takes the
#       longest WHOLE-WORD stretch of the phrase with no apostrophe in it —
#       "I'm interested in" → "interested in", "[BGG] I'm" → "[BGG]" — and
#       _soften_searches rewrites the plan with it. Whole words, because
#       Gmail has no token "m" either. The answer is always a CONTIGUOUS
#       piece of the original, so the search can only ever be wider, never
#       narrower, and _sweep_keep narrows it back to exactly the rule.
#   [x] The condition's index is dropped from the search's `cis` in the same
#       breath — that is what stops the server's answer being taken on trust
#       and makes the whole phrase be re-tested locally.
#   [x] Softening happens on the PLAN, not down inside the IMAP call: both
#       rule kinds are built from the plan, so the filters' whole-mailbox
#       sweep is fixed by the same lines — and a plan is something a test can
#       look at, which the inside of a live IMAP session is not.
#   [x] BODY terms are deliberately NOT softened. The body is never
#       downloaded, so a widened body search could not be re-checked and
#       would file mail the rule does not really match. Better it keeps
#       failing loudly.
#   [x] Tests: scratchpad/test_apostrophe.py — 15 checks against his REAL
#       rule out of relocator.json and his REAL cached geekmails, with a
#       stand-in server that indexes the way his log shows Gmail indexing.
#       It finds them now; with the softening switched off it finds 0, which
#       is exactly what his log recorded.
#
#   --- BATCH 39: CONTACTS YOU CAN EDIT, AND ONES NEVER SAVED ----------------
#   --- (Issu 2026-08-25) ----------------------------------------------------
#   [x] "det finns fält för Add/update, men jag kan inte klicka på någon
#       kontakt och få dem till den rutan, för att redigera." True — the
#       address-book rows had a ★ and a ✕ and nothing in between. A contact
#       could be deleted and retyped, never corrected. Now the ROW ITSELF is
#       clickable (`_edit_contact`): it fills Name/Email/Group, highlights
#       the row in C_MSG_SEL, and the button becomes "💾 Save changes".
#       "✖ Clear" (and Esc) lets go of it again.
#   [x] Editing the ADDRESS replaces the contact instead of twinning it —
#       `editing["email"]` remembers what it was called when the edit
#       started, and BOTH the old and the new address are dropped before the
#       record is appended. Without that, correcting a typo would have left
#       the typo sitting in the book, still feeding autocomplete.
#   [x] An edit keeps everything it did not touch: ★ favorite and group are
#       carried over from the old record, so renaming somebody cannot
#       quietly un-favorite them.
#   [x] Deleting a row while editing clears the form. The form held an INDEX;
#       after a pop, that index is a different person. This is the whole
#       class of bug that makes an edit land on the wrong contact.
#   [x] "Det vore bra om jag kunde lägga till vissa prefix/suffix/domäner/
#       adresser, som aldrig ska sparas i contacts." → 🚫 Never save…, a
#       list of rules kept in the SAME addressbook.json (`never_save`), so
#       every path that can add a contact already has it in hand. Four kinds
#       because that is how the junk actually looks: `address` (exact),
#       `domain` (that domain and anything under it — mail.shop.example yes,
#       notshop.example no), `prefix` (the address starts with it) and
#       `suffix` (the address ends with it, OR the name before the @ does,
#       so both ".ru" and "-bounce" work). Case-insensitive; a BLANK rule
#       matches nothing, which is the failure mode that would matter here.
#   [x] Enforced at the one door every automatic contact comes through —
#       `_merge_contacts` — which is auto-save-on-reply, auto-save-on-send,
#       .vcf import and CSV import all at once. A blocked address is logged
#       at info with the rule that stopped it, not swallowed.
#   [x] Typed in BY HAND it asks instead of refusing: a person meant it, and
#       the rules are about what happens automatically. Answer yes and it is
#       saved.
#   [x] A new rule NEVER deletes anything by itself. "🧹 Clean the book now"
#       is the broom, and it shows the full list of matching contacts before
#       removing one. "✨ Add the usual robots" fills in noreply / no-reply /
#       donotreply / bounce / mailer-daemon / postmaster in one press.
#   [x] Tests: test_contacts.py (62 checks — every rule kind and its
#       near-misses, the blank-rule trap, _merge_contacts, then the REAL
#       dialog driven by real clicks: edit, rename the address, keep the ★,
#       Clear, ask-on-hand-typed, delete-while-editing, the rule editor and
#       the broom) and test_contacts_layout.py (13 — a fourth footer button
#       still fits in 620px and every one of them is mapped with a real
#       width — the 1-pixel-invisible-panel trap again).
#
#   --- BATCH 40: PAIRS INSIDE THE EITHER/OR SECTION (Issu 2026-09-07) -------
#   [x] Sections could say "MUST all of these" and "…and at least one of
#       these". They could not say the shape his order mail actually has:
#           (Subject "Beställningsuppdatering" AND From vinted)
#        OR (Subject "är på väg!"              AND From sellpy)
#       — two complete alternatives, each one a PAIR. In sections alone that
#       is two rules, because the either/or section ORs its rows one by one:
#       put all four in it and a Sellpy mail merely saying
#       "Beställningsuppdatering" fires the rule.
#       So an either/or row now carries a PAIR LETTER. Rows sharing a letter
#       are ONE alternative and must be true together; "–" leaves a row on its
#       own, an alternative by itself. The rule fires when the MUST section
#       holds AND at least one alternative holds WHOLE (_split_alternatives).
#       Every rule already saved has no letters at all, so for all of them
#       this changes exactly nothing — same no-op migration as sections were.
#   [x] It runs through the whole engine, not just the matcher:
#       • _filter_describe draws a pair as one parenthesised AND, so "OR"
#         always separates whole alternatives — "(Subject … AND From …) OR
#         (Subject … AND From …)".
#       • _sweep_plan builds ONE server search per ALTERNATIVE with the pair's
#         rows ANDed into it (two searches for the rule above, not four). A
#         row the server cannot search only narrows its own alternative and
#         _sweep_keep re-checks it locally — except a BODY "doesn't contain",
#         which cannot be re-checked from headers, and is refused as before.
#       • _sweep_keep re-checks a pair AS a pair, so a swept crossed match
#         (Sellpy + "Beställningsuppdatering") is thrown away again.
#       • The diagnosis counts ALTERNATIVES, not rows: a half-true pair is not
#         "one of the either/or rows matched", and saying so was the exact
#         confusion pairs exist to remove. Near-miss lines read "[either A]".
#       • _cond_signature includes the letter (two rows paired are a different
#         rule from the same two unpaired), and _merge_rules re-letters every
#         incoming pair, because two rules folded together can each call their
#         pair "A" and mean different things.
#   [x] The Relocator's rule dialog gets the same letter box (it shares the
#       engine), and _reloc_norm keeps the label on an "any one of" row while
#       dropping it from a MUST row, where it would name nothing.
#   [x] Tests: test_filter_pairs.py — 35 checks, engine only, pulled out of
#       this file with ast so no GUI starts. The Vinted/Sellpy rule and its
#       crossed matches, a MUST row on top, old sections rules and even older
#       match_mode all/any rules unchanged, a lone row beside a pair, the
#       sweep plan (one search per alternative, the unsearchable-row cases),
#       _sweep_keep, and the merge re-lettering.
#
#   --- BATCH 41: PASTED "mailto:" LINKS (Issu 2026-09-09) --------------------
#   [x] Copying an address off a web page gives you the LINK, not the address —
#       "mailto:info@sallesror.se" — and the prefix had to be deleted by hand
#       every single time. It is now unwrapped automatically (_strip_mailto):
#         • the chip shows the plain address the instant it is pasted, so
#           there is nothing left to delete and nothing to wonder about;
#         • _clean_one_address does it too, which is the one point EVERY
#           address passes through (compose, Smart Reply, the address book,
#           a restored draft, the outbox, the last clean before SMTP), so a
#           path that never learned about mailto: still cannot send one;
#         • "?subject=…&body=…" is dropped — in an address field a smuggled
#           subject would go out as part of the recipient — and "%40" and the
#           other percent escapes are decoded, since a mailto: URL may write
#           the "@" that way and "info%40sallesror.se" bounces.
#       It is deliberately narrow: a string with no "mailto:" in it is
#       returned untouched, and only the address token right after the
#       "mailto:" is rewritten, so a display name keeps whatever it says —
#       "Who? <mailto:a@b.se>" becomes "Who? <a@b.se>", question mark intact.
#       Unwrapping is NOT logged as address corruption (nothing was corrupt),
#       but the field still redraws so the correction is visible.
#   [x] Tests: test_freemail_mailto.py — 28 checks, engine only, pulled out of
#       this file with ast so no GUI starts. Every paste shape (bare, upper
#       case, spaced, ?subject=, <angled>, %40, with a display name), the
#       untouched-if-no-mailto cases, a whole mixed To: field, the old ♣
#       corruption guard still firing, and the chip field's own call.
#
#   --- BATCH 42: FOLDER AGEING (Issu 2026-09-09) ----------------------------
#   [x] "Jag har skapat Delete later i Temporär … jag vill kunna högerklicka på
#       katalogen och välja funktioner, t.ex. delete everything older than XX
#       hours, eller mark everything as read after xx hours … ungefär som
#       filterregler men på kataloger och bara påverka innehållet, beroende på
#       hur gamla mailen är."
#       Right-click a folder → ⏳ Age the mail in "…". A filter asks who sent it
#       and fires once, on arrival; this asks only how old it is and keeps
#       asking, every quarter of an hour, for as long as the mail sits there.
#   [x] A rule is a LADDER, which is his own example and the reason this is not
#       one more filter condition:
#           "Delete later"   after 24 h → mark it read
#                            after 48 h → move it to the Trash
#       Each message gets the LAST step whose time has come, so a three-day-old
#       mail is trashed outright instead of being marked read today and binned
#       tomorrow. Steps: mark read · move to a folder · move to the Trash.
#       Age is the server's INTERNALDATE — when it ARRIVED, not the Date: the
#       sender wrote (same reasoning as _sweep_age_terms).
#   [x] The rails, every one of them on by default:
#       • nothing is ever ERASED — "delete" is the Trash, 30 days, recoverable;
#         Empty the Trash stays a thing you press yourself (DEL 04s);
#       • a STARRED message is never touched — a star is him saying "not this
#         one" by hand, and no clock may outvote that;
#       • a step can say "only if I have already read it", so nothing unseen is
#         thrown away;
#       • a PROTECTED folder is never aged — protection means "nothing
#         automatic may move mail out of here" and this is exactly that;
#       • it stops and ASKS before touching more than `ask_over` (50) messages
#         in one run: typing 2 where you meant 200 is a real way to lose a
#         folder, and this is what makes that mistake survivable;
#       • it is a server change, so "Server changes" gates it like the rest —
#         with that off it does nothing, silently, and the dialog says so;
#       • the background pass never asks a question. Anything that would need
#         one waits for ▶ Run now.
#   [x] 👁 "Show me what it would do now" is read-only and lists every message,
#       its age in hours and what would happen to it — the same
#       preview-before-anything-happens the dated folders make (DEL 04l), and
#       the preview and the real run share one scan, so they cannot disagree.
#   [x] Accounts → Folder ageing… is the same editor as a list of every rule.
#       Storage: Accounts/folderage.json. The engine (_age_plan, _age_steps,
#       _age_describe, _imap_age_scan) is DEL 04r; the folder menu, the editor
#       and the tick are in the app class.
#   [x] Tests, both pulled out of this file with ast so importing 2.7 MB (and
#       its log file, and his account store) never happens:
#       • test_folder_ageing.py — 56 checks, engine only. The 24/48 ladder
#         itself, the last-step-wins rule, starred and unread guards, steps
#         typed out of order, a missing move destination, rubbish in the JSON,
#         the include_sub matching (and its near-miss "Temporär2", and the
#         same folder spelled in raw modified-UTF-7), the quarter-hour brake,
#         and the proof that the BEFORE search hint can only ever ask for MORE
#         than the plan will act on.
#       • test_folder_ageing_gui.py — 33 checks, and it really builds the
#         editor, with real Tk widgets, against a stub app: no widget ends up
#         1 pixel wide (the invisible-panel trap again), the step list sorts
#         itself as you add and change steps, a non-numeric or zero wait is
#         refused, an enabled rule with no steps is refused, the 🔒 and
#         "Server changes is off" warnings appear when they should, and the
#         buttons reach the app. Nothing it does touches Gmail or Helpfiles.
#
#   --- STILL ON THE LIST (asked for, not built yet) -------------------------
#   [ ] Live whole-mailbox IMAP search on the QUICK filter too (the scoped
#       search is real IMAP; the instant type-ahead filter is still local).
#   [x] The whole-mailbox sweep also MOVES and MARKS READ, not just trashes —
#       📁 Move all to… and ● Mark all read next to the Trash button,
#       same search/batching/confirmation, gated by Server changes like the
#       rest (2026-08-08).
#   [ ] Read receipts, PGP/S-MIME, RSS — not planned, listed so nobody asks
#       twice.
#
#   --- NICE TO HAVE (later) -------------------------------------------------
#   [x] Frozen column header — Subject/Correspondent/Date headers stay visible
#       while the message list scrolls (separate ml_hdr frame above the canvas).
#   [x] Contact colours — assign a colour to a sender so it stands out in the
#       list; multiple senders can share a colour to form informal groups
#       (contacts.json, _contact_color, Accounts → Contact colours). Doubles
#       as a lightweight colour-coded address book.
#   [x] Full address book — Accounts → Address book: store/edit named contacts
#       (name/email/group, filter), and the compose To: field auto-completes
#       from it (addressbook.json, _addressbook_dialog, ComposeWindow._ac_*).
#   [x] OS-level new-mail signals — the unread count is shown in the window
#       TITLE (so the taskbar button and Alt-Tab carry it), and the taskbar
#       button FLASHES until you look at the window (FlashWindowEx, and only
#       when the window is not already in front). Together with the in-app
#       toast that covers "I was away from the computer".
#       A tray icon was deliberately NOT built: Shell_NotifyIcon via ctypes
#       needs its own message loop to receive clicks, and a half-working tray
#       icon that swallows the window is worse than no tray icon.
#   [x] HTML mail rendering — "View formatted (HTML)" opens a popup via
#       tkinterweb; remote images blocked by default (_strip_remote_images),
#       toggle to load them. Main pane still shows plain text. (CEF not needed.)
#   [x] Thread/conversation view — was BROKEN, not merely unpolished: every
#       message of a conversation got its own top-level row, and expanding one
#       re-rendered its siblings underneath, so a three-message thread showed
#       three times collapsed and five times expanded. Now one row per
#       conversation (the newest message, with a "(3)" count), the + opens the
#       rest indented with "↳", and View → Threaded view switches to a flat
#       one-row-per-message list. Expand/Collapse all in the same menu.
#       The twisty is keyed on the THREAD id, not the message id, because
#       which message leads a conversation changes as new mail arrives.
#   [x] Thread ordering used the message id — which with a real account is the
#       IMAP UID as a STRING, so "100" sorted before "99". Both the list and
#       the reading pane's "the message directly before this one" were
#       affected. Now chronological (_thread_order).
#
#   --- BATCH 35: A TICK THAT STAYS, AND A REPLY YOU CAN READ (Issu 2026-09-20)
#   [x] "jag kan markera ett mail... det kan vara updating/loading... eller
#       inte, och så blir den klar och mailet är inte längre markerat... jag
#       måste markera igen. Det är jobbigt."  THREE separate causes, all fixed:
#       • _render_one_row paints a row from its read/unread colour ALONE, so
#         every full redraw drew the whole list unselected. The tick was still
#         in _selected_ids — only the colour had gone, which from the outside
#         is exactly the same thing. _render_msg_list now ends with
#         _repaint_selection() + _update_bulk_bar(), so no caller can forget.
#       • A refresh replaces every row with a BRAND-NEW dict off the wire, and
#         _selected_ids holds ids belonging to the objects being thrown away.
#         _carry_selection re-points them: Message-ID first, reply-key second,
#         so a mail a rule MOVED (same Message-ID, new UID, new id) keeps its
#         tick instead of losing it. Used by _apply_messages AND by the
#         instant-from-cache render in _refresh_messages.
#       • _apply_messages ended a background check with
#         `self._selected_ids = {keep.get("id")}` — collapsing however many
#         rows you had ticked down to the one that happened to be open. The
#         carried set is kept now; the open message only joins it when nothing
#         at all survived.
#       Switching folder clears the ticks on purpose (_select_folder): an id
#       is a per-folder IMAP UID, so carrying "42" into another folder would
#       tick whatever mail happened to be number 42 there.
#   [x] "Originaldelen i Reply, kan må gott av zoom +-, för att lättare kunna
#       läsa den texten... och att reply sedan minns förra inställning, av
#       zoom och hur jag har expanderat fönstret/originalmeddelande-delen, och
#       en (go back to) default-knapp (och gärna en favoritknapp där jag kan
#       spara mitt favoritläge)."  Both reply windows got the same strip:
#           🔍 Zoom their text:  [A −] [ 9 pt] [A +]  |  [↺ Default]
#                                [★ Favourite] [📌 Save as favourite]
#       Ctrl + / Ctrl − / Ctrl 0 and Ctrl+wheel over the original do the same.
#       THREE remembered things, deliberately not one (_RecipientFields,
#       shared by Reply and Smart Reply, keyed on self._layout_key):
#         • LAST — zoom + splitter, written when the window closes and put
#           back when it opens. The window's own size/position was already
#           remembered (_apply_remembered_geometry); this is what is INSIDE.
#         • DEFAULT — _REPLY_LAYOUT_DEFAULTS, the numbers the program ships
#           with. ↺ Default is the way back when the remembered layout has
#           drifted somewhere unusable.
#         • FAVOURITE — one whole layout (zoom, splitter, width, height) you
#           pin yourself with 📌 and jump back to with ★. Saved to disk the
#           moment you pin it, so it survives a crash as well as a close.
#   [x] SECOND PASS, same day. "knapparna hamnade längst till höger så ser
#       mer ut som kopplade till min svars-del (som också skulle kunna må bra
#       av zoom, faktiskt)." Quite right — so the strip was split in two and
#       each half moved over the pane it acts on:
#         • LEFT, on the "Quote original on send" row, directly over the
#           original: ☑ Quote original on send · 🔍 Original: A− [9 pt] A+
#         • RIGHT, on the Often-used-text row, directly over your answer:
#           Often-used text: ➕ ➕ ➕ · 🔍 Answer: A− [10 pt] A+ ·
#           ↺ Default · ★ Favourite · 📌 Pin
#       The ➕ buttons moved in front of the answer zoom on purpose ("för att
#       tydligare visa att de har med Answer-delen att göra") — they type into
#       your box, not his. Default/Favourite/Pin stayed where they were, with
#       the answer group, because they are about the WHOLE window.
#       Two rows rather than one: all of it side by side comes to ~1050 px and
#       the window's own default is 680, so one row would simply have been cut
#       off. Smart Reply has no left/right split to respect, so its strip keeps
#       both zoom groups and the buttons on the one row it already had.
#       Every compose window (New message, Forward, Note) gets the answer zoom
#       and the three buttons too — they all have a body you have to read.
#       Keyboard: Ctrl + / Ctrl − / Ctrl 0 size YOUR text (that is where the
#       cursor is), Ctrl+Shift the same three size THEIRS, and Ctrl with the
#       mouse wheel sizes whichever of the two you are hovering over.
#   [x] "Vissa folk är tokiga och skickar meddelanden till dussintals
#       mottagare (i CC). Det tar upp en himla plats och vanligtvis så vill man
#       inte se vem de andra är." The READING pane already folded those
#       (recipients_max, 2026-08-08) — what did not was the To:/Cc:/Bcc: field
#       in the reply itself, where Reply All drops all thirty of them as chips
#       that wrap onto row after row and push the message off the screen.
#       _ChipEntry now folds to ONE row above `compose_recipients_max` (3):
#       as many chips as the width takes, then a "+27 more ▾" pill. Clicking
#       the pill — or the ▾ beside the Cc: caption, which appears only when
#       there is something to open — shows them all, and ▴ folds them back.
#       Display only: .get() has always returned every chip, so a folded field
#       sends exactly what an open one does. The caption shows the count
#       ("Cc: (28)") so the number is never hidden, only the addresses.
# ==============================================================================

# ******************************************************************************
# DEL 00 — IMPORTS & CRASH CATCHER
# ******************************************************************************

import ctypes
import json
import logging
import os
import platform
import subprocess   # MODULE level on purpose: open_path/_launch_my_app use it. It was only
                    # imported inside methods, so every hand-over to PDFull/WhyBrowse hit a
                    # NameError, was swallowed, and fell back to Windows' own default app.
import sys
import traceback
import tkinter as tk
from tkinter import messagebox
from datetime import datetime

# ── AppUserModelID BEFORE tk.Tk() ─────────────────────────────────────────────
try:
    ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
        "IssuOrg.Freemail.1")
except Exception:
    pass

# ── Resolve paths relative to THIS file (works as .py and as .exe) ───────────
# Everything this program owns now lives in ONE folder named after it —
# Helpfiles/Freemail/ — so it follows the "each program gets its own Helpfiles
# subfolder" convention and the generic 'settings.json' can't collide with any
# other program's. Only the LOG stays in Helpfiles/0---Empty/ (house rule).
# Data written before this change is moved over automatically on first run by
# _migrate_to_freemail_dir() (called from main()).
def _find_home(start):
    """The folder that holds Helpfiles, searching upward from `start`.

    Helpfiles is a SIBLING of the program's folder, not a child of it, so the
    answer is "the nearest folder above me that contains Helpfiles". The same
    three lines then work from Py\\, from Folder-exe\\<Name>\\ and from the old
    layout where the .py sat directly beside Helpfiles - and a group like
    Chess\\ that keeps its own world finds its own.

    Capped at four levels: a stray Helpfiles far up the tree must not be
    adopted by accident. Nothing found means behave exactly as before and use
    the program's own folder, which is what keeps a working copy under test
    away from his live data.
    """
    # 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():
    """Where Helpfiles and Icons live, as .py and as a frozen build alike."""
    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__)))


def _own_dir():
    """The folder this program's own file sits in.

    Its neighbours are the FIRST place to look for another of his programs -
    they are kept together, whether that folder is 1---Blandat, the Py folder
    under 0---Python, or one of his own making. _program_home() is the DATA
    root, and in the 0---Python layout that is one level ABOVE the programs,
    so a lookup that starts there walks straight past the program standing
    right next to it.
    """
    if getattr(sys, "frozen", False):
        return os.path.dirname(os.path.abspath(sys.executable))
    return 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 ""


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.

    The .py is the file that is actually edited, so it is always current.
    A build is worth reaching for only when there is no source or no
    interpreter - a machine without Python, or a program only ever shipped
    as a build."""
    if not name or name.lower() == MY_PROGRAM_NAME.lower():
        return False                      # never hand a thing to myself
    cmd = work = None
    for home in _my_app_roots():
        script = os.path.join(home, "Py", name + ".py")
        exe = os.path.join(home, "Folder-exe", name, name + ".exe")
        if os.path.isfile(script):
            pyw = _real_pythonw()
            if pyw:
                cmd, work = [pyw, script, str(argument)], os.path.dirname(script)
                break
        if os.path.isfile(exe):           # no source, or no interpreter
            cmd, work = [exe, str(argument)], os.path.dirname(exe)
            break
        if os.path.isfile(script):
            break                         # found the tree; do not look further
    if not cmd:
        return False
    try:
        subprocess.Popen(cmd, cwd=work or None)
        return True
    except Exception:
        return False


def open_url(url) -> None:
    """Open a link with MY browser (or mail client), else Windows' default."""
    u = str(url or "").strip()
    if not u:
        return
    try:
        if _launch_my_app(_target_for(u), u):
            return
    except Exception:
        pass
    try:
        webbrowser.open(u)
    except Exception:
        pass


def open_path(path) -> None:
    """Open a file or folder with MY program for it, else let Windows decide."""
    p = str(path or "")
    if not p:
        return
    try:
        if _launch_my_app(_target_for(p, os.path.isdir(p)), p):
            return
    except Exception:
        pass
    try:
        os.startfile(p)
    except Exception:
        try:
            webbrowser.open(p)
        except Exception:
            pass




def _freemail_base_dir():
    r"""Where the mail, accounts and settings live.

    __file__ is the trap here: in a frozen build it points INSIDE the payload
    folder (F(re)email_data\), which ExeForge deletes and rewrites on every
    single build - so mail written there would vanish with the next rebuild.
    A frozen build therefore uses PROGRAM_HOME when that folder really holds a
    Freemail directory, and only falls back to beside the .exe when it does not.

    Running the .py still follows the script, so a working copy under test
    cannot touch his live mail.
    """
    return _program_home()


_BASE_DIR    = _freemail_base_dir()
# Save as... / Save the QR code as... / Save all... always open in this folder.
ATTACH_SAVE_DIR_DEFAULT = r"X:\0---Temp"
_HELPFILES   = os.path.join(_BASE_DIR, "Helpfiles")   # the SHARED Helpfiles root
_FM_DIR      = os.path.join(_HELPFILES, "Freemail")    # this program's own folder
_LOG_DIR     = os.path.join(_HELPFILES, "0---Empty")   # logs only (house rule)
_SETTINGS_F  = os.path.join(_FM_DIR, "settings.json")

os.makedirs(_LOG_DIR, exist_ok=True)
os.makedirs(_FM_DIR, exist_ok=True)

# ── Logging ───────────────────────────────────────────────────────────────────
_log_file = os.path.join(_LOG_DIR, "Freemail.log")
# encoding="utf-8" is NOT optional here (Issu 2026-08-03). Without it Python
# writes the log in the Windows ANSI code page, and every folder name, subject
# line and arrow in the filter diagnosis came out as "Tempor?r" and "→" —
# a log about Swedish mail that cannot spell Swedish is no evidence at all.
# errors="backslashreplace" keeps a genuinely undecodable byte visible instead
# of killing the log line it appears in.
# ── A log that does not drown itself (Issu 2026-08-08) ────────────────────────
#
# Measured on his machine: Freemail.log had reached 24.1 MB / 201,614 lines,
# and EIGHTY PER CENT of it was the once-a-minute filter dump — every rule,
# with its full plain-English reading, written again whether or not anything
# matched. A log nobody can read is not a log; finding the three stuck outbox
# messages meant grepping through all of it.
#
# Two changes. This one caps the FILE: it rotates at 4 MB and keeps three old
# ones, so it can never grow without limit again. The other is in
# _record_filter_diag, which now stays quiet when a background run matched
# nothing.
_LOG_MAX_BYTES = 4 * 1024 * 1024
_LOG_KEEP      = 3

try:
    from logging.handlers import RotatingFileHandler
    _handler = RotatingFileHandler(
        _log_file, maxBytes=_LOG_MAX_BYTES, backupCount=_LOG_KEEP,
        encoding="utf-8", errors="backslashreplace")
    _handler.setFormatter(logging.Formatter(
        "%(asctime)s  %(levelname)-8s  %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S"))
    logging.basicConfig(level=logging.DEBUG, handlers=[_handler])
except Exception:
    # Rotation is a convenience; never let it stop the program from logging.
    logging.basicConfig(
        filename=_log_file,
        level=logging.DEBUG,
        format="%(asctime)s  %(levelname)-8s  %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
        encoding="utf-8",
        errors="backslashreplace",
    )
log = logging.getLogger("Freemail")

# ── Global crash catcher ──────────────────────────────────────────────────────
def _handle_exception(exc_type, exc_value, exc_tb):
    if issubclass(exc_type, KeyboardInterrupt):
        sys.__excepthook__(exc_type, exc_value, exc_tb)
        return
    msg = "".join(traceback.format_exception(exc_type, exc_value, exc_tb))
    log.critical("UNCAUGHT EXCEPTION:\n%s", msg)

    # ALWAYS put it on stderr as well as in the log. A crash dialog is only
    # useful when there is someone in front of the screen to click it.
    try:
        sys.stderr.write("\nF(re)email — unhandled exception:\n" + msg)
        sys.stderr.flush()
    except Exception:
        pass

    # Only offer the dialog if a Tk main window actually exists. Without this
    # guard a failure BEFORE the window is up (a bad settings file, a missing
    # DLL, an import error) pops a modal box that nothing can dismiss — the
    # program then hangs forever with the real error hidden behind it, which
    # is precisely what happened while this program was being tested.
    try:
        if getattr(tk, "_default_root", None) is not None:
            messagebox.showerror(
                "F(re)email — Crash",
                f"An unexpected error occurred.\n\nDetails saved to:\n"
                f"{_log_file}\n\n{exc_value}")
    except Exception:
        pass

sys.excepthook = _handle_exception


# ******************************************************************************
# DEL 01 — SETTINGS (persistent, JSON)
# ******************************************************************************

# Special sentinel used for the "All Accounts" virtual account (defined here
# so _DEFAULT_SETTINGS can reference it before DEL 05 is reached)
ALL_ACCOUNTS_ID = "__ALL__"

_DEFAULT_SETTINGS = {
    "win_width":   1200,
    "win_height":  700,
    "win_x":       80,
    "win_y":       60,
    "sash_left":   220,
    "sash_right":  520,
    "win_zoomed":  False,   # was the window maximized when it was last closed
    "last_account": ALL_ACCOUNTS_ID,
    "last_folder":  "Inbox",

    # Message list: which column is sorted, and which way (set by clicking a
    # column header). Listed here so a fresh settings.json documents them.
    "sort_col":    8,       # 8 = Date (was 7 before the ✉ column was inserted)
    "sort_desc":   True,    # newest first
    "msg_cols_v":  1,       # message-list column layout version — see migration

    # Background mail check, in minutes. 0 = off (Tools → Auto-check).
    # This is the DEFAULT interval that applies to every account which does
    # NOT have its own value in "account_intervals" below.
    "check_interval_min": 0,

    # Per-account auto-check overrides: { "you@gmail.com": 5, "work@…": 1 }.
    # An account listed here uses its own interval (minutes; 0 = off) instead
    # of check_interval_min. Accounts not listed fall back to the default.
    # Set from Tools → Auto-check for new mail… (one row per account).
    "account_intervals": {},

    # Keep a local copy of fetched messages on disk (Helpfiles/Cache), the way
    # Thunderbird does: a message body is downloaded ONCE, then refreshes only
    # pull the UIDs that are actually new and re-sync read/unread flags. This
    # is what makes updating an inbox fast. Turn it off to always re-download.
    "cache_enabled": True,

    # ── Read / unread behaviour ───────────────────────────────────────────────
    # A message stops being "new" (turns read) after you have kept it open for
    # mark_read_seconds. If you later mark it unread by hand, it then takes the
    # longer reread_seconds of dwell to turn read again — so a passing glance
    # does not re-read something you deliberately flagged. 0 = read instantly.
    "mark_read_enabled": True,
    "mark_read_seconds": 1,
    "reread_seconds":    5,
    # Also tell Gmail when a message becomes read: this ADDS the \Seen flag on
    # the server and NEVER removes it, so your phone / Thunderbird / Rambox
    # stop showing it as new — while Freemail's own "mark unread" stays purely
    # local and can never make Gmail ping again. Only acts when Server changes
    # (Tools → Server changes) is turned on.
    "mark_read_on_server": True,

    # ── Message list ──────────────────────────────────────────────────────────
    # thread_view = AUTO-merge by Gmail conversation. DEFAULT OFF (Issu: each
    # Tradera "Frakthandling" must stay its own row). Manual merge groups (the
    # right-click "Merge…" picker) still work regardless of this.
    "thread_view": False,
    # Gmail thread ids the user has explicitly SPLIT APART with the right-click
    # "Separate this conversation" action, so an auto-merged conversation shows
    # one row per message again even while thread_view is on (Issu 2026-08-02).
    "split_threads": [],
    # ── Folders that never AUTO-merge (Issu 2026-08-19) ──────────────────────
    # As "<account>\t<folder-or-path>", the same shape as muted_count_folders.
    # split_threads is per CONVERSATION: you separate one thread, by hand,
    # after it has already merged in front of you. That is the wrong unit of
    # work for a folder whose whole content is look-alikes — every Tradera
    # "📦 Frakthandlingar och kvitto" carries the same subject and the same
    # sender, so Gmail hands them all one conversation id and two shipments
    # booked minutes apart collapse into a single row. You would be splitting
    # a new thread every time you booked postage, for ever.
    #
    # So the rule is set on the FOLDER instead, once: mail listed from here
    # is grouped by its own id, never by Gmail's conversation id, exactly as
    # if thread_view were off — but only here, so ordinary conversations in
    # every other folder keep merging.
    #
    # AUTO-merge only. A merge group you built by hand with the right-click
    # picker is a deliberate act and still holds; this switch only stops the
    # grouping the program does on its own.
    "no_merge_folders": [],
    # Folders you have moved mail to recently, most-recent first. Shown at the
    # TOP of the "Move to folder" picker so your frequent destinations are one
    # click away (Issu 2026-08-02: "jag får inte in några ofta-vägar").
    "recent_move_folders": [],
    # How many times each folder has actually been moved to, as {name: count}.
    # Feeds the "▾ All folders — most used first" dropdown in the picker (Issu
    # 2026-08-22: "en dropdown-lista med alla sparade; sorterade efter mest
    # använd = överst"). Recency alone could not do that job — the folder you
    # use fifty times a week kept being pushed down by a one-off.
    "move_folder_counts": {},
    # ── Favourite move destinations (Issu 2026-08-03) ─────────────────────────
    # FIVE slots across the whole folder structure, shown as buttons at the top
    # of the folder picker:
    #   slots 1–4  PERMANENT — once filled they stay until you take them off
    #              by hand (the ✕ on the chip).
    #   slot 5     ROLLING   — always the destination you used last, replaced
    #              every time.
    # Each entry: {"name": <folder path>, "pinned": bool}. Kept in slot order,
    # so index 4 is always the rolling one.
    "fav_move_folders": [],
    # Folders whose unread NUMBER is muted, as "<account>\t<folder-or-path>".
    # The folder still shows its mail as unread when you open it; it just stops
    # contributing a "(N)" badge to the sidebar and the taskbar total. For a
    # folder that collects filtered mail where a running count is only noise
    # (Issu 2026-08-03).
    "muted_count_folders": [],
    # Folders DELETED from here that Gmail's folder list may still be reporting
    # for a minute or two, as "<account>\t<raw mailbox>". The sidebar leaves
    # them out until the server agrees they are gone, and the entry is then
    # dropped by itself (Issu 2026-08-03).
    "hidden_folders": [],
    # Folder-tree branches you have COLLAPSED in the picker, by path. The picker
    # opens the way you left it, so a mailbox with fifty sub-labels does not
    # have to be scrolled past every time (Issu: "ingen kollaps i katalogerna").
    "picker_collapsed": [],
    # ── Smart Reply (DEL 06b) ─────────────────────────────────────────────────
    # A Smart Reply sends TWO parts — your answers alone, and the full original
    # text with your answers interleaved. answers_top decides which comes first
    # (default: your answers). quote_style is how the sender's OLD text looks in
    # the HTML copy's full part (plain text always uses "> ").
    "smart_reply_answers_top":  True,
    "smart_reply_quote_style":  "grey",   # none|grey|italic|bold|blockquote
    # Which condition SECTION a suggested condition lands in, and where a brand
    # new rule starts (the little "Match:" number in the filter editor):
    #   "1" = the MUST section (every row must match)      ← default
    #   "2" = the either/or section (at least one row)
    #   "3" = all messages
    # It is a remembered DEFAULT for NEW rules — editing a rule never moves it
    # (Issu 2026-08-03: "den siffran ska inte ändras när jag byter…").
    "filter_default_section": "1",
    # Write a full per-rule / per-message explanation of every filter run to
    # Freemail.log and the "Why didn't it match?" window. ON by default while
    # the "my rules do not move anything" hunt is open (Issu 2026-08-03).
    "filter_diagnostics": True,

    # ── Sidebar folder layout (View menu) ─────────────────────────────────────
    # compact_folders: pack the less-used folders (Sent/Drafts, Spam/Trash/…)
    #   into side-by-side COLUMNS instead of one per row, to save space.
    # merge_duplicate_folders: hide Thunderbird duplicate folders (Junk, Skickat,
    #   Utkast, Papperskorg) since the real Gmail folder is already shown.
    "compact_folders":         True,
    "merge_duplicate_folders": True,

    # ── Sending: undo-send + scheduling ───────────────────────────────────────
    # undo_send_on      : hold every outgoing message for a moment so it can be
    #                     cancelled with one click. DEFAULT ON (Issu's request).
    # undo_send_seconds : how long that window is. 10 s default, 600 s (10 min)
    #                     is the maximum offered in the Sending dialog.
    # undo_countdown    : show the remaining seconds ticking in the toast.
    #                     DEFAULT OFF — the toast is quiet unless you want it.
    "undo_send_on":      True,
    "undo_send_seconds": 10,
    "undo_countdown":    False,

    # ── Sending window (DEL 04r) ──────────────────────────────────────────────
    # "Never send before 08:00." Off by default; when on, outgoing mail is
    # held to the next allowed moment and the outbox shows when that is.
    "send_window_on":            False,
    "send_window_from":          "08:00",
    "send_window_to":            "20:00",
    "send_window_weekdays":      False,   # Mon–Fri only
    "send_window_skip_holidays": False,   # skip Swedish public holidays
    # How long a draft is kept AFTER its message was sent successfully, in
    # minutes. Short by design: it is only a safety net against a crash
    # between "SMTP said OK" and "the mail really left".
    "draft_keep_min":    10,

    # ── Notifications ─────────────────────────────────────────────────────────
    "notify_on":        True,    # toast when a background check finds new mail
    "notify_sound":     False,   # also beep (Windows MessageBeep)
    "notify_windows":   True,    # use a native Windows toast (falls back to the
                                 # in-app toast if the OS one is unavailable)
    "notify_flash":     True,    # give the TASKBAR BUTTON a couple of gentle
                                 # flashes on new mail. Off = never flash. It is
                                 # taskbar-only and finite — never the title bar,
                                 # never blinking non-stop (Issu dislikes blinks).

    # ── Search ────────────────────────────────────────────────────────────────
    # "folder" | "all_folders" | "all_accounts" | "all_except"
    #   — remembered between sessions.
    "search_scope":     "folder",

    # ── Search: what to leave out (Issu 2026-08-17) ───────────────────────────
    # The fourth scope, "All except…", is the widest search there is MINUS these
    # two lists. Both are empty to begin with, so the choice searches everything
    # until you actually fill them in (Tools → "Search: what to leave out…").
    #   search_exclude_accounts: ["someone@gmail.com", …]  — the whole account
    #   search_exclude_folders : ["<account>\t<folder>", …] — one folder of one
    #                            account. "*" in place of the account means that
    #                            folder name in EVERY account.
    # Same "<account>\t<folder>" key format as hidden_folders and
    # mini_hidden_folders, so settings.json reads the same way throughout.
    "search_exclude_accounts": [],
    "search_exclude_folders":  [],
    # Does the separate search WINDOW (Ctrl+Shift+F) honour those lists too?
    # On by default and free while the lists are empty.
    "search_window_skip_excluded": True,

    # ── Archiving a conversation out of the inbox (DEL 09h) ───────────────────
    # archive_folder: where "Send & archive" puts the original. Your own name
    # for it — "Minbox", "Klart", whatever. With server changes OFF it is a
    # local hide plus a tag; with them ON it is a real IMAP move.
    "archive_folder":   "Minbox",
    "archive_tag":      "keep",     # tag applied when archiving locally

    # ── Message list (DEL 09e) ────────────────────────────────────────────────
    # show_real_address: put the sender's actual address next to the display
    # name in the list. A forged name (one containing a DIFFERENT address)
    # always shows it regardless — that is a warning, not a preference.
    "show_real_address": False,

    # ── Sidebar: per-account collapse + "mini" folder hiding (DEL 09c) ─────────
    # collapsed_accounts : list of account e-mails whose folder tree is folded
    #                      away in the sidebar. Click an account name to toggle.
    # mini_hidden_folders: PER-ACCOUNT keys ("<account>\t<folder-name-or-path>")
    #                      that DISAPPEAR while that account is collapsed.
    #                      Right-click any folder to add/remove it. Empty by
    #                      default — collapse hides nothing until you pick the
    #                      folders you never look at. Per account, so the same
    #                      folder can be shown for one account and hidden for
    #                      another.
    "collapsed_accounts":  [],
    "mini_hidden_folders": [],

    # ── Folders that read themselves (Issu 2026-08-17) ────────────────────────
    # "Filter som skickar till t.ex. 0---frakt & kvitto — då ska jag kunna ha
    #  den katalogen som auto-read, så mail hämtas, skickas dit… och jag slipper
    #  både 'nytt mail' och 'siffra för antal mail'."
    #
    # Anything that lands in one of these folders is marked READ the moment
    # Freemail sees it, raises no new-mail notification, and adds nothing to any
    # unread badge. Deliberately a property of the FOLDER, not of the rule that
    # filed the mail: any number of rules may aim at the same receipt folder,
    # and mail you move there by hand should behave the same way.
    #
    # Keys are "<account>\t<folder>", compared through _folder_norm, so the raw
    # modified-UTF-7 name a message carries and the decoded path a rule stores
    # both match — the same trap _protected_key exists for.
    #
    # With "Server changes" on, the \Seen flag is also set on Gmail, so the
    # phone stops showing them as new too. That is the least destructive server
    # write there is, and it is only ever ADDED, never removed.
    "auto_read_folders": [],
    # Set the flag on Gmail as well, not just in this program. Only has any
    # effect while allow_server_changes is on.
    "auto_read_on_server": True,

    # ── Sidebar: custom-folder tree expand/collapse (DEL 09c) ─────────────────
    # expanded_folders : keys ("<account>\t<mailbox-path>") of tree nodes that
    #                    are currently OPEN. A node not listed is collapsed, so
    #                    its children are hidden until you click its ▸ twisty.
    # folders_seeded   : accounts whose top level has already been opened once
    #                    automatically (so a first discovery shows the folders
    #                    directly under Inbox, but a later manual collapse is
    #                    respected and never re-opened).
    "expanded_folders": [],
    "folders_seeded":   [],

    # ── Phishing: how hard the brand-impersonation check tries (DEL 04e) ───────
    # "off"        : no brand/domain-in-name check at all.
    # "domain"     : warn only when the NAME contains a domain (e.g. "amazon.se")
    #                that does not match the real sending domain.
    # "balanced"   : the above, PLUS warn when a known brand word (Amazon,
    #                Swedbank, PayPal…) appears in the name but the mail comes
    #                from a free provider (gmail/outlook/…). DEFAULT.
    # "aggressive" : also warn on a brand word whenever the sending domain does
    #                not contain it — more false positives on 3rd-party senders.
    "phish_brand_level": "balanced",

    # ── Notes (DEL 04g) ───────────────────────────────────────────────────────
    # Where local notes are written. Empty = Helpfiles/Notes next to the
    # program. Notes are .eml files and never touch any server.
    "notes_dir":        "",

    # ── Local archive (DEL 04h) ───────────────────────────────────────────────
    # archive_auto: keep an .eml copy of every message the program fetches.
    # Default OFF — it writes to your disk, so that is your call, not the
    # program's. archive_dir empty = Helpfiles/Archive.
    "archive_auto":     False,
    "archive_dir":      "",

    # ── PHASE 2 (DEL 04i) ─────────────────────────────────────────────────────
    # The master switch for the only code that changes anything on Gmail.
    # MUST default to False: a fresh install, or a configuration restored from
    # a backup, must never be able to delete mail on the server.
    "allow_server_changes": False,

    # ── Deleted archive (DEL 04s) ─────────────────────────────────────────────
    # Deleting FROM the Trash removes a message from Gmail for good, but a
    # hidden local copy is kept for this many days so you can still read it,
    # forward it, or try to restore it. 0 = keep forever (never auto-prune).
    "deleted_keep_days": 30,

    # ── Calendar ──────────────────────────────────────────────────────────────
    "cal_view":         "Month",  # "Month" | "Week" | "Agenda"
    "cal_win_w":        1000,
    "cal_win_h":        680,

    # ── Rules panel + hidden parts (DEL 04t) ──────────────────────────────────
    # A small, collapsible panel at the TOP of every opened message that shows
    # which rules are acting on it — split into "for this message" and "for this
    # sender". Default expanded (Issu's request); the twisty state is remembered.
    "rules_panel_expanded": True,
    # Reading-pane toolbar toggles (next to "Show full thread history"), all
    # remembered, all OFF by default so the message itself is what you see:
    #   rp_show_thread  — include the older thread history
    #   rp_show_rules   — show the "rules acting on this mail" panel at the top
    #   rp_show_actions — show the action buttons (Save as PDF, Snooze, …) at top
    "rp_show_thread":  False,
    "rp_show_rules":   False,
    "rp_show_actions": False,
    # always_html_view: when a message has an HTML part, open the formatted
    # (HTML) view automatically instead of making you click "View formatted"
    # every time. Toggled by the checkbox next to that link (Issu 2026-08-01).
    "always_html_view": False,
    # delete_undo_seconds: how long a deleted message sits in "limbo" with an
    # Undo button before the Gmail change actually happens. Issu wanted Delete
    # to act at once with NO Yes/No popup, but to be reversible for a minute.
    # 0 = delete immediately with no undo window (old behaviour).
    "delete_undo_seconds": 60,
    # Auto-remember people you write to, into the address book (Issu 2026-08-01).
    #   reply  → default ON  (people you answer are worth keeping)
    #   sent   → default OFF (a brand-new message might be a one-off)
    "autosave_reply_contacts": True,
    "autosave_sent_contacts":  False,
    # The last message you had open, so the reading pane comes back to it on
    # start-up instead of empty / the top of the list.
    "last_msg_key":    "",

    # ── Connection reuse (DEL 04v) ────────────────────────────────────────────
    # Keep one IMAP connection per account and reuse it, instead of logging in
    # afresh for every fetch / unread-count / quota check. Cuts the "Too many
    # simultaneous connections" stalls and makes folder switches quick. Default
    # ON; turn off only to rule it out if a connection ever misbehaves.
    "imap_reuse":      True,

    # ── Reading ahead (Issu 2026-08-08) ───────────────────────────────────────
    # The folder list arrives headers-first, which is what made switching
    # folders quick — but it also meant the first open of any message had to go
    # and fetch it, and landing on top of the once-a-minute auto-check turned
    # that into a half-minute wait.
    #
    # With this on, the bodies of the newest messages come down QUIETLY in the
    # background right after the list, so clicking one is a local read with
    # nothing to wait for. It runs on its own connection, pauses the instant
    # you click anything, and stops when you change folder.
    #
    # prefetch_count is how many of the newest messages to read ahead. 12
    # covers "the new mail plus a few" without pulling a whole folder down;
    # raise it if you like opening old mail instantly, lower it (or switch it
    # off) on a metered connection.
    "prefetch_bodies": True,
    "prefetch_count":  12,

    # ── Protected folders (Issu 2026-08-08) ───────────────────────────────────
    # "Jag vill bara inte att mail hoppar omkring." Folders listed here (keyed
    # "<account>\t<folder>", the same shape as muted_count_folders) refuse to
    # let anything AUTOMATIC move mail out of them: no filter move, no filter
    # trash, whatever any rule says. Mail can still ARRIVE, and you can still
    # move or delete it yourself — both are deliberate acts. Set it from the
    # folder's right-click menu.
    "protected_folders": [],

    # ── Long recipient lists (Issu 2026-08-08) ────────────────────────────────
    # A circular addressed to fifty people put a screenful of strangers'
    # addresses between him and the message ("det tar mycket plats, innan
    # meddelandet"). Above this many, the To:/Cc: line folds to a one-line
    # summary with a "show all" you can click. 0 = never fold.
    "recipients_max": 5,
    # Senders whose recipient lists are NEVER shown, however short — for the
    # mailing list that does this every single time. Set it by right-clicking
    # the To:/Cc: line of one of their messages.
    "hide_recipients_from": [],

    # ── Keys that were being read without a default listed here ──────────────
    # A static pass on 2026-08-08 found six of these. They all worked, because
    # every read passes a fallback — but an undocumented setting is one nobody
    # can find, and the next person to change a fallback changes the program's
    # behaviour without noticing. Same rule as the rest of this block: if the
    # code reads it, it is declared here with what it means.
    #
    # Smart Reply: how far the sender's quoted lines are pushed right (0/5/10).
    "smart_reply_quote_indent": 0,
    # Month folders: "year_month" (2026-01) · "month" (01) · "year/month".
    "date_folder_style": "year_month",
    # Whether the built-in boilerplate-trim rules have been added once
    # (DEL 04t2). Set on first run; deleting a built-in rule afterwards sticks.
    "trim_seeded": False,
    # Which GENERATION of built-ins has been offered (_TRIM_SEED_VERSION). A
    # new built-in reaches an existing installation exactly once; rules from a
    # generation already seen are never re-added, so deletions stick.
    "trim_seed_version": 0,
    # Never let a hide rule fold a line that carries a link, unless the rule's
    # own patterns are about links (Issu 2026-08-17). Display safety net: a
    # boilerplate rule may hide the words around an address, never the address.
    "trim_keep_links": True,
    # Show a run of blank lines as ONE blank line (DEL 04t2). Display only —
    # the message itself keeps them all. On by default: the gaps come from
    # HTML table layout and are never meaningful.
    "collapse_blank_lines": True,
    # The search WINDOW's remembered choices (DEL 06f).
    "search_fields":        ["subject", "from", "body"],
    "search_all_accounts":  True,
    "search_include_trash": True,
    # Play a sound with a calendar/follow-up reminder.
    "reminder_sound": True,

    # ── "Open attachment with…" remembered programs (DEL 04u) ─────────────────
    # Left-click an attachment = open in the OS default (or the built-in image
    # popup). Right-click = a menu that can Save it, Save all, or open it with a
    # program YOU pick — e.g. a PNG in your QR-code-text tool. The programs you
    # choose are remembered here, per file extension, so they come back as
    # one-click choices next time.  {".png": [{"name": "QR-code-text",
    #                                          "path": "C:\\...\\QR-code-text.py"}]}
    "open_with_apps": {},
    # Last folder used for "Save attachment(s)…", so it reopens where you were.
    "attach_save_dir": "",

    # ── Reply layout: zoom, splitter, favourite (Issu 2026-09-20) ────────────
    # "<key>_layout_zoom" is the point size of the ORIGINAL text (their words),
    # "<key>_layout_sash" is where the splitter between their text and your
    # answer sits (pixels; 0 = leave it wherever Tk puts it), and
    # "<key>_layout_fav" is one whole layout {zoom, sash, w, h} pinned by hand.
    # <key> is "compose" for Reply and "smart_reply" for Smart Reply — the same
    # two names the remembered window POSITION already uses, so one window's
    # settings can never be read into the other's. The shipped values live in
    # _REPLY_LAYOUT_DEFAULTS, just below this dict, and the ↺ Default button
    # reads them from there rather than from here.
    # "..._zoom" sizes THEIR text, "..._zoom_answer" sizes YOURS.
    "compose_layout_zoom":            9,
    "compose_layout_zoom_answer":     10,
    "compose_layout_sash":            430,
    "compose_layout_fav":             {},
    "smart_reply_layout_zoom":        10,
    "smart_reply_layout_zoom_answer": 10,
    "smart_reply_layout_sash":        0,
    "smart_reply_layout_fav":         {},

    # ── Long recipient lists in the FIELD you are writing into ───────────────
    # (Issu 2026-09-20; recipients_max above is the same idea for the reading
    # pane.) Reply All on a circular hands you thirty chips that wrap onto row
    # after row and push the message itself off the screen. Above this many the
    # To:/Cc:/Bcc: field shows one row and a "+N more" pill. 0 = never fold.
    "compose_recipients_max": 3,

    # ── Backup ────────────────────────────────────────────────────────────────
    "backup_on_exit":   False,   # write a .zip of all settings when closing
    "backup_keep":      10,      # how many automatic backups to keep
    "backup_dir":       "",      # empty → Helpfiles/Backups
}

# ── What ↺ Default puts back (Issu 2026-09-20) ────────────────────────────────
# The layout each reply window SHIPS with, as opposed to the layout it last had
# (remembered per window) or the one you pinned (the favourite). Kept here, in
# one place, rather than as fallbacks scattered through the two windows: the
# button is only honest if "default" means the same thing everywhere.
#   zoom — point size of the sender's text
#   sash — splitter position in pixels (x for Reply's left|right split,
#          y for Smart Reply's top/bottom one; 0 = leave it to Tk)
#   w/h  — the window size that goes with it
_REPLY_LAYOUT_DEFAULTS = {
    # 1180x620, not 680x560 (Issu 2026-09-20). Two numbers drove this up:
    # the answer cluster alone needs 790 px, so at 680 the last two buttons
    # were cut clean off the right-hand edge; and putting the original's half
    # on the SAME row — "spara en rads höjd" — needs both halves side by side,
    # about 1150. The strip reflows onto two rows below that rather than
    # cutting anything, so a narrower window still works; this is just the
    # width at which it looks the way he asked for. ↺ Default is how a window
    # still remembering the old narrow size gets here.
    "compose":     {"zoom":  9, "zoom_answer": 10, "sash": 430,
                    "w": 1180, "h": 620},
    "smart_reply": {"zoom": 10, "zoom_answer": 10, "sash": 0,
                    "w": 720, "h": 720},
}

# ── Folder lists that tidy themselves (Issu 2026-08-17) ───────────────────────
#
# Lists whose entries are "<account>\t<folder>". Two kinds of rubbish collect in
# them over months of use, neither of which does any harm and both of which make
# the file impossible to read:
#
#   • THE SAME FOLDER TWICE, once per spelling. A rule stores the decoded path
#     ("INBOX/Temporär/0---Frakt & Kvitto/2026-08") while a message carries the
#     raw modified-UTF-7 name ("INBOX/Tempor&AOQ-r/0---Frakt &- Kvitto/2026-08").
#     _folder_norm makes both answer alike, so the duplicate has always WORKED —
#     it is just noise, and it grows every time a folder is protected from a
#     different starting point. His protected_folders held three months twice.
#
#   • ENTRIES WITH NO ACCOUNT, left over from before these lists were made
#     per-account. Every reader compares a composite "<email>\t<folder>" key, so
#     a bare "Snoozed" can never match anything at all. His mini_hidden_folders
#     held six.
#
# Cleaning up is safe offline: nothing here needs to know which folders still
# exist on the server, because an entry is only dropped when an EQUIVALENT one
# stays behind, or when it could never have matched in the first place. What was
# removed goes in the log, so it is always recoverable.
_PER_ACCOUNT_FOLDER_KEYS = ("protected_folders", "muted_count_folders",
                            "mini_hidden_folders", "hidden_folders",
                            "expanded_folders", "auto_read_folders",
                            "search_exclude_folders", "no_merge_folders")

# Lists that are plain folder names, global to every account BY DESIGN — the
# move picker's recents and its collapsed rows. They are deduped, never split.
_GLOBAL_FOLDER_KEYS = ("recent_move_folders", "picker_collapsed")


def _tidy_folder_settings(cfg: dict) -> list:
    """Collapse duplicate spellings and drop entries that can never match.
    Returns a list of plain-English notes about what changed (empty = nothing
    to do, which is the normal case)."""
    notes = []
    for key in _PER_ACCOUNT_FOLDER_KEYS:
        raw = cfg.get(key)
        if not isinstance(raw, list) or not raw:
            continue
        kept, seen, dropped, orphaned = [], {}, 0, 0
        for entry in raw:
            if not isinstance(entry, str):
                kept.append(entry)
                continue
            if "\t" not in entry:
                orphaned += 1          # no account — unreachable by every reader
                continue
            acct, folder = entry.split("\t", 1)
            ident = (acct.strip().lower(), _folder_norm(folder))
            first = seen.get(ident)
            if first is None:
                seen[ident] = len(kept)
                kept.append(entry)
                continue
            dropped += 1
            # Keep the RAW modified-UTF-7 spelling when there is a choice: it is
            # what a message carries and what SELECT wants, so it is the one
            # that reads back correctly if these lists are ever compared by
            # hand. Raw names are ASCII by construction.
            if folder.isascii() and not kept[first].split("\t", 1)[1].isascii():
                kept[first] = entry
        if dropped or orphaned:
            # Sorted for a stable, readable file — but only when every entry is
            # a string. A hand-edited file could hold anything, and sorting
            # mixed types raises (caught by the test, not by Issu).
            cfg[key] = (sorted(kept) if all(isinstance(k, str) for k in kept)
                        else kept)
            bits = []
            if dropped:
                bits.append(f"{dropped} duplicate spelling(s)")
            if orphaned:
                bits.append(f"{orphaned} entr{'ies' if orphaned != 1 else 'y'} "
                            f"with no account")
            notes.append(f"{key}: removed " + " and ".join(bits))

    for key in _GLOBAL_FOLDER_KEYS:
        raw = cfg.get(key)
        if not isinstance(raw, list) or not raw:
            continue
        kept, seen, dropped = [], set(), 0
        for entry in raw:
            if not isinstance(entry, str):
                kept.append(entry)
                continue
            ident = _folder_norm(entry)
            if ident in seen:
                dropped += 1           # "Inbox" and "INBOX" are one folder
                continue
            seen.add(ident)
            kept.append(entry)         # order matters here — recents are recent
        if dropped:
            cfg[key] = kept
            notes.append(f"{key}: removed {dropped} duplicate(s)")
    return notes


def _load_settings() -> dict:
    try:
        if os.path.isfile(_SETTINGS_F):
            with open(_SETTINGS_F, "r", encoding="utf-8") as f:
                data = json.load(f)
            merged = _DEFAULT_SETTINGS.copy()
            merged.update(data)
            try:
                for note in _tidy_folder_settings(merged):
                    log.info("Tidied settings — %s", note)
            except Exception as e:
                log.warning("Settings tidy-up skipped: %s", e)
            return merged
    except Exception as e:
        log.warning("Could not load settings: %s", e)
    return _DEFAULT_SETTINGS.copy()

def _save_settings(cfg: dict):
    try:
        os.makedirs(os.path.dirname(_SETTINGS_F), exist_ok=True)
        with open(_SETTINGS_F, "w", encoding="utf-8") as f:
            json.dump(cfg, f, indent=2)
    except Exception as e:
        log.warning("Could not save settings: %s", e)


# ******************************************************************************
# DEL 02 — ICON LOADER (external Icons/<program>.ico)
# ******************************************************************************

def _icon_path() -> str:
    """Path to the app icon. Prefers Icons/<script-name>.ico — i.e. the CLAUDE
    convention "same name as the .py", which for this program is the literal
    'F(re)email.ico' — and falls back to the older 'Freemail.ico'. Returns the
    first that EXISTS, or the primary path (for logging) if neither does."""
    prog = os.path.splitext(os.path.basename(__file__))[0]   # "F(re)email"
    candidates = [
        os.path.join(_BASE_DIR, "Icons", f"{prog}.ico"),
        os.path.join(_BASE_DIR, "Icons", "Freemail.ico"),
    ]
    for c in candidates:
        if os.path.isfile(c):
            return c
    return candidates[0]


def _set_window_icon(root: tk.Tk) -> None:
    if platform.system() != "Windows":
        # On Linux/Mac just try iconbitmap
        ico = _icon_path()
        try:
            root.iconbitmap(ico)
        except Exception:
            pass
        return

    ico = _icon_path()
    if not os.path.isfile(ico):
        log.warning("Icon file not found: %s", ico)
        return

    # Channel 1: tkinter
    try:
        root.iconbitmap(ico)
    except Exception as e:
        log.debug("iconbitmap failed: %s", e)

    # Channel 2: Win32 WM_SETICON
    try:
        user32          = ctypes.windll.user32
        LR_LOADFROMFILE = 0x0010
        LR_DEFAULTSIZE  = 0x0040
        IMAGE_ICON      = 1
        WM_SETICON      = 0x0080
        hwnd = user32.FindWindowW(None, root.title())
        if hwnd:
            hbig = user32.LoadImageW(None, ico, IMAGE_ICON, 0,  0,  LR_LOADFROMFILE | LR_DEFAULTSIZE)
            hsml = user32.LoadImageW(None, ico, 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 as e:
        log.debug("Win32 WM_SETICON failed: %s", e)


# ******************************************************************************
# DEL 03 — HELPER: no-blink cursor + scrollable frame
# ******************************************************************************

def no_blink(widget):
    """Force a static (non-blinking) cursor on any Entry or Text widget."""
    try:
        widget.configure(insertofftime=0, insertontime=9999999)
    except Exception:
        pass

def add_tooltip(widget, text, delay=1500):
    """Attach a hover help-bubble to any widget (Issu 2026-08-01).

    The bubble appears after `delay` ms of hovering (1.5 s by default, as
    asked) and disappears on leave or click. It is a borderless Toplevel, so it
    never steals focus and never blinks — a plain static label. Cheap: one
    after-timer per widget, created only while the pointer sits still on it.

    `text` may be a CALLABLE, read at hover time. That matters because the
    bindings below use add="+" and therefore STACK: calling add_tooltip twice
    on one widget gives it two bubbles, the stale one included. Anything whose
    help text changes while the window is open (the snippet buttons) must pass
    a callable and be attached exactly once."""
    state = {"after": None, "tip": None}

    def _show():
        state["after"] = None
        if state["tip"] is not None:
            return
        try:
            x = widget.winfo_rootx() + 12
            y = widget.winfo_rooty() + widget.winfo_height() + 4
            tip = tk.Toplevel(widget)
            tip.wm_overrideredirect(True)
            tip.configure(bg="#11131d")
            tip.attributes("-topmost", True)
            try:
                shown = text() if callable(text) else text
            except Exception:
                shown = ""
            tk.Label(tip, text=shown, bg="#11131d", fg="#e8ecff",
                     font=("Segoe UI", 8), justify="left",
                     wraplength=320, padx=8, pady=5,
                     relief="solid", bd=1).pack()
            tip.wm_geometry(f"+{x}+{y}")
            state["tip"] = tip
        except Exception:
            state["tip"] = None

    def _hide(_e=None):
        if state["after"] is not None:
            try:
                widget.after_cancel(state["after"])
            except Exception:
                pass
            state["after"] = None
        if state["tip"] is not None:
            try:
                state["tip"].destroy()
            except Exception:
                pass
            state["tip"] = None

    def _enter(_e=None):
        _hide()
        state["after"] = widget.after(delay, _show)

    widget.bind("<Enter>", _enter, add="+")
    widget.bind("<Leave>", _hide, add="+")
    widget.bind("<Button-1>", _hide, add="+")
    widget.bind("<Destroy>", _hide, add="+")
    return widget


def _center_over(top, parent, width, height):
    """Position a Toplevel window centred over its parent window.

    Tkinter's .geometry("WxH") only sets size, never position, so by
    default every new window (Reply, Smart Reply, Help, ...) lands in
    the screen's top-left corner. This computes a centred x/y from the
    parent's current position+size and applies it together with the
    requested width/height in one geometry() call, then clamps so the
    window can't end up partly off-screen if the parent is near an edge.
    """
    try:
        parent.update_idletasks()
        px, py = parent.winfo_x(), parent.winfo_y()
        pw, ph = parent.winfo_width(), parent.winfo_height()
        sw, sh = top.winfo_screenwidth(), top.winfo_screenheight()
        x = px + (pw - width)  // 2
        y = py + (ph - height) // 2
        x = max(0, min(x, sw - width))
        y = max(0, min(y, sh - height))
        top.geometry(f"{width}x{height}+{x}+{y}")
    except Exception:
        top.geometry(f"{width}x{height}")

def _force_english_dialogs(root):
    """Make Tk's own message boxes say Yes / No / Cancel, not Ja / Nej /
    Avbryt (Issu 2026-08-03).

    The buttons in messagebox.askyesnocancel are drawn by Tk itself, not by
    this program, and Tk translates them through msgcat using the SYSTEM
    language — which on a Swedish Windows is Swedish, in an application whose
    house rule is "English only, never Swedish". Setting the message-catalogue
    locale to "en" makes every lookup fall through to the untranslated source
    string, i.e. English, for every Tk dialog at once.

    Tk 8.7 moved its catalogue into its own ::tk::msgcat namespace, so both are
    set; each is wrapped on its own because the missing one raises."""
    for cmd in ("::msgcat::mclocale en",
                "::tk::msgcat::mclocale en"):
        try:
            root.tk.eval(cmd)
        except Exception:
            pass
    # Belt and braces: overwrite the four button texts in whatever catalogue
    # IS active, so a Tk build that ignores the locale change still shows
    # English words.
    for src in ("Yes", "No", "Cancel", "OK", "Retry", "Abort", "Ignore"):
        for ns in ("::msgcat::mcset", "::tk::msgcat::mcset"):
            try:
                root.tk.eval(f'{ns} [{ns.rsplit("::", 1)[0]}::mclocale] '
                             f'"{src}" "{src}"')
            except Exception:
                pass


def _ask_line(parent, title, prompt, initial="", ok="OK"):
    """Ask for one line of text. Returns the string, or None if cancelled.

    Our own, rather than Tk's simpledialog: that one draws its buttons from the
    SYSTEM language (so an English-only program asked in Swedish) and gives a
    blinking cursor. ENTER confirms and ESC cancels, as everywhere here."""
    result = {"v": None}
    top = tk.Toplevel(parent)
    top.title(title)
    top.configure(bg=C_BG3)
    top.resizable(False, False)
    _center_over(top, parent, 460, 190)
    top.transient(parent)
    top.grab_set()
    top.focus_force()
    top.bind("<Escape>", lambda e: top.destroy())

    tk.Label(top, text=title, bg=C_BG3, fg=C_ACCENT,
             font=("Segoe UI", 12, "bold")).pack(pady=(16, 2))
    tk.Label(top, text=prompt, bg=C_BG3, fg=C_FG, font=("Segoe UI", 9),
             wraplength=410, justify="left").pack(padx=20)

    e = tk.Entry(top, bg=C_BG2, fg=C_FG, relief="flat", font=("Segoe UI", 11),
                 insertbackground=C_ACCENT,
                 insertofftime=0, insertontime=9999999)
    no_blink(e)
    e.pack(fill="x", padx=20, pady=12, ipady=4)
    e.insert(0, initial)
    e.select_range(0, "end")

    def _ok(event=None):
        result["v"] = e.get().strip()
        top.destroy()

    e.bind("<Return>", _ok)
    btns = tk.Frame(top, bg=C_BG3)
    btns.pack(pady=(0, 14))
    tk.Button(btns, text=ok, bg=C_BTN_NEW, fg=C_BTN_FG,
              font=("Segoe UI", 9, "bold"), relief="flat", cursor="hand2",
              padx=16, pady=4, command=_ok).pack(side="left", padx=4)
    tk.Button(btns, text="Cancel", bg=C_BTN_STD, fg=C_BTN_FG,
              font=("Segoe UI", 9), relief="flat", cursor="hand2",
              padx=16, pady=4, command=top.destroy).pack(side="left", padx=4)
    e.focus_set()
    parent.wait_window(top)
    return result["v"] or None


def ask_yes_no_cancel(parent, title, message, yes="Yes", no="No",
                      cancel="Cancel", icon="❓"):
    """A three-way question in THIS program's own colours and words.

    Returns True (yes), False (no) or None (cancel/Escape/closed). Used where
    the answer matters enough that "Ja/Nej/Avbryt" in the middle of an English
    program would be a real stumble — keeping a half-written message, for one.
    House rules: grab_set(), focus_force(), Escape bind, in that order."""
    result = {"v": None}
    top = tk.Toplevel(parent)
    top.title(title)
    top.configure(bg=C_BG3)
    top.resizable(False, False)
    _center_over(top, parent, 460, 260)
    top.transient(parent)
    top.grab_set()
    top.focus_force()
    top.bind("<Escape>", lambda e: top.destroy())

    tk.Label(top, text=f"{icon}  {title}", bg=C_BG1, fg=C_ACCENT,
             font=("Segoe UI", 12, "bold"), pady=8).pack(fill="x")
    tk.Label(top, text=message, bg=C_BG3, fg=C_FG, font=("Segoe UI", 10),
             wraplength=420, justify="left").pack(fill="both", expand=True,
                                                  padx=18, pady=14)

    def _set(v):
        result["v"] = v
        top.destroy()

    br = tk.Frame(top, bg=C_BG3)
    br.pack(pady=(0, 14))
    for text, colour, val in ((yes, C_BTN_NEW, True),
                              (no, C_BTN_DEL, False),
                              (cancel, C_BTN_STD, None)):
        tk.Button(br, text=text, bg=colour, fg=C_BTN_FG,
                  font=("Segoe UI", 9, "bold"), relief="flat", cursor="hand2",
                  padx=16, pady=5,
                  command=lambda v=val: _set(v)).pack(side="left", padx=6)
    top.bind("<Return>", lambda e: _set(True))
    parent.wait_window(top)
    return result["v"]


# ── Bottom-right toast stack (Issu 2026-08-03) ────────────────────────────────
#
# Send-undo, delete-undo, new-mail notifications, calendar reminders and
# follow-up reminders all lived in the same corner of the screen at the same
# coordinates, so two of them at once meant one hiding the other completely
# ("men inte på samma plats som Delete, så att de krockar"). Each class used to
# stack only against OTHERS OF ITS OWN KIND, which is why a Send toast and a
# Delete toast still landed on top of each other.
#
# One registry for all of them: a new toast is placed above whatever is already
# standing, whatever kind it is.
_CORNER_TOASTS = []


def _corner_forget(win):
    try:
        _CORNER_TOASTS.remove(win)
    except ValueError:
        pass


def _corner_stack(win, width, height, margin=18):
    """Place a toast in the bottom-right corner, ABOVE any toast already
    there. Call _corner_forget(win) when it closes."""
    global _CORNER_TOASTS
    live = []
    for w in _CORNER_TOASTS:
        try:
            if w.winfo_exists():
                live.append(w)
        except Exception:
            pass
    _CORNER_TOASTS = live
    offset = sum(getattr(w, "_toast_height", 60) + 8 for w in live)
    try:
        sw = win.winfo_screenwidth()
        sh = win.winfo_screenheight()
        y = sh - height - margin - 40 - offset
        y = max(0, y)
        win.geometry(f"{width}x{height}+{sw - width - margin}+{y}")
    except Exception:
        win.geometry(f"{width}x{height}")
    win._toast_height = height
    _CORNER_TOASTS.append(win)
    return win


def _bind_mousewheel(widget, canvas):
    """Bind mouse-wheel scroll to a canvas.

    If canvas is None, the widget itself is scrolled instead (e.g. a
    Text widget that can scroll on its own, like the reading pane body).

    Why this approach: a per-widget <MouseWheel> bind only fires on the
    exact widget under the cursor and does NOT bubble up to a parent in
    Tkinter, so binding only the outer frame leaves it dead under any
    child label/row. Binding recursively to every child (an earlier
    version of this function) breaks again whenever children get
    destroyed and rebuilt, which several panels here do.

    A second attempt used <Enter>/<Leave> on the canvas to toggle a
    global bind_all on/off. That is ALSO unreliable: on X11/Windows,
    moving the mouse from the bare canvas onto a child widget stacked on
    top of it (e.g. a row's Frame/Label, which is a separate window as
    far as the windowing system is concerned) fires a <Leave> for the
    canvas and an <Enter> for the child — so the global bind kept
    flicking on and off depending on exactly which pixel the cursor was
    over. That's the "works sometimes, can't tell when" behaviour.

    The actually-reliable fix: bind <MouseWheel> globally ONCE (on the
    toplevel window, shared across every scrollable area) and, on each
    wheel event, ask Tkinter what widget is physically under the cursor
    right now (winfo_containing). Walk up from there through its parent
    chain — if this scroll area's frame/canvas is an ancestor, scroll it;
    otherwise ignore the event. This needs no per-widget binds at all, so
    it's completely unaffected by widgets being destroyed, recreated, or
    not yet existing.
    """
    target = canvas if canvas is not None else widget
    # The widget whose bounding box defines "is the mouse over this
    # scroll area" — the canvas when there is one (it always covers the
    # full visible area, even when its inner frame is shorter than it),
    # otherwise the widget itself.
    area = canvas if canvas is not None else widget

    # Use the real Tk() root (not winfo_toplevel()) so every scroll area
    # in the whole app — including ones inside Toplevel dialogs like the
    # Help window — shares exactly ONE global dispatcher and registry,
    # instead of each Toplevel accidentally creating its own (bind_all
    # is application-wide regardless of which window .bind_all() was
    # called on, so duplicate dispatchers would otherwise both fire on
    # every wheel event for no reason).
    app_root = widget.nametowidget(".")
    registry = getattr(app_root, "_wheel_scroll_areas", None)
    if registry is None:
        registry = []
        app_root._wheel_scroll_areas = registry

        def _dispatch_wheel(event):
            try:
                under = app_root.winfo_containing(event.x_root, event.y_root)
            except Exception:
                under = None
            if under is None:
                return
            # Drop entries whose scroll-area widget no longer exists
            # (panel was torn down and rebuilt) so the registry doesn't
            # grow stale references forever.
            registry[:] = [(a, t) for (a, t) in registry
                           if a.winfo_exists()]
            # Find the most specific (innermost) registered scroll area
            # that contains the widget under the cursor, by walking up
            # from `under` through its ancestors. The first registered
            # area we hit is the right one, since nested scroll areas
            # (none currently overlap in this app, but stay safe) would
            # otherwise both match.
            w = under
            while w is not None:
                for area_w, target_w in registry:
                    if w is area_w:
                        if platform.system() == "Windows":
                            target_w.yview_scroll(
                                int(-1 * (event.delta / 120)), "units")
                        elif platform.system() == "Darwin":
                            target_w.yview_scroll(
                                int(-1 * event.delta), "units")
                        else:
                            if getattr(event, "num", None) == 4:
                                target_w.yview_scroll(-1, "units")
                            elif getattr(event, "num", None) == 5:
                                target_w.yview_scroll(1, "units")
                        return
                w = w.master

        app_root.bind_all("<MouseWheel>", _dispatch_wheel)
        app_root.bind_all("<Button-4>",   _dispatch_wheel)
        app_root.bind_all("<Button-5>",   _dispatch_wheel)

    registry.append((area, target))


# ******************************************************************************
# DEL 04 — COLOUR THEME (change hex values here to restyle the whole app)
# ******************************************************************************

# Background layers
C_BG1      = "#1b1d2a"   # darkest  — outermost chrome
C_BG2      = "#22253a"   # main panels
C_BG3      = "#2a2d42"   # raised panels / dialogs
C_BG4      = "#33374f"   # hover / selection
C_SEP      = "#3e4260"   # separator lines

# Text
C_FG       = "#d8ddf0"   # normal text
C_FG_DIM   = "#7a80a0"   # muted / secondary text
C_FG_UNRD  = "#eef2ff"   # unread message text (brighter)

# Accent (blue — F(re)email brand colour)
C_ACCENT   = "#52b7ff"   # links, highlights, selected sidebar
C_ACCENT2  = "#3d8fcc"   # darker accent for button borders

# Buttons (named so they're easy to spot and change)
C_BTN_NEW   = "#1e6fa8"  # "New Message" button  — change to e.g. "#1a7a45" for green
C_BTN_STD   = "#2e3350"  # standard toolbar buttons  — change to e.g. "#4a2060" for purple
C_BTN_DEL   = "#7a2020"  # delete button  — change to e.g. "#c0392b" for bright red
C_BTN_LATER = "#4a3a70"  # "Send later" button  — change to e.g. "#2e6b4f" for green
C_BTN_KEEP  = "#2e6b4f"  # "Send and save" button  — change to e.g. "#7a5a12" for amber
C_BTN_UNDO  = "#8a5a12"  # "Cancel" in the undo-send toast  — e.g. "#a02020" for red
C_BTN_FG    = "#d8ddf0"  # button text colour

# ── FIVE TOOLBAR COLOURS THAT MEAN SOMETHING (Issu 2026-08-22) ────────────────
# The toolbar was one blue button in a row of identical grey ones, so the two
# things reached for constantly — Refresh and Reply — took as long to find as
# anything else. Each of the five now owns a colour, and no two of them are in
# the same part of the wheel:
#     blue   New Message      green  ↻ Refresh
#     orange ↩ Reply          red    🗑 Delete
#     teal   📌 Notes  (was green, which Refresh has taken over)
C_BTN_REFRESH = "#1a7a45"  # "↻ Refresh"  — the one you press most
C_BTN_REPLY   = "#b5601a"  # "↩ Reply"    — orange, as asked for
C_BTN_NOTE    = "#1f6f7a"  # Notes / "Save note" (local only) — the fifth colour
C_BTN_DO      = "#a02020"  # "⚡ Do it now" beside an Undo button — see DEL 09j

# Warning / alert colours (phishing banner, undo toast, notifications)
C_WARN_BG   = "#6b1f1f"  # phishing banner background  — e.g. "#8a2b2b" for lighter
C_WARN_FG   = "#ffd9d9"  # phishing banner text
C_TOAST_BG  = "#2a2d42"  # notification / undo toast background
C_TOAST_ACC = "#52b7ff"  # notification accent bar

# Message list
C_MSG_SEL   = "#1e3d6e"  # selected message row
C_MSG_UNRD  = "#252849"  # unread message row tint
C_MSG_READ  = C_BG2      # read message row
C_ADDR      = "#3ecf7a"  # ✉ address-mail envelope — THIS message holds an address
#                          (a thread that has one only DEEPER down draws it grey,
#                           in C_FG_DIM — the same grammar the 📎 paperclip uses)

# Folder sidebar
C_FOLD_SEL  = "#1e3a6e"  # selected folder


# ******************************************************************************
# DEL 04b — CREDENTIAL STORE  (Windows DPAPI-encrypted app passwords)
# ******************************************************************************
#
# Gmail "app passwords" are stored ENCRYPTED with the Windows Data Protection
# API (DPAPI), tied to the current Windows user account — the file cannot be
# decrypted by another Windows user or copied to another machine and read.
# On non-Windows we fall back to a clearly-marked obfuscated form (base64),
# which is NOT real security — it just avoids casual shoulder-surfing.

import base64
import threading
import tempfile
import time

_ACCOUNTS_DIR = os.path.join(_FM_DIR, "Accounts")
_ACCOUNTS_F   = os.path.join(_ACCOUNTS_DIR, "accounts.json")


def _dpapi_available() -> bool:
    return platform.system() == "Windows"


def _dpapi(data: bytes, encrypt: bool) -> bytes:
    """Encrypt (encrypt=True) or decrypt (encrypt=False) via Windows DPAPI."""
    from ctypes import wintypes

    class DATA_BLOB(ctypes.Structure):
        _fields_ = [("cbData", wintypes.DWORD),
                    ("pbData", ctypes.POINTER(ctypes.c_char))]

    buf      = ctypes.create_string_buffer(data, len(data))
    blob_in  = DATA_BLOB(len(data),
                         ctypes.cast(buf, ctypes.POINTER(ctypes.c_char)))
    blob_out = DATA_BLOB()
    fn = (ctypes.windll.crypt32.CryptProtectData if encrypt
          else ctypes.windll.crypt32.CryptUnprotectData)
    if not fn(ctypes.byref(blob_in), None, None, None, None, 0,
              ctypes.byref(blob_out)):
        raise OSError("DPAPI operation failed")
    try:
        out = ctypes.string_at(blob_out.pbData, blob_out.cbData)
    finally:
        ctypes.windll.kernel32.LocalFree(blob_out.pbData)
    return out


def _encrypt_secret(secret: str) -> str:
    raw = secret.encode("utf-8")
    if _dpapi_available():
        try:
            return "dpapi:" + base64.b64encode(_dpapi(raw, True)).decode("ascii")
        except Exception as e:
            log.warning("DPAPI encrypt failed, storing obfuscated: %s", e)
    return "plain:" + base64.b64encode(raw).decode("ascii")


_DECRYPT_FAIL_LOGGED = set()


def _decrypt_secret(token: str) -> str:
    try:
        scheme, _, b64 = (token or "").partition(":")
        raw = base64.b64decode(b64.encode("ascii"))
        if scheme == "dpapi":
            return _dpapi(raw, False).decode("utf-8")
        return raw.decode("utf-8")
    except Exception as e:
        # Once per stored secret: every poll of every account used to repeat
        # this line every 15 s after Windows was reinstalled (2026-10-19).
        if token not in _DECRYPT_FAIL_LOGGED:
            _DECRYPT_FAIL_LOGGED.add(token)
            log.error("Could not decrypt stored secret: %s", e)
        return ""


def _load_account_store() -> dict:
    try:
        if os.path.isfile(_ACCOUNTS_F):
            with open(_ACCOUNTS_F, "r", encoding="utf-8") as f:
                data = json.load(f)
            data.setdefault("accounts", [])
            data.setdefault("default_sender", "")
            return data
    except Exception as e:
        log.warning("Could not load accounts: %s", e)
    return {"accounts": [], "default_sender": ""}


def _save_account_store(store: dict):
    try:
        os.makedirs(_ACCOUNTS_DIR, exist_ok=True)
        with open(_ACCOUNTS_F, "w", encoding="utf-8") as f:
            json.dump(store, f, indent=2)
    except Exception as e:
        log.warning("Could not save accounts: %s", e)


# ── Attachment auto-save rules ────────────────────────────────────────────────
_AUTOSAVE_F = os.path.join(_ACCOUNTS_DIR, "autosave_rules.json")

def _load_autosave_rules() -> dict:
    try:
        if os.path.isfile(_AUTOSAVE_F):
            with open(_AUTOSAVE_F, "r", encoding="utf-8") as f:
                data = json.load(f)
            data.setdefault("default_dir", "")
            data.setdefault("rules", [])
            return data
    except Exception as e:
        log.warning("Could not load autosave rules: %s", e)
    return {"default_dir": "", "rules": []}

def _save_autosave_rules(store: dict):
    try:
        os.makedirs(_ACCOUNTS_DIR, exist_ok=True)
        with open(_AUTOSAVE_F, "w", encoding="utf-8") as f:
            json.dump(store, f, indent=2)
    except Exception as e:
        log.warning("Could not save autosave rules: %s", e)


# ── Contact colours (a lightweight colour-coded address book) ─────────────────
# Each entry: {"match": <email or substring>, "color": "#rrggbb", "label": <group>}
# Several contacts may share one colour — that's how informal groups work.
_CONTACTS_F = os.path.join(_ACCOUNTS_DIR, "contacts.json")

# A palette of 10 clearly-distinct colours offered in the editor.
CONTACT_PALETTE = [
    "#ff6b6b", "#ffa94d", "#ffd43b", "#69db7c", "#38d9a9",
    "#4dabf7", "#748ffc", "#b197fc", "#f783ac", "#e599f7",
]

# ── Per-account colours (DEL 09c) ─────────────────────────────────────────────
# Each account gets its own colour, so at a glance you can tell which account a
# message belongs to — especially in the "All Accounts" view, and in the
# sidebar where every account's folders wear its colour. Auto-assigned from
# this palette in order; can be overridden per account (Accounts → Account
# colours…). Kept visually distinct from CONTACT_PALETTE on purpose.
ACCOUNT_PALETTE = [
    "#4dabf7", "#69db7c", "#ffa94d", "#f783ac", "#b197fc",
    "#38d9a9", "#ffd43b", "#ff8787", "#63e6be", "#da77f2",
]

def _load_contacts() -> dict:
    try:
        if os.path.isfile(_CONTACTS_F):
            with open(_CONTACTS_F, "r", encoding="utf-8") as f:
                data = json.load(f)
            data.setdefault("contacts", [])
            return data
    except Exception as e:
        log.warning("Could not load contacts: %s", e)
    return {"contacts": []}

def _save_contacts(store: dict):
    try:
        os.makedirs(_ACCOUNTS_DIR, exist_ok=True)
        with open(_CONTACTS_F, "w", encoding="utf-8") as f:
            json.dump(store, f, indent=2)
    except Exception as e:
        log.warning("Could not save contacts: %s", e)


# ── Address book (named contacts + To: autocomplete) ──────────────────────────
# Each person: {"name": <display name>, "email": <address>, "group": <optional>}
_ADDRBOOK_F = os.path.join(_ACCOUNTS_DIR, "addressbook.json")

def _load_addressbook() -> dict:
    try:
        if os.path.isfile(_ADDRBOOK_F):
            with open(_ADDRBOOK_F, "r", encoding="utf-8") as f:
                data = json.load(f)
            data.setdefault("people", [])
            data.setdefault("never_save", [])
            return data
    except Exception as e:
        log.warning("Could not load address book: %s", e)
    return {"people": [], "never_save": []}

def _save_addressbook(store: dict):
    try:
        os.makedirs(_ACCOUNTS_DIR, exist_ok=True)
        with open(_ADDRBOOK_F, "w", encoding="utf-8") as f:
            json.dump(store, f, indent=2)
    except Exception as e:
        log.warning("Could not save address book: %s", e)


# ── Never-save rules (addresses that must never enter the book) ───────────────
# Issu 2026-08-25: "Det vore bra om jag kunde lägga till vissa prefix / suffix /
# domäner / adresser, som aldrig ska sparas i contacts."
#
# The auto-save of everyone you reply to is convenient right up until the book
# fills with noreply@, bounce-handlers and one-off shop robots. A rule here is
# a small dict {"kind": ..., "value": ...} kept in the SAME addressbook.json,
# so every path that can add a contact already has it in hand.
#
#   address     an exact address            "robot@shop.example"
#   domain      that domain and below it    "example.com" → a@example.com and
#                                            a@mail.example.com, never
#                                            "notexample.com"
#   prefix      the address STARTS with it  "noreply"  → noreply-x@a.com
#   suffix      the address ENDS with it, or the name before the @ does —
#               so both ".ru" (a domain ending) and "-bounce" (a local-part
#               ending) work the way you would expect.
#
# Matching is case-insensitive. Blank rules are ignored rather than blocking
# everything, which is the failure mode that would matter here.
_NEVER_KINDS = ("address", "domain", "prefix", "suffix")

_NEVER_KIND_LABEL = {
    "address": "Address is",
    "domain":  "Domain is",
    "prefix":  "Starts with",
    "suffix":  "Ends with",
}

def _never_save_match(email: str, rules) -> dict:
    """Return the first rule that blocks this address, or None.

    Returning the RULE (not just True) is deliberate: every refusal can then
    say which line of the list did it, in the log and on screen."""
    addr = (email or "").strip().lower()
    if not addr:
        return None
    local, _, domain = addr.rpartition("@")
    if not local:            # no "@" at all — treat the whole thing as local
        local, domain = addr, ""
    for r in (rules or []):
        try:
            kind = (r.get("kind") or "address").lower()
            val  = (r.get("value") or "").strip().lower().lstrip("@")
        except AttributeError:
            continue
        if not val:
            continue
        if kind == "address":
            if addr == val:
                return r
        elif kind == "domain":
            if domain == val or domain.endswith("." + val):
                return r
        elif kind == "prefix":
            if local.startswith(val) or addr.startswith(val):
                return r
        elif kind == "suffix":
            if addr.endswith(val) or local.endswith(val):
                return r
    return None


# A starter set, offered by a button — never applied behind your back. These
# are the robots that fill an address book fastest.
_NEVER_SAVE_SUGGESTED = [
    {"kind": "prefix", "value": "noreply"},
    {"kind": "prefix", "value": "no-reply"},
    {"kind": "prefix", "value": "no_reply"},
    {"kind": "prefix", "value": "donotreply"},
    {"kind": "prefix", "value": "do-not-reply"},
    {"kind": "prefix", "value": "bounce"},
    {"kind": "prefix", "value": "mailer-daemon"},
    {"kind": "prefix", "value": "postmaster"},
    {"kind": "prefix", "value": "notification"},
    {"kind": "prefix", "value": "automated"},
    {"kind": "suffix", "value": "-bounce"},
]


# ******************************************************************************
# DEL 04c — GMAIL IMAP/SMTP BACKEND  (Phase 1: read-only fetch + send)
# ******************************************************************************
#
# PHASE-1 SAFETY: every IMAP mailbox is opened with readonly=True and bodies
# are fetched with BODY.PEEK[] — the Gmail server itself then refuses to
# change any flag or expunge any message. This program literally cannot make
# mail disappear from Gmail in this phase. SMTP send is additive (it only
# adds a new outgoing message) so it is allowed here.

import imaplib
import smtplib
import ssl
import re as _re
import string as _string
import email as _email
import html as _htmllib
import mimetypes
from email.header import decode_header, make_header
from email.utils import (parseaddr, parsedate_to_datetime, format_datetime,
                         formataddr, make_msgid)
from email.message import EmailMessage

IMAP_HOST = "imap.gmail.com"
IMAP_PORT = 993
SMTP_HOST = "smtp.gmail.com"
SMTP_PORT = 465

# Most-recent messages fetched per folder (keeps the first paint fast).
FETCH_LIMIT = 40

# Logical folder name -> default Gmail (English) IMAP mailbox. Used only as a
# fallback; _discover_mailboxes() finds the real (possibly localized, e.g.
# Swedish "[Gmail]/Skickat") names automatically via IMAP SPECIAL-USE flags.
_DEFAULT_MAILBOX = {
    "Inbox":    "INBOX",
    "Starred":  "[Gmail]/Starred",
    "Sent":     "[Gmail]/Sent Mail",
    "Drafts":   "[Gmail]/Drafts",
    "Spam":     "[Gmail]/Spam",
    "Trash":    "[Gmail]/Trash",
    "All Mail": "[Gmail]/All Mail",
}

# IMAP SPECIAL-USE attribute -> our logical folder name.
_SPECIAL_USE = {
    rb"\Sent": "Sent", rb"\Drafts": "Drafts", rb"\Junk": "Spam",
    rb"\Trash": "Trash", rb"\All": "All Mail", rb"\Flagged": "Starred",
}

_LIST_RE = _re.compile(
    rb'^\((?P<flags>[^)]*)\)\s+(?P<delim>"[^"]*"|NIL)\s+(?P<name>"(?:[^"\\]|\\.)*"|\S+)\s*$')

# Any of these SPECIAL-USE flags means "this is one of the standard folders we
# already show under its own English name" — so it is left OUT of the custom
# (user-created) folder list.
_STD_SPECIAL_USE = (rb"\Sent", rb"\Drafts", rb"\Junk", rb"\Trash",
                    rb"\All", rb"\Flagged", rb"\Important")


def _imap_utf7_decode(s: str) -> str:
    """Decode an IMAP modified-UTF-7 mailbox name (RFC 3501 §5.1.3) to Unicode.

    Gmail encodes non-ASCII folder names this way — "R&AOQ-kningar" is really
    "Räkningar". Names with no '&' are plain ASCII and returned untouched. The
    RAW (encoded) name must still be used when SELECTing the mailbox; this is
    only for what the sidebar shows the human."""
    if not s or "&" not in s:
        return s
    out, i, n = [], 0, len(s)
    while i < n:
        c = s[i]
        if c == "&":
            j = s.find("-", i)
            if j == -1:
                j = n
            chunk = s[i + 1:j]
            if chunk == "":
                out.append("&")                 # "&-" is a literal ampersand
            else:
                b64 = chunk.replace(",", "/")   # modified alphabet uses ','
                b64 += "=" * ((-len(b64)) % 4)
                try:
                    out.append(base64.b64decode(b64).decode("utf-16-be"))
                except Exception:
                    out.append(s[i:j + 1])      # leave it as-is if malformed
            i = j + 1
        else:
            out.append(c)
            i += 1
    return "".join(out)


def _imap_utf7_encode(s: str) -> str:
    """The inverse of _imap_utf7_decode: turn a HUMAN folder name into the RAW
    modified-UTF-7 name IMAP wants (RFC 3501 §5.1.3).

    This is why "move to folder" could not work for a label with a Swedish
    letter or an ampersand in it (Issu 2026-08-03, "det fungerar fortfarande
    inte med flytt"). The sidebar shows the DECODED name — "Temporär/0---Frakt
    & Kvitto" — and that decoded name was handed straight to IMAP. The server
    never has a mailbox by that name: on the wire it is called
    "Tempor&AOQ-r/0---Frakt &- Kvitto". Worse, imaplib encodes command
    arguments as ASCII, so "Temporär" raised UnicodeEncodeError before the
    command was even sent, and an ASCII-but-ampersand name silently addressed
    (or created!) a DIFFERENT label.

    The result is always plain ASCII, so it is safe to send as a command
    argument."""
    if not s:
        return s
    out, buf = [], []

    def _flush():
        if not buf:
            return
        data = "".join(buf).encode("utf-16-be")
        b64 = base64.b64encode(data).decode("ascii").rstrip("=")
        out.append("&" + b64.replace("/", ",") + "-")
        del buf[:]

    for ch in s:
        if ch == "&":
            _flush()
            out.append("&-")                 # a literal ampersand
        elif 0x20 <= ord(ch) <= 0x7E:
            _flush()
            out.append(ch)
        else:
            buf.append(ch)
    _flush()
    return "".join(out)


def _mb_arg(raw_name: str) -> bytes:
    """One mailbox name as a quoted IMAP command argument, in bytes.

    Bytes, not str, on purpose: imaplib encodes str arguments as ASCII and
    raises on anything else, and a raw modified-UTF-7 name is ASCII by
    construction — so this can never blow up mid-command."""
    safe = (raw_name or "").replace("\\", "\\\\").replace('"', '\\"')
    return b'"' + safe.encode("ascii", "replace") + b'"'


def _resolve_mailbox(imap, wanted: str, mapping=None, create=False) -> str:
    """Turn the folder name a HUMAN picked into the RAW IMAP mailbox name.

    `wanted` may be any of these and they all land in the same place:
      • a logical name we own  — "Inbox", "Trash", "All Mail"
      • the decoded path shown in the sidebar — "Temporär/0---Frakt & Kvitto"
      • the raw name already   — "Tempor&AOQ-r/0---Frakt &- Kvitto"

    With create=True a name that does not exist yet is encoded and created, so
    a first move into a brand-new label works. Returns "" for an empty name."""
    wanted = (wanted or "").strip()
    if not wanted:
        return ""
    mapping = mapping or {}
    if wanted in mapping:                     # Inbox / Sent / Trash / …
        return mapping[wanted]
    want_low = wanted.lower()

    delim = "/"
    # One LIST per CONNECTION, not per lookup: a move resolves both ends, and
    # a bulk move would otherwise ask the server for the whole folder list
    # twice for every single message.
    cached = getattr(imap, "_fm_listing", None)
    if cached is None:
        try:
            typ, data = imap.list()
        except Exception as e:
            log.warning("Mailbox resolve: LIST failed (%s) — using %r as-is",
                        e, wanted)
            typ, data = "NO", []
        cached = (typ, list(data or []))
        try:
            imap._fm_listing = cached
        except Exception:
            pass
    typ, data = cached
    if typ == "OK":
        for raw in data or []:
            if not raw:
                continue
            if isinstance(raw, tuple):
                raw = raw[0]
            if isinstance(raw, str):
                raw = raw.encode("utf-8", "replace")
            m = _LIST_RE.match(raw)
            if not m:
                continue
            name = m.group("name")
            if name.startswith(b'"'):
                name = name[1:-1]
            name_str = name.decode("utf-8", "replace")
            d_raw = m.group("delim")
            if d_raw and d_raw != b"NIL":
                delim = d_raw.strip(b'"').decode("ascii", "replace") or "/"
            disp = delim.join(_imap_utf7_decode(p)
                              for p in name_str.split(delim))
            if want_low in (name_str.lower(), disp.lower()):
                return name_str
            # Gmail hangs custom labels off INBOX; the sidebar drops that
            # prefix on the Inbox subtree, so "Temporär" may really be
            # "INBOX/Temporär". Accept either way round.
            for pre in ("INBOX" + delim, "Inbox" + delim):
                if disp.lower() == (pre + wanted).lower() or \
                        (pre + disp).lower() == want_low:
                    return name_str

    encoded = delim.join(_imap_utf7_encode(p) for p in wanted.split(delim))
    if create:
        try:
            imap.create(_mb_arg(encoded))
            log.info("Created mailbox %r (for %r)", encoded, wanted)
        except Exception as e:
            log.warning("Could not create mailbox %r: %s", encoded, e)
    else:
        log.warning("Mailbox %r not found on the server; using %r",
                    wanted, encoded)
    return encoded


def _list_user_folders(email_addr, password) -> list:
    """READ-ONLY. Return the account's own (custom-created) mailboxes — every
    label/folder that is NOT one of the standard Inbox/Sent/Drafts/Spam/Trash/
    Starred/All-Mail/Drafts set and is not a non-selectable container.

    Each entry: {"mailbox": <raw IMAP name, used to SELECT>,
                 "display": <human name of the LEAF segment>,
                 "full":    <human name of the whole path>,
                 "depth":   <how many levels deep, 0 = top>}.
    Sorted case-insensitively by full path so a tree renders in order."""
    # A read, so the shorter limit: a flaky account must not be able to spend
    # half a minute in front of the sidebar (Issu 2026-08-19).
    imap = _imap_connect(email_addr, password, timeout=IMAP_READ_TIMEOUT_SEC)
    out = []
    try:
        typ, data = imap.list()
        if typ != "OK":
            return []
        for raw in data:
            if not raw:
                continue
            if isinstance(raw, tuple):
                raw = raw[0]
            if isinstance(raw, str):
                raw = raw.encode("utf-8", "replace")
            m = _LIST_RE.match(raw)
            if not m:
                continue
            flags = m.group("flags")
            if rb"\Noselect" in flags or rb"\NonExistent" in flags:
                continue                      # a container, holds no mail
            if any(su in flags for su in _STD_SPECIAL_USE):
                continue                      # a standard folder, shown already
            name = m.group("name")
            if name.startswith(b'"'):
                name = name[1:-1]
            name_str = name.decode("utf-8", "replace")
            if name_str.upper() == "INBOX":
                continue
            # Gmail keeps its system folders under the ASCII "[Gmail]" (or
            # "[Google Mail]") namespace regardless of interface language.
            if name_str.startswith("[Gmail]") or name_str.startswith("[Google Mail]"):
                continue
            delim_raw = m.group("delim")
            delim = "/"
            if delim_raw and delim_raw != b"NIL":
                delim = delim_raw.strip(b'"').decode("ascii", "replace") or "/"
            raw_parts  = name_str.split(delim) if delim else [name_str]
            disp_parts = [_imap_utf7_decode(p) for p in raw_parts]
            human_full = delim.join(disp_parts)
            depth = len(raw_parts) - 1
            out.append({"mailbox": name_str, "display": disp_parts[-1],
                        "full": human_full, "depth": depth,
                        "delim": delim, "raw_parts": raw_parts,
                        "disp_parts": disp_parts})
    except Exception as e:
        log.warning("Folder listing failed for %s: %s", email_addr, e)
        return []
    finally:
        try:
            imap.logout()
        except Exception:
            pass
    out.sort(key=lambda f: f["full"].lower())
    return out


def _hdr_safe(value: str) -> str:
    """Make one string safe to put in a mail HEADER.

    A header is a single logical line. Anything with a real CR or LF in it
    makes Python's email package refuse the whole message with

        Header values may not contain linefeed or carriage return characters

    and that is exactly what happened to three of Issu's replies on
    2026-08-07. The culprit was NOT the subject (one of them was just
    "order 1237") but the References: header: it is copied straight off the
    message being answered, and a long thread's References arrives FOLDED —

        <id-1@x>\\r\\n <id-2@x>\\r\\n <id-3@x>

    — because that is how it travels on the wire. Re-folding is the sending
    library's job, not ours, so every header value is UNFOLDED here: each run
    of CR/LF/TAB collapses to one plain space. Applied to Subject, From, To,
    Cc, In-Reply-To and References alike, so no header can ever break a send
    again, whatever put the line break there."""
    if not value:
        return ""
    return _re.sub(r"[\r\n\t]+", " ", str(value)).strip()


def _dh(value) -> str:
    """Decode a possibly RFC2047-encoded header to a plain str — on ONE line.

    ── THE SUBJECT THAT CAME WITH AN EMPTY LINE IN IT (Issu 2026-08-22) ──────
    "Långa subject delas på två (eller flera?) rader… och lägger till en tom
     rad mellan raderna."

    A long header travels FOLDED — the wire carries

        Subject: Din order 999 har skickats med PostNord\\r\\n och kan hämtas ut

    — and the fold survives decoding untouched whenever the header is plain
    text rather than RFC2047-encoded (an =?utf-8?…?= subject is re-joined by
    decode_header, which is why only SOME long subjects showed it and it looked
    random). The pair then reaches a Tk Label, and Tk breaks a line on the
    "\\n" AND draws the "\\r" as a line of its own: measured, one label,
    same text — 23 px on one line, 40 px with a bare "\\n", 57 px with
    "\\r\\n". That third line, blank, is the empty row he was looking at.

    A header is a single logical line by definition, so the fold is simply
    undone here. Note that the break AND the continuation line's leading
    whitespace go together: a fold is written "…PostNord\\r\\n och kan…", so
    collapsing only the CR/LF leaves "PostNord  och" with two spaces in it —
    less obvious than the blank row, but just as wrong, and it would show up
    in every search and every filter that matches on the subject. The whole
    run of whitespace around the break becomes ONE space.

    Long subjects still wrap where they are shown with a wraplength (the
    reading pane); that wraps cleanly and puts nothing between the rows."""
    if not value:
        return ""
    try:
        text = str(make_header(decode_header(value)))
    except Exception:
        text = str(value)
    return _re.sub(r"[ \t]*[\r\n]+[ \t]*", " ", text).replace("\t", " ").strip()


# ── A DEAD READ MUST DIE INSIDE THE ROUND, NOT AFTER IT (Issu 2026-08-19) ─────
#
# The socket timeout was 30 s while the refresh round gives up at 25 s
# (FETCH_DEADLINE_SEC). Those five seconds the wrong way round meant a stalled
# read could NEVER fail inside its own round: the round was always abandoned
# first, and the thread carried on holding the pooled connection into the next
# one. Reads now fail at 20 s — comfortably inside the round, so the fetch
# reports a real error, the account is stood down cleanly, and the next check
# starts from a known state instead of queueing behind a ghost.
#
# Only the pooled READ path uses it. Uploading a message (append/move) keeps the
# longer limit: that one really can take half a minute on a big attachment.
IMAP_READ_TIMEOUT_SEC = 20
IMAP_WRITE_TIMEOUT_SEC = 30


def _imap_connect(email_addr: str, password: str,
                  timeout: int = IMAP_WRITE_TIMEOUT_SEC) -> imaplib.IMAP4_SSL:
    # A timeout so a dead connection fails fast instead of hanging the account's
    # lock forever (matters now that connections are pooled and reused).
    try:
        imap = imaplib.IMAP4_SSL(IMAP_HOST, IMAP_PORT, timeout=timeout)
    except TypeError:
        imap = imaplib.IMAP4_SSL(IMAP_HOST, IMAP_PORT)   # very old Python
    imap.login(email_addr, password)
    return imap


# ── Connection reuse pool (DEL 04v) ───────────────────────────────────────────
# Every read used to log in fresh and log out again. Switching folders, the
# per-account auto-check, the unread-count pass and the quota check could open a
# dozen logins at once — and Gmail answers "Too many simultaneous connections",
# which is the multi-second stall Issu saw between folders (it is right there in
# Freemail.log).
#
# This keeps ONE authenticated connection per account behind a per-account lock,
# so (a) the login is reused instead of repeated, and (b) each account can only
# ever have a single connection in flight — no more storms. A connection that
# has gone stale (Gmail idles them out) is spotted with NOOP and replaced.
#
# Only the READ hot-path uses the pool. The delete / move / expunge / append
# paths still open their own short-lived connection: they are rare, and leaving
# that careful, well-tested code untouched keeps the risk here contained.
#
# ── TWO LANES (Issu 2026-08-08: "loading… det tog nog cirka 30 sekunder") ──────
#
# One connection per account was an improvement over a login per read, but it
# put EVERYTHING in one queue. Measured from his own Freemail.log and settings:
#
#   • the auto-check re-fetches the open folder every ~63 seconds, and
#   • the unread-count pass STATUSes 21 mailboxes on issusbarn@gmail.com in
#     that same cycle (7 standard + 14 of his own labels), and
#   • the quota check joins in every 15 minutes,
#
# all through the ONE connection. Click a message at the wrong moment and the
# on-demand body fetch simply waits its turn behind all of it. That is the
# half-minute — not a slow server, a queue.
#
# So reads now use one of TWO lanes:
#   "bg" — everything automatic: the periodic fetch, counts, quota, prefetch.
#   "ui" — YOU clicked something and are watching the screen.
# They are separate pooled connections, so a click never waits for a background
# pass. Two per account is still far below Gmail's simultaneous-connection
# limit (the old code opened a fresh login per read and hit exactly that —
# "Too many simultaneous connections" is in his log), and the ui connection is
# closed again after a few minutes idle by _imap_reap_idle().
_IMAP_POOL = {}                     # (email, lane) -> {"imap", "lock", "used"}
_IMAP_POOL_GUARD = threading.Lock()
_IMAP_REUSE = True                  # mirrors cfg["imap_reuse"]; set at start-up

# Set while a click is waiting for the wire. Background loops check it between
# steps and stand aside — see _background_yield. Counted rather than a bare
# flag, so two overlapping clicks cannot have the first one to finish clear the
# flag while the second is still waiting.
_UI_WAITING = threading.Event()
_UI_WAITING_N = 0
_UI_WAITING_GUARD = threading.Lock()
_UI_LANE_IDLE_SEC = 300             # close an unused "ui" connection after this

# ── A FOLDER FETCH OUTRANKS THE READ-AHEAD (Issu 2026-08-19) ──────────────────
#
# _UI_WAITING above only knows about YOU clicking. That left the read-ahead
# (_prefetch_bodies) and the every-minute auto-check as equals, both "just
# background" — and on 2026-08-19 the read-ahead won for three quarters of an
# hour. He opened 0---Frakt & Kvitto, the read-ahead started pulling twelve
# whole receipt bodies (Tradera and DHL receipts carry PDFs) down the ONE
# background connection issusbarn@gmail.com has, and the Inbox check that
# would have found his new shipping mail queued behind them every single time:
#
#   06:20:39  Prefetched 12 message body/bodies … 0---Frakt & Kvitto
#   06:15:18  Drawing the list without issusbarn@gmail.com — still fetching
#             after 25 s   (× 34 today)
#
# Reading ahead is a convenience — it saves a wait LATER. Finding new mail is
# the job. So a fetch of a folder now raises this flag for its duration and the
# read-ahead stands aside between messages, exactly as it already does for a
# click.
_FETCH_WAITING = threading.Event()
_FETCH_WAITING_N = 0
_FETCH_WAITING_GUARD = threading.Lock()


def _ui_wait_begin():
    global _UI_WAITING_N
    with _UI_WAITING_GUARD:
        _UI_WAITING_N += 1
        _UI_WAITING.set()


def _ui_wait_end():
    global _UI_WAITING_N
    with _UI_WAITING_GUARD:
        _UI_WAITING_N = max(0, _UI_WAITING_N - 1)
        if _UI_WAITING_N == 0:
            _UI_WAITING.clear()


def _fetch_wait_begin():
    global _FETCH_WAITING_N
    with _FETCH_WAITING_GUARD:
        _FETCH_WAITING_N += 1
        _FETCH_WAITING.set()


def _fetch_wait_end():
    global _FETCH_WAITING_N
    with _FETCH_WAITING_GUARD:
        _FETCH_WAITING_N = max(0, _FETCH_WAITING_N - 1)
        if _FETCH_WAITING_N == 0:
            _FETCH_WAITING.clear()


def _set_imap_reuse(on: bool):
    global _IMAP_REUSE
    _IMAP_REUSE = bool(on)


def _background_yield(max_wait=15.0, for_fetch=False):
    """Called by background loops between steps: pause while the user is
    waiting for something.

    Cheap insurance on top of the two lanes — it also keeps the ACCOUNT quiet
    (Gmail throttles a chatty connection), and it can never deadlock because it
    gives up after `max_wait` whatever happens.

    `for_fetch=True` also stands aside for a folder fetch in progress, not just
    for a click. Only the read-ahead passes it: everything else IS the fetch, or
    is quick enough not to matter. Nothing that holds a lock ever waits here, so
    the extra condition cannot deadlock either — and the time limit still
    applies whatever happens."""
    def _busy():
        return _UI_WAITING.is_set() or (for_fetch and _FETCH_WAITING.is_set())
    if not _busy():
        return
    waited = 0.0
    while _busy() and waited < max_wait:
        time.sleep(0.05)
        waited += 0.05


def _imap_pool_entry(email_addr, lane="bg"):
    with _IMAP_POOL_GUARD:
        key = (email_addr, lane)
        e = _IMAP_POOL.get(key)
        if e is None:
            e = {"imap": None, "lock": threading.RLock(), "used": 0.0}
            _IMAP_POOL[key] = e
        return e


def _imap_reap_idle():
    """Close "ui" connections that have not been used for a while, so the
    interactive lane costs nothing when you are not clicking."""
    now = time.time()
    with _IMAP_POOL_GUARD:
        entries = [(k, v) for k, v in _IMAP_POOL.items() if k[1] == "ui"]
    for key, e in entries:
        if e["imap"] is None or (now - e.get("used", 0.0)) < _UI_LANE_IDLE_SEC:
            continue
        if not e["lock"].acquire(blocking=False):
            continue                     # in use right now — leave it alone
        try:
            imap, e["imap"] = e["imap"], None
            if imap is not None:
                try:
                    imap.logout()
                except Exception:
                    pass
                log.debug("Closed idle interactive connection for %s", key[0])
        finally:
            e["lock"].release()


def _imap_alive(imap, seconds=5.0) -> bool:
    """Is this pooled connection still usable? Asked with a SHORT timeout.

    Issu 2026-08-17: the probe was a bare noop() on a socket whose timeout is
    30 seconds, so being handed a dead connection cost half a minute before
    anything else could even start. Five seconds is far more than a live
    server needs to answer NOOP, and a dead one is spotted six times sooner."""
    sock = getattr(imap, "sock", None)
    old = None
    try:
        if sock is not None:
            old = sock.gettimeout()
            sock.settimeout(seconds)
        imap.noop()
        return True
    except Exception:
        return False
    finally:
        if sock is not None and old is not None:
            try:
                sock.settimeout(old)
            except Exception:
                pass


def _imap_close_fast(imap, seconds=1.5):
    """Drop one connection without waiting on the network.

    LOGOUT is a round trip: it sends the command and waits for BYE. On a socket
    that has already stopped answering that wait is the full 30-second timeout,
    which is why closing the program took so long and the window went "not
    responding" (Issu 2026-08-17) — _imap_pool_close_all runs on the main
    thread, once per pooled connection.

    Be polite when it is cheap, hang up when it is not. A dropped IMAP
    connection is completely normal; the server tidies up on its own."""
    sock = getattr(imap, "sock", None)
    try:
        if sock is not None:
            sock.settimeout(seconds)
        imap.logout()
        return
    except Exception:
        pass
    for closer in ("shutdown", "close"):
        try:
            getattr(imap, closer)()
        except Exception:
            pass
    try:
        if sock is not None:
            sock.close()
    except Exception:
        pass


# ── WAITING FOR THE POOL IS BOUNDED (Issu 2026-08-19) ─────────────────────────
#
# `entry["lock"].acquire()` with no limit is what turned one stuck read into a
# dead account: the auto-check blocked on it, so `done()` never ran, so the next
# timer was never armed, so that account stopped being checked at all and only a
# manual Refresh found anything. Nothing in the log said so, because nothing had
# failed — it was simply waiting, for ever.
#
# A caller now waits this long and then goes around the pool with a private
# connection for that one read. Rare by construction (it takes a genuinely stuck
# lane), bounded (one extra socket per waiting caller, closed straight after),
# and far below Gmail's simultaneous-connection limit.
IMAP_LOCK_WAIT_SEC = 12

# Which pooled locks THIS thread actually holds. Without it a caller that went
# around the pool would, on release, null out `entry["imap"]` and log out a
# connection another thread was in the middle of using — which is precisely the
# "[WinError 10038] … not a socket" in his log for 06:18:39.
_POOL_LOCAL = threading.local()

# Who has each lane right now, so the "busy for 12 s" warning can say WHAT it
# was waiting behind (Issu 2026-10-12: opening a message sometimes takes ages).
_POOL_HOLDER = {}          # (email, lane) -> (function name, thread, since)


def _pool_owned() -> dict:
    d = getattr(_POOL_LOCAL, "owned", None)
    if d is None:
        d = {}
        _POOL_LOCAL.owned = d
    return d


def _imap_acquire(email_addr, password, lane="bg"):
    """A reused, authenticated connection for one account, with its lock held.
    Falls back to a plain fresh login when reuse is switched off. Always pair
    with _imap_release().

    lane="ui" for anything the user is waiting on, so it never queues behind
    the automatic passes."""
    if not _IMAP_REUSE:
        return _imap_connect(email_addr, password,
                             timeout=IMAP_READ_TIMEOUT_SEC)
    entry = _imap_pool_entry(email_addr, lane)
    key = (email_addr, lane)
    if not entry["lock"].acquire(timeout=IMAP_LOCK_WAIT_SEC):
        # The lane is stuck. Do NOT queue behind it — that is how an account
        # stops being checked altogether.
        _h = _POOL_HOLDER.get(key)
        log.warning("The %s connection for %s has been busy for %d s — using a "
                    "separate one for this read rather than waiting "
                    "(held by %s on thread %s for %.0f s; wanted by %s)",
                    lane, email_addr, IMAP_LOCK_WAIT_SEC,
                    _h[0] if _h else "?", _h[1] if _h else "?",
                    (time.time() - _h[2]) if _h else 0.0,
                    sys._getframe(1).f_code.co_name)
        _pool_owned()[key] = False
        try:
            return _imap_connect(email_addr, password,
                                 timeout=IMAP_READ_TIMEOUT_SEC)
        except Exception:
            _pool_owned().pop(key, None)
            raise
    _pool_owned()[key] = True
    entry["used"] = time.time()
    try:
        _POOL_HOLDER[key] = (sys._getframe(1).f_code.co_name,
                             threading.current_thread().name, time.time())
    except Exception:
        pass
    try:
        imap = entry["imap"]
        if imap is not None and not _imap_alive(imap):
            _imap_close_fast(imap)
            imap = None
            entry["imap"] = None
        if imap is None:
            imap = _imap_connect(email_addr, password,
                                 timeout=IMAP_READ_TIMEOUT_SEC)
            entry["imap"] = imap
        return imap
    except Exception:
        # Could not hand one out — never leave the lock held.
        _pool_owned().pop(key, None)
        _POOL_HOLDER.pop(key, None)
        try:
            entry["lock"].release()
        except RuntimeError:
            pass
        raise

def _imap_release(email_addr, imap, broken=False, lane="bg"):
    """Give the connection back. Kept warm for next time unless `broken`, in
    which case it is dropped so the next call reconnects."""
    if not _IMAP_REUSE:
        try:
            imap.logout()
        except Exception:
            pass
        return
    key = (email_addr, lane)
    owned = _pool_owned().pop(key, None)
    if owned is False:
        # A private connection opened because the lane was busy. It is ours
        # alone: close it, and touch nothing in the pool.
        try:
            imap.logout()
        except Exception:
            pass
        return
    entry = _IMAP_POOL.get(key)
    if entry is None:
        return
    entry["used"] = time.time()
    _POOL_HOLDER.pop(key, None)
    if broken:
        try:
            if entry["imap"] is not None:
                entry["imap"].logout()
        except Exception:
            pass
        entry["imap"] = None
    if owned:
        try:
            entry["lock"].release()
        except RuntimeError:
            pass

# ── ONE SICK ACCOUNT MUST NOT COST EVERY REFRESH A MINUTE (Issu 2026-08-17) ───
#
# Straight out of his own log, 2026-08-17 07:15–09:16: Loss.THN@gmail.com timed
# out 22 times in two hours, always at exactly the 30-second socket timeout, and
# usually TWICE in a row — _fetch_folder_smart tried the cached fetch, that
# timed out, and it immediately tried the FULL fetch, which timed out too over
# the same dead socket. One whole minute of waiting per attempt, on an account
# that was not answering at all:
#
#   07:32:07  Cached fetch failed for Loss.THN@gmail.com/Inbox … timed out
#   07:32:37  Cached fetch failed for Loss.THN@gmail.com/Inbox … timed out
#   07:33:07  Fetch failed for Loss.THN@gmail.com/Inbox … timed out
#
# In the All Accounts view every refresh joins EVERY account's thread before the
# list is drawn, so that minute is exactly the "fastnar i updating/loading".
#
# Two changes:
#   • a fetch that died because the CONNECTION stalled is not retried as a full
#     fetch — the cache was never the problem, so pulling everything down again
#     over the same dead socket can only cost another 30 seconds;
#   • an account that stalls is stood down for a while (2 minutes, doubling to
#     10) so AUTOMATIC passes skip it rather than paying the timeout every
#     single minute. Anything YOU do — opening a folder, pressing ↻ Refresh —
#     always tries every account and clears the stand-down first, so an account
#     can never be quietly written off while you are looking at it. And a
#     skipped account keeps the messages already on screen (see _refresh_
#     messages): standing an account down must never make its mail disappear.

_STALL_UNTIL = {}                  # email -> monotonic deadline
_STALL_STEP  = {}                  # email -> length of the last stand-down
_STALL_GUARD = threading.Lock()
STALL_FIRST_SEC = 120
STALL_MAX_SEC   = 600

# How long ONE round of fetching may take before the list is drawn with
# whatever has arrived. Not per account — for the whole round. A five-account
# view used to wait 120 s PER account, which is the "konstant loading".
FETCH_DEADLINE_SEC = 25


def _is_network_stall(exc) -> bool:
    """Did this fail because the CONNECTION is dead or timed out, rather than
    for any reason to do with the mail itself?

    Deliberately generous: the cost of being wrong is one extra retry, while
    missing a stall costs thirty seconds of a frozen window."""
    if isinstance(exc, (TimeoutError, ConnectionError, OSError)):
        return True
    text = str(exc).lower()
    return any(s in text for s in (
        "timed out", "timeout", "cannot read from", "state logout",
        "socket error", "eof occurred", "broken pipe", "connection"))


def _stall_note(email_addr) -> int:
    """Stand this account down after a stall. Returns the seconds chosen."""
    with _STALL_GUARD:
        step = min(max(_STALL_STEP.get(email_addr, 0) * 2, STALL_FIRST_SEC),
                   STALL_MAX_SEC)
        _STALL_STEP[email_addr]  = step
        _STALL_UNTIL[email_addr] = time.monotonic() + step
    log.warning("%s is not answering — automatic passes will skip it for "
                "%d s (you can still open it by hand)", email_addr, step)
    return step


def _stall_clear(email_addr):
    """It answered (or you asked for it yourself) — back to normal."""
    with _STALL_GUARD:
        _STALL_UNTIL.pop(email_addr, None)
        _STALL_STEP.pop(email_addr, None)


def _stall_left(email_addr) -> float:
    """Seconds an automatic pass should still leave this account alone."""
    with _STALL_GUARD:
        until = _STALL_UNTIL.get(email_addr)
    return 0.0 if until is None else max(0.0, until - time.monotonic())


def _imap_pool_close_all(max_seconds=2.5):
    """Close every pooled connection, both lanes (called on exit).

    All of them at once, on daemon threads, with ONE short deadline for the lot
    — closing the program must never wait on a server. Anything still trying
    when the deadline passes is abandoned; the process is about to end and the
    server drops the connection by itself (Issu 2026-08-17: "lång tid att
    stänga av… not responding")."""
    with _IMAP_POOL_GUARD:
        live = []
        for _key, e in list(_IMAP_POOL.items()):
            imap = e.get("imap")
            e["imap"] = None
            if imap is not None:
                live.append(imap)
    if not live:
        return
    threads = [threading.Thread(target=_imap_close_fast, args=(imap,),
                                daemon=True) for imap in live]
    for t in threads:
        t.start()
    deadline = time.monotonic() + max_seconds
    for t in threads:
        t.join(timeout=max(0.05, deadline - time.monotonic()))
    stuck = sum(1 for t in threads if t.is_alive())
    if stuck:
        log.info("Left %d IMAP connection(s) to be dropped by the server — "
                 "not waiting for them on the way out", stuck)


def _discover_mailboxes(imap) -> dict:
    """Return {logical_folder: real_mailbox} resolved from the account's
    own SPECIAL-USE flags, so localized Gmail folder names just work."""
    mapping = dict(_DEFAULT_MAILBOX)
    try:
        typ, data = imap.list()
        if typ == "OK":
            for raw in data:
                if not raw:
                    continue
                if isinstance(raw, tuple):
                    raw = raw[0]
                if isinstance(raw, str):
                    raw = raw.encode("utf-8", "replace")
                m = _LIST_RE.match(raw)
                if not m:
                    continue
                flags = m.group("flags")
                name  = m.group("name")
                if name.startswith(b'"'):
                    name = name[1:-1]
                name_str = name.decode("utf-8", "replace")
                for attr, logical in _SPECIAL_USE.items():
                    if attr in flags:
                        mapping[logical] = name_str
    except Exception as e:
        log.warning("Mailbox discovery failed, using defaults: %s", e)
    return mapping


def _decode_part(part) -> str:
    try:
        payload = part.get_payload(decode=True)
        if payload is None:
            return ""
        charset = part.get_content_charset() or "utf-8"
        return payload.decode(charset, "replace")
    except Exception:
        try:
            return part.get_payload()
        except Exception:
            return ""


# ── Mail that shows "=C3=A5" instead of "å" (Issu 2026-08-18) ────────────────
#
# "Sl=C3=A5 klockan =E2=80=93 och spara!" is quoted-printable that reached the
# screen without being decoded: =C3=A5 is the two UTF-8 bytes for å, =E2=80=93
# is an en dash, and a lone "=" at the end of a line is a SOFT line break —
# which is why such a mail also comes out double-spaced, every line broken in
# the middle of a word.
#
# _decode_part already asks email.message for the decoded payload, so a
# well-formed message never gets here. This is for the ones that arrive
# malformed enough that the parser gives up and hands back the raw text.
# Rather than guess at every way a sender can be wrong, the repair is done on
# the TEXT, at the moment a message is opened — no sweep, nothing read in the
# background, and it costs nothing on the overwhelming majority of mail
# because _looks_quoted_printable says no immediately.

def _looks_quoted_printable(text: str) -> bool:
    """Cheap, strict test: does this text look like UNDECODED quoted-printable?

    Deliberately hard to trigger. A URL full of "?a=b&c=d", a code snippet or a
    line of "=====" must never qualify, so it takes an escape that decodes to a
    HIGH byte (0x80+) — the thing that actually renders as mojibake — and more
    than one of them."""
    if not text:
        return False
    esc = _re.findall(r"=([0-9A-Fa-f]{2})", text)
    if len(esc) < 2:
        return False
    high = [h for h in esc if int(h, 16) >= 0x80]
    return len(high) >= 2


def _undo_quoted_printable(text: str, charset: str = "utf-8") -> str:
    """Turn "Sl=C3=A5 klockan" back into "Slå klockan", and rejoin the lines
    that a soft break cut in half.

    Returns the text UNCHANGED if the result would be worse — if the bytes do
    not actually decode in the charset the message claims. A message that is
    merely odd must never be made unreadable by trying to help it."""
    if not text:
        return text
    s = text.replace("\r\n", "\n").replace("\r", "\n")
    # Soft line break: "=" as the last thing on a line means "this line and the
    # next are one line". Trailing spaces before it are legal and common.
    s = _re.sub(r"=[ \t]*\n", "", s)
    out = bytearray()
    i, n = 0, len(s)
    while i < n:
        if (s[i] == "=" and i + 2 < n
                and s[i + 1] in _string.hexdigits
                and s[i + 2] in _string.hexdigits):
            out.append(int(s[i + 1:i + 3], 16))
            i += 3
        else:
            out.extend(s[i].encode("utf-8", "replace"))
            i += 1
    for cs in (charset or "utf-8", "utf-8", "cp1252", "latin-1"):
        try:
            fixed = out.decode(cs)
        except (UnicodeDecodeError, LookupError):
            continue
        # Only accept a repair that did not invent replacement characters.
        if fixed.count("�") > text.count("�"):
            continue
        return fixed
    return text


def _repair_encoding(text: str, charset: str = "utf-8") -> tuple:
    """(repaired_text, was_repaired) — the two helpers above as one call."""
    if not _looks_quoted_printable(text):
        return text, False
    fixed = _undo_quoted_printable(text, charset)
    return (fixed, True) if fixed != text else (text, False)


def _html_to_text(html: str) -> str:
    if not html:
        return ""
    text = _re.sub(r"(?is)<(script|style).*?>.*?</\1>", "", html)
    # HTML COMMENTS are never content, and Outlook's conditional blocks hide
    # real-looking text inside them: DHL's mail carries
    # <!--[if mso]>…<o:PixelsPerInch>96</o:PixelsPerInch>…<![endif]-->, and
    # tag-stripping alone left a bare "96" sitting at the top of the message
    # (Issu 2026-08-16). Removed before anything else looks at the markup.
    text = _re.sub(r"(?s)<!--.*?-->", "", text)

    # Keep hyperlink TARGETS. An <a href="URL">label</a> becomes "label (URL)"
    # so the address survives into the plain-text body — the reading pane then
    # makes it clickable AND copyable (Issu: DHL tracking links lived only in
    # the href, so after tag-stripping they were neither). Parentheses (NOT
    # angle brackets — the generic <...> tag strip below would eat those) sit on
    # _URL_RE's boundary, so the clickable span is exactly the URL. Only real
    # http(s) targets, and only when the URL is not already in the label (so a
    # plain "https://…" link is not doubled).
    def _keep_link(m):
        url = (m.group("url") or "").strip()
        label = _re.sub(r"(?is)<.*?>", "", m.group("label") or "")
        label = _htmllib.unescape(label).strip()
        if not url or not url.lower().startswith(("http://", "https://")):
            return label
        if url in label:
            return label
        return f"{label} ({url})" if label else url
    text = _re.sub(
        r'(?is)<a\b[^>]*?\bhref\s*=\s*["\'](?P<url>[^"\']+)["\'][^>]*>'
        r'(?P<label>.*?)</a>',
        _keep_link, text)

    text = _re.sub(r"(?is)<br\s*/?>", "\n", text)
    text = _re.sub(r"(?is)</p\s*>", "\n\n", text)
    text = _re.sub(r"(?is)<.*?>", "", text)
    text = _htmllib.unescape(text)
    # CRLF first, or the trailing-space cleanup below never matches (it looks
    # for "\n") and a table-based mail keeps dozens of space-only lines — which
    # is exactly how DHL's converted mail opened with a screenful of nothing.
    text = text.replace("\r\n", "\n").replace("\r", "\n")
    # NON-BREAKING SPACES COUNT AS WHITESPACE HERE (Issu 2026-08-16).
    # &nbsp; unescapes to \xa0, which is not matched by [ \t] — so a table-based
    # mail kept hundreds of lines holding one invisible \xa0 each. They were not
    # "blank", so the \n{3,} collapse below could never join the runs they broke,
    # and a Tradera mail opened as four screens of nothing. Measured on his own
    # mail: 714 lines, 410 of them visually blank. \xa0 is folded into a plain
    # space first, and every cleanup below then sees ordinary whitespace.
    text = text.replace("\xa0", " ")
    # Leading indentation is layout in HTML, never meaning — a nested table
    # otherwise arrives as text pushed 20 columns to the right. Safe here
    # because this function only ever sees markup.
    text = _re.sub(r"(?m)^[ \t]+", "", text)
    text = _re.sub(r"[ \t]+\n", "\n", text)
    text = _re.sub(r"\n{3,}", "\n\n", text)
    return text.strip()


def _demote_html_masquerading_as_text(text: str) -> str:
    """A text/plain part that is actually an HTML document → readable text.

    Returns the text unchanged unless it is convincingly a whole HTML
    document. "Convincingly" means a real opening marker at the very start
    (<!DOCTYPE html> / <html …>) OR a structural tag plus its closing partner —
    never just an angle bracket somewhere in a sentence, which is why a mail
    that merely quotes "<html>" while discussing it is left alone."""
    if not text:
        return text
    head = text.lstrip()[:400].lower()
    looks = head.startswith("<!doctype html") or head.startswith("<html")
    if not looks:
        low = text.lower()
        looks = any(f"<{t}" in low and f"</{t}>" in low
                    for t in ("html", "body", "table", "div"))
    if not looks:
        return text
    converted = _html_to_text(text)
    # Only accept the conversion if it actually produced readable text; a page
    # that is nothing but <style> would otherwise blank the message entirely,
    # and an empty body is worse than an ugly one.
    return converted if converted.strip() else text


def _strip_remote_images(html: str) -> str:
    """Neutralize remote <img>/background URLs so opening an HTML mail does
    not phone home to tracking pixels. Inline cid: images are left alone."""
    if not html:
        return html
    # Blank out src="http(s)://…" on <img> tags
    html = _re.sub(r'(?i)(<img\b[^>]*?\bsrc\s*=\s*)(["\'])\s*https?:[^"\']*\2',
                   r'\1\2\2', html)
    # Remove url(http…) in inline styles / background images
    html = _re.sub(r'(?i)url\(\s*["\']?\s*https?:[^)]*\)', 'none', html)
    return html


def _extract_body_and_attachments(msg):
    body_plain, body_html = "", ""
    attachments, attach_data = [], {}
    ics_text = ""          # meeting invitation, if the mail carries one
    if msg.is_multipart():
        for part in msg.walk():
            if part.is_multipart():
                continue
            ctype    = part.get_content_type()
            # A meeting invitation usually rides along as a text/calendar
            # part with no filename, so it would otherwise be invisible.
            # Grab it here for the calendar (DEL 04f) and let the normal
            # attachment logic below still see it if it HAS a filename.
            if ctype == "text/calendar" and not ics_text:
                ics_text = _decode_part(part)
            disp     = (part.get("Content-Disposition") or "").lower()
            # _hdr_safe as well as _dh: a long filename is FOLDED across lines
            # in the header it comes from, and the raw CR/LF survives into the
            # decoded name. One is sitting in Issu's own Sent folder —
            # "WhatsApp Image 2026-07-16 at\r\n 18.23.30.jpeg" — which would
            # print as two lines in the attachment list and fail outright when
            # saved, since Windows will not have a newline in a filename.
            filename = _hdr_safe(_dh(part.get_filename())) if part.get_filename() else ""
            is_attach = ("attachment" in disp or
                         (filename and ctype not in ("text/plain", "text/html")))
            if is_attach:
                try:
                    payload = part.get_payload(decode=True) or b""
                except Exception:
                    payload = b""
                fn = filename or "attachment"
                # Avoid clobbering duplicate filenames
                base, n = fn, 1
                while fn in attach_data:
                    root_, ext_ = os.path.splitext(base)
                    fn = f"{root_}({n}){ext_}"; n += 1
                attachments.append(fn)
                attach_data[fn] = payload
            elif ctype == "text/plain" and not body_plain:
                body_plain = _decode_part(part)
            elif ctype == "text/html" and not body_html:
                body_html = _decode_part(part)
    else:
        if msg.get_content_type() == "text/html":
            body_html = _decode_part(msg)
        else:
            body_plain = _decode_part(msg)
    # ── A "plain text" part that is really HTML (Issu 2026-08-16) ───────────
    # DHL's "Ditt paket från …" mails declare text/plain and then put a full
    # HTML document in it — <!DOCTYPE html>, <style> blocks, the lot. Taking it
    # at its word meant the reading pane showed hundreds of lines of markup and
    # the ONE thing that mattered, the parcel's own hamta.dhl.com link, was
    # buried inside an href where it was neither clickable nor visible.
    #
    # This is not a per-sender rule and should not be: any sender that mislabels
    # a part is fixed by the same check, now and later. _html_to_text keeps
    # link TARGETS, so the tracking URL survives into the text and the pane
    # makes it clickable. Deliberately narrow — a real plain-text mail that
    # merely mentions "<html>" in a sentence has no document structure and is
    # left exactly as it is.
    body_plain = _demote_html_masquerading_as_text(body_plain)
    body = body_plain.strip() or _html_to_text(body_html)
    return body, attachments, attach_data, body_html, ics_text


def _fmt_date(dt):
    """Return (display_string, sort_key) for an email Date header datetime."""
    if dt is None:
        return "", 0.0
    try:
        local = dt.astimezone()
    except Exception:
        local = dt
    try:
        sortkey = local.timestamp()
    except Exception:
        sortkey = 0.0
    now = datetime.now(local.tzinfo) if local.tzinfo else datetime.now()
    delta = (now.date() - local.date()).days
    if delta == 0:
        disp = "Today " + local.strftime("%H:%M")
    elif delta == 1:
        disp = "Yesterday"
    elif 1 < delta < 7:
        disp = local.strftime("%a %H:%M")
    else:
        disp = local.strftime("%Y-%m-%d")
    return disp, sortkey


# ── Exact time, on demand (Issu 2026-08-29) ─────────────────────────────────
# "Det räcker med att visa Yesterday, vanligtvis, men ibland så är det viktigt
# och då vill jag kunna klicka fram den informationen."
#
# The short form above stays exactly as it is — it is the right thing to read
# 99 times out of 100. But "Yesterday" throws away the clock entirely, and when
# it matters (who answered first, was this before or after the deadline, did
# the parcel notice really arrive at 04:00) there was no way to get it back
# short of the raw source. So the full timestamp is kept on every message and
# is one click away wherever the short one is shown.
def _exact_time(msg) -> str:
    """The message's own Date: header, spelled out in full local time.

    Falls back to the short display string when the header was missing or
    unparseable — never returns "" for a message that shows a date, because a
    blank answer to "what time exactly?" reads as a bug."""
    iso = (msg or {}).get("_dt", "") or ""
    if not iso:
        return (msg or {}).get("date", "") or "(no date in this message)"
    try:
        local = datetime.fromisoformat(iso)
    except Exception:
        return (msg or {}).get("date", "") or iso
    # "Thursday 28 August 2026, 14:33:07" — spelled out, so it cannot be
    # misread as a day/month swap the way 08-09 can.
    out = local.strftime("%A %d %B %Y, %H:%M:%S")
    # Offset only, no time-zone NAME: _dt is round-tripped through
    # isoformat/fromisoformat, so its tzinfo is a bare fixed offset and %Z just
    # spells that offset out a second time ("(UTC+02:00, UTC+02:00)").
    off = local.strftime("%z")
    if off and len(off) == 5:
        out += f"  (UTC{off[:3]}:{off[3:]})"
    # If the sender's clock was on a different offset, say so — otherwise the
    # exact time silently answers a question you did not ask.
    orig = (msg or {}).get("_dt_orig", "") or ""
    if orig:
        try:
            sender = datetime.fromisoformat(orig)
            if sender.utcoffset() != local.utcoffset():
                soff = sender.strftime("%z")
                if soff and len(soff) == 5:
                    soff = f"UTC{soff[:3]}:{soff[3:]}"
                out += (f"   ·   sent {sender.strftime('%H:%M:%S')} "
                        f"where the sender was ({soff})")
        except Exception:
            pass
    return out


def _exact_time_short(msg) -> str:
    """Same instant, one compact line — for a menu label or a tooltip."""
    iso = (msg or {}).get("_dt", "") or ""
    if not iso:
        return (msg or {}).get("date", "") or ""
    try:
        return datetime.fromisoformat(iso).strftime("%Y-%m-%d  %H:%M:%S")
    except Exception:
        return (msg or {}).get("date", "") or iso


_LABELS_RE = _re.compile(r'X-GM-LABELS\s+\(([^)]*)\)')


def _parse_gm_labels(meta_s: str) -> list:
    """Gmail's labels for a message, from the FETCH response.

    These matter for deletion: Gmail keeps ONE message and hangs labels on it,
    so trashing it removes it from EVERY label at once. The confirmation
    dialog names them, which is the whole point of keeping them."""
    m = _LABELS_RE.search(meta_s or "")
    if not m:
        return []
    out = []
    for raw in _re.findall(r'"([^"]*)"|(\S+)', m.group(1)):
        label = (raw[0] or raw[1] or "").strip()
        if not label:
            continue
        # Gmail's own labels arrive as \\Inbox, \\Sent, \\Important …
        pretty = label.lstrip("\\").replace("\\\\", "\\")
        if pretty:
            out.append(pretty)
    return out


def _build_msg_dict(msg, flags, thread_id, uid, account_email, folder, meta_s,
                    body_loaded=True):
    subject = _dh(msg.get("Subject")) or "(no subject)"
    from_name_raw, from_addr = parseaddr(msg.get("From", ""))
    from_name = _dh(from_name_raw) or from_addr
    try:
        dt = parsedate_to_datetime(msg.get("Date"))
    except Exception:
        dt = None
    date_disp, sortkey = _fmt_date(dt)
    # Machine-readable timestamp of the EMAIL itself (local tz, ISO). Used by
    # the planned attachment auto-save {YYYY-MM} prefix token and any future
    # exact-date logic — keep separate from the human "date" display string.
    try:
        dt_iso = dt.astimezone().isoformat() if dt else ""
    except Exception:
        dt_iso = ""
    # The same instant on the SENDER's clock, their UTC offset intact. _dt above
    # has already been converted to your time zone, which throws that away — and
    # "it says 07:12 but he wrote it at 01:12 his time" is exactly the kind of
    # thing you go looking for the exact time FOR (Issu 2026-08-29).
    try:
        dt_orig = dt.isoformat() if dt else ""
    except Exception:
        dt_orig = ""
    body, attachments, attach_data, body_html, ics_text = \
        _extract_body_and_attachments(msg)

    flagset = set()
    for f in (flags or ()):
        flagset.add(f.decode().lower() if isinstance(f, bytes) else str(f).lower())
    unread  = "\\seen" not in flagset
    starred = "\\flagged" in flagset

    prio = "normal"
    xp  = (msg.get("X-Priority") or "").strip()
    imp = (msg.get("Importance") or "").strip().lower()
    if xp[:1] in ("1", "2") or imp == "high":
        prio = "high"
    elif xp[:1] in ("4", "5") or imp == "low":
        prio = "low"

    return {
        "id":            uid or str(id(msg)),
        "uid":           uid,
        "thread_id":     thread_id or uid or str(id(msg)),
        "account_email": account_email,
        "from":          from_addr,
        "from_name":     from_name,
        "subject":       subject,
        "date":          date_disp,
        "_sortkey":      sortkey,
        "_dt":           dt_iso,
        "_dt_orig":      dt_orig,
        "body":          body,
        # False for a message whose full body/attachments have not been
        # downloaded yet — only its headers have (see _fetch_folder_cached's
        # headers-only path and _ensure_full_body). Everything above this
        # line is real; body/attachments/_html below are empty placeholders
        # until the real content is fetched, which happens automatically the
        # moment the message is opened (Issu 2026-08-06: folder-switching
        # took 20-40s because every not-yet-cached message in the window —
        # attachments included — downloaded in full before anything showed).
        "_body_loaded":  body_loaded,
        "unread":        unread,
        "starred":       starred,
        "priority":      prio,
        "spam":          (folder == "Spam"),
        "attachments":   attachments,
        "_attachment_data": attach_data,
        "_html":         body_html,
        "_folder":       folder,
        # ── Headers kept for the phishing scan and the unsubscribe dialog ─────
        # (DEL 04e). They are cheap to carry and impossible to recover later
        # without re-fetching the whole message from the server.
        "_to_hdr":       _dh(msg.get("To")),
        "_cc_hdr":       _dh(msg.get("Cc")),
        "_reply_to_hdr": _dh(msg.get("Reply-To")),
        "_references_hdr": _dh(msg.get("References")),
        "_list_unsub":   (msg.get("List-Unsubscribe") or ""),
        # RFC 8058 one-click. When a sender ships this alongside an https
        # List-Unsubscribe URL, ONE POST to that URL unsubscribes you — no
        # page, no browser, no "click here to confirm". It is the sender
        # promising, in a standard header, that the URL needs no human at the
        # other end (Issu 2026-08-29: "ju smidigare desto bättre").
        "_list_unsub_post": (msg.get("List-Unsubscribe-Post") or ""),
        "_auth_results": (msg.get("Authentication-Results") or ""),
        "_message_id":   (msg.get("Message-ID") or ""),
        # DEL 09p — "✉🔒 Send and save". The protection mark travels WITH the
        # message, so the Sent copy is self-identifying: still protected on a
        # machine that has never seen protected.json, and still protected
        # after a rule has moved it somewhere else. See _is_protected_msg.
        "_protected_hdr": (msg.get(_PROTECT_HEADER) or ""),
        "_ics":          ics_text,
        # Every Gmail label this message carries — needed so a delete can say
        # exactly where it would disappear from (DEL 04i).
        "_labels":       _parse_gm_labels(meta_s),
    }


def _parse_fetch(fetched, account_email, folder):
    results = []
    for item in fetched:
        if not isinstance(item, tuple):
            continue
        meta = item[0] or b""
        raw  = item[1] or b""
        meta_s = meta.decode("utf-8", "replace")
        thr  = _re.search(r"X-GM-THRID\s+(\d+)", meta_s)
        uidm = _re.search(r"UID\s+(\d+)", meta_s)
        try:
            flags = imaplib.ParseFlags(meta)
        except Exception:
            flags = ()
        try:
            msg = _email.message_from_bytes(raw)
        except Exception as e:
            log.warning("Could not parse a message: %s", e)
            continue
        built = _build_msg_dict(
            msg, flags,
            thr.group(1) if thr else None,
            uidm.group(1) if uidm else None,
            account_email, folder, meta_s)
        # Keep the ORIGINAL bytes. The local archive (DEL 04h) writes these
        # untouched, so an archived message is byte-for-byte what the server
        # sent — every header, signature and encoding intact. Rebuilding an
        # .eml from the parsed dict would quietly lose most of that.
        built["_raw"] = raw
        results.append(built)
    return results


def _fetch_folder(email_addr, password, folder, limit=FETCH_LIMIT,
                  interactive=False):
    """Connect, fetch the most-recent `limit` messages of one folder, logout.

    READ-ONLY: select(readonly=True) + BODY.PEEK[] — nothing on the server
    is changed. Raises on connection/login failure (caller handles)."""
    lane = "ui" if interactive else "bg"
    if interactive:
        _ui_wait_begin()
    _fetch_wait_begin()          # the read-ahead stands aside — see _FETCH_WAITING
    imap = _imap_acquire(email_addr, password, lane=lane)
    broken = False
    try:
        mapping = _discover_mailboxes(imap)
        mailbox = mapping.get(folder, folder)
        typ, _ = imap.select(f'"{mailbox}"', readonly=True)
        if typ != "OK":
            return []
        typ, data = imap.uid("SEARCH", None, "ALL")
        if typ != "OK" or not data or not data[0]:
            return []
        uids = data[0].split()[-limit:]
        if not uids:
            return []
        uid_set = ",".join(u.decode() for u in uids)
        typ, fetched = imap.uid(
            "FETCH", uid_set,
            "(UID FLAGS X-GM-THRID X-GM-LABELS BODY.PEEK[])")
        if typ != "OK":
            return []
        msgs = _parse_fetch(fetched, email_addr, folder)
        msgs.sort(key=lambda m: m.get("_sortkey", 0.0), reverse=True)
        return msgs
    except Exception:
        broken = True
        raise
    finally:
        _imap_release(email_addr, imap, broken, lane=lane)
        _fetch_wait_end()
        if interactive:
            _ui_wait_end()


# ******************************************************************************
# DEL 04c-CACHE — LOCAL MESSAGE CACHE  (Thunderbird-style offline copy)
# ******************************************************************************
#
# WHY: the plain _fetch_folder() re-downloads the full body of the newest N
# messages on EVERY refresh — a fresh IMAP login plus BODY.PEEK[] for mail we
# already have. That is what makes updating an inbox feel slow.
#
# WHAT: we keep the raw .eml of each message on disk, exactly once, under
#   Helpfiles/Cache/<account>/<folder>/<uid>.eml
# plus an index.json holding UIDVALIDITY + per-UID {thrid, meta, flags}. A
# refresh then:
#   1. asks the server for the UID list (cheap — no bodies),
#   2. downloads bodies ONLY for UIDs we do not already have on disk,
#   3. re-syncs FLAGS/labels for the visible window (cheap — no bodies),
#   4. drops anything the server no longer has (deleted mail),
# and rebuilds the message dicts from the cached bytes. READ-ONLY throughout:
# select(readonly=True) + BODY.PEEK[], so nothing on Gmail is ever changed.
#
# If UIDVALIDITY changes (Gmail rebuilt the mailbox) the folder cache is wiped
# and refilled from scratch. Any error at all falls back to a full fetch, so
# the cache can never leave you unable to read mail.

_CACHE_DIR = os.path.join(_FM_DIR, "Cache")

# One lock per (account, folder) so a manual Refresh and a background
# auto-check of the same inbox cannot corrupt the same index.json / .eml set.
_CACHE_LOCKS = {}
_CACHE_LOCKS_GUARD = threading.Lock()


def _cache_lock(email_addr, folder):
    key = (email_addr, folder)
    with _CACHE_LOCKS_GUARD:
        lk = _CACHE_LOCKS.get(key)
        if lk is None:
            lk = threading.Lock()
            _CACHE_LOCKS[key] = lk
        return lk


def _cache_folder_dir(email_addr, folder):
    d = os.path.join(_CACHE_DIR, _safe_name(email_addr), _safe_name(folder))
    os.makedirs(d, exist_ok=True)
    return d


# ── THE FOLDER LIST IS REMEMBERED BETWEEN RUNS (Issu 2026-08-19) ──────────────
#
# "Det tog kanske 60-90 sekunder, innan inbox-underkataloger existerade. Varför
# så lång tid? Varför finns de inte direkt?"
#
# Because nothing was ever written down. `self._user_folders` started every run
# as an empty dict, so the sidebar could not show one single label until a LIST
# came back over the network — and that LIST was behind a fresh TLS handshake
# and LOGIN per account, run one account after another, with a flaky account
# (Loss.THN) able to spend the full 30-second socket timeout in front of the
# rest.
#
# Your folder names change perhaps twice a month. There is no reason at all to
# ask the server before showing them. This is the same promise the MESSAGE list
# has made since 2026-08-06 — draw what is on disk at once, then quietly correct
# it — finally extended to the sidebar.
def _folderlist_cache_path(email_addr):
    return os.path.join(_CACHE_DIR, _safe_name(email_addr), "folders.json")


def _folderlist_cache_load(email_addr):
    """The folder list as it was at the end of the last run, or [] if there is
    none yet. Never raises: a missing or damaged file just means "ask the
    server", which is exactly what used to happen every time anyway."""
    try:
        with open(_folderlist_cache_path(email_addr), "r",
                  encoding="utf-8") as f:
            data = json.load(f)
        if isinstance(data, dict):
            data = data.get("folders")
        if isinstance(data, list) and all(isinstance(x, dict) for x in data):
            return data
    except Exception:
        pass
    return []


def _folderlist_cache_save(email_addr, folders):
    """Write the folder list for next time. Only ever called with a real answer
    from the server — a failed LIST returns [] and must NOT be allowed to erase
    a perfectly good list, or one bad start-up would cost you the sidebar on
    the next one too."""
    if not folders:
        return
    try:
        d = os.path.join(_CACHE_DIR, _safe_name(email_addr))
        os.makedirs(d, exist_ok=True)
        with open(_folderlist_cache_path(email_addr), "w",
                  encoding="utf-8") as f:
            json.dump({"saved": datetime.now().isoformat(timespec="seconds"),
                       "folders": folders}, f)
    except Exception as e:
        log.debug("Could not write the folder list for %s: %s", email_addr, e)


def _cache_index_path(email_addr, folder):
    return os.path.join(_cache_folder_dir(email_addr, folder), "index.json")


def _cache_load_index(email_addr, folder):
    try:
        with open(_cache_index_path(email_addr, folder), "r",
                  encoding="utf-8") as f:
            idx = json.load(f)
        if isinstance(idx, dict) and isinstance(idx.get("uids"), dict):
            return idx
    except Exception:
        pass
    return {"uidvalidity": None, "uids": {}}


def _cache_save_index(email_addr, folder, idx):
    try:
        with open(_cache_index_path(email_addr, folder), "w",
                  encoding="utf-8") as f:
            json.dump(idx, f)
    except Exception as e:
        log.debug("Could not write cache index for %s/%s: %s",
                  email_addr, folder, e)


def _cache_clear_folder(email_addr, folder):
    try:
        shutil.rmtree(os.path.join(_CACHE_DIR, _safe_name(email_addr),
                                   _safe_name(folder)), ignore_errors=True)
    except Exception:
        pass


def _cache_clear_all():
    """Wipe the whole on-disk cache (Tools → Auto-check → Clear cache)."""
    try:
        shutil.rmtree(_CACHE_DIR, ignore_errors=True)
    except Exception:
        pass


def _cache_size_bytes():
    """Total bytes the cache currently occupies (for the settings dialog)."""
    total = 0
    for root_dir, _dirs, files in os.walk(_CACHE_DIR):
        for name in files:
            try:
                total += os.path.getsize(os.path.join(root_dir, name))
            except OSError:
                pass
    return total


def _flags_from_meta(metab):
    """Return a list of flag strings from one raw FETCH response line."""
    try:
        raw = metab if isinstance(metab, (bytes, bytearray)) else str(metab).encode()
        return [f.decode() if isinstance(f, bytes) else str(f)
                for f in imaplib.ParseFlags(raw)]
    except Exception:
        return []


# The smallest a real .eml can plausibly be. Anything under this is a failed
# write, not a message — see _cached_body_ok.
_MIN_EML_BYTES = 40


def _cached_body_ok(path: str) -> bool:
    """Is there a USABLE cached message at `path`?

    Merely existing is not enough. A `<uid>.eml` of ZERO bytes was found in
    Issu's own cache (BGGGeekmarket/Trash/2641.eml) — a write that failed or
    was cut short. Every other test in this file asks only `os.path.isfile()`,
    so that empty file counted as "fully cached" for ever: the message showed
    as a permanently blank row, and nothing would ever fetch it again because
    the cache insisted it already had it.

    Treating a too-small file as NOT cached makes the folder heal itself on
    the next refresh instead of carrying a dead row indefinitely."""
    try:
        return os.path.getsize(path) >= _MIN_EML_BYTES
    except OSError:
        return False


# ── Is this raw message HEADERS ONLY? (Issu 2026-08-16) ───────────────────────
#
# The single most damaging bug this program has had. _fetch_folder_cached
# lists a folder by fetching BODY.PEEK[HEADER] for messages it has never seen,
# and stores those header bytes in msg["_raw"] as a stand-in until the body is
# really needed. That is fine for showing a list — but a CROSS-ACCOUNT filter
# move read that same msg["_raw"] and uploaded it to the other account, then
# trashed the original. The result is exactly what Issu found in
# 0---Frakt & Kvitto: 4–5 KB messages, one part, ZERO body — the receipt is
# gone and only its envelope survives.
#
# So: before any APPEND, the bytes are checked here. No body → not good enough
# to deliver, and the source is never trashed on the strength of it.
def _raw_is_headers_only(raw) -> bool:
    """True when these bytes carry headers but no message body at all.

    Deliberately byte-level and format-agnostic: it looks for the blank line
    that ends the header block (CRLFCRLF or LFLF) and asks whether anything
    of substance follows. A MIME multipart whose first boundary line is
    present counts as having a body; a header block that simply stops does
    not. Empty/None counts as headers-only — there is nothing to deliver."""
    if not raw:
        return True
    if isinstance(raw, str):
        raw = raw.encode("utf-8", "replace")
    for sep in (b"\r\n\r\n", b"\n\n"):
        i = raw.find(sep)
        if i >= 0:
            return len(raw[i + len(sep):].strip()) < 8
    return True          # no blank line at all — the whole thing is a header


def _fetch_folder_cached(email_addr, password, folder, limit=FETCH_LIMIT,
                         interactive=False):
    """READ-ONLY fetch that reuses the local disk cache (see section header).

    Returns the same list-of-dicts shape as _fetch_folder(). Raises on any
    trouble so the caller can fall back to a full fetch.

    ── THE LOCK IS NOT HELD OVER THE WIRE (Issu 2026-08-19) ──────────────────
    This used to run the WHOLE function inside _cache_lock(account, folder) —
    network round trips and all. _fetch_single_full_body had already been
    fixed for exactly that on 2026-08-08 ("the per-folder cache lock is no
    longer held across the NETWORK round-trip"), but its sibling here never
    was, and that is what turned one slow round into a permanent backlog:

      • the auto-check for issusbarn@gmail.com/Inbox takes the lock,
      • it runs long and the 25-second round deadline abandons the WAIT —
        but not the WORK, so the thread keeps the lock,
      • the next minute's check blocks on that lock, runs out of time too,
        and hands the same problem to the one after it.

    His log for 2026-08-19 has 34 abandoned fetches in a row for that one
    account between 05:35 and 06:18. Two Tradera receipts booked at 06:05 did
    not appear until he restarted — the mail was in Gmail the whole time; the
    program never got a turn to ask for it.

    So the work is now split in two, strictly:
      • NETWORK — SELECT, SEARCH, the header FETCH and the flag FETCH — runs
        with NO cache lock held at all;
      • DISK — reading the index, pruning deleted mail, writing .hdr files,
        rebuilding from cached bytes and saving the index — runs inside short
        locked sections that touch nothing but the hard drive.

    The index is RE-READ inside the final locked section and merged rather
    than overwritten, so two fetches of the same folder overlapping can no
    longer lose each other's entries — which is the one thing the long lock
    was really buying."""
    lane = "ui" if interactive else "bg"
    if interactive:
        _ui_wait_begin()
    # A real fetch outranks the read-ahead: _prefetch_bodies pauses between
    # messages while this is set, so twelve receipt bodies can no longer sit
    # in front of the check that would have found the new mail.
    _fetch_wait_begin()
    imap = _imap_acquire(email_addr, password, lane=lane)
    broken = False
    try:
        mapping = _discover_mailboxes(imap)
        mailbox = mapping.get(folder, folder)
        typ, _ = imap.select(f'"{mailbox}"', readonly=True)
        if typ != "OK":
            return []

        # UIDVALIDITY — if the server reset it, the cached UIDs are lies.
        uidvalidity = None
        try:
            typ_s, data_s = imap.status(f'"{mailbox}"', "(UIDVALIDITY)")
            if typ_s == "OK" and data_s and data_s[0]:
                mm = _re.search(rb"UIDVALIDITY\s+(\d+)", data_s[0])
                if mm:
                    uidvalidity = mm.group(1).decode()
        except Exception:
            uidvalidity = None

        # ── DISK: read the index (lock held for milliseconds) ───────────────
        with _cache_lock(email_addr, folder):
            idx = _cache_load_index(email_addr, folder)
            if uidvalidity is not None and idx.get("uidvalidity") != uidvalidity:
                _cache_clear_folder(email_addr, folder)
                idx = {"uidvalidity": uidvalidity, "uids": {}}

        # ── NETWORK: what does the server have? (no lock held) ──────────────
        typ, data = imap.uid("SEARCH", None, "ALL")
        if typ != "OK":
            return []
        all_uids = data[0].split() if (data and data[0]) else []
        all_uids_s = [u.decode() for u in all_uids]
        window = all_uids_s[-limit:]           # newest `limit` shown
        server_set = set(all_uids_s)

        cache_dir = _cache_folder_dir(email_addr, folder)
        stored = idx.get("uids", {})

        # ── DISK: which of the window do we not have a body for? ────────────
        # _cached_body_ok, not isfile: a zero-byte .eml is a failed write, and
        # treating it as cached is what makes a blank row permanent.
        with _cache_lock(email_addr, folder):
            need = [u for u in window
                    if not _cached_body_ok(os.path.join(cache_dir, u + ".eml"))]

        # ── NETWORK: for those, fetch HEADERS ONLY (no lock held) ───────────
        # Fast, no attachment bytes, so the list shows Subject/From/Date right
        # away. The full body (and attachments) is fetched lazily the instant
        # you actually open the message (_ensure_full_body) and gets written to
        # the normal on-disk cache then, so opening it again later is just as
        # instant as any other cached message. Downloading every uncached
        # message IN FULL up front — the old behaviour — is what made opening
        # an unfamiliar or attachment-heavy folder take 20-40 seconds
        # (Issu 2026-08-06).
        hdr_bytes  = {}   # uid -> raw header bytes, written to disk below
        stub_built = {}   # uid -> built dict, header-only for now
        if need:
            typ, fetched = imap.uid(
                "FETCH", ",".join(need),
                "(UID FLAGS X-GM-THRID X-GM-LABELS BODY.PEEK[HEADER])")
            if typ == "OK":
                for item in fetched:
                    if not isinstance(item, tuple):
                        continue
                    meta    = item[0] or b""
                    hdr_raw = item[1] or b""
                    meta_s = meta.decode("utf-8", "replace")
                    um = _re.search(r"UID\s+(\d+)", meta_s)
                    if not um:
                        continue
                    uid = um.group(1)
                    thr = _re.search(r"X-GM-THRID\s+(\d+)", meta_s)
                    flags_here = _flags_from_meta(meta)
                    # Deliberately NOT written to <uid>.eml — that filename
                    # means "fully cached" everywhere else in this function,
                    # and a header-only fetch is not that yet.
                    #
                    # It IS written to <uid>.hdr though (Issu 2026-08-08).
                    # Without that, a folder whose bodies were never downloaded
                    # — his Trash and Spam hold index entries and not one .eml
                    # — had nothing at all to show from disk, so opening it
                    # went blank and announced "no messages" until the server
                    # answered. Headers are a couple of KB each and give a
                    # complete, correct list instantly; the bodies then fill in
                    # behind it exactly as before.
                    #
                    # The bytes are kept in memory here and written in the
                    # locked disk section below, so this loop stays pure
                    # network + CPU.
                    stored[uid] = {
                        "thrid": thr.group(1) if thr else "",
                        "meta":  meta_s,
                        "flags": flags_here,
                    }
                    hdr_bytes[uid] = hdr_raw
                    try:
                        hdr_msg = _email.message_from_bytes(hdr_raw)
                        built = _build_msg_dict(
                            hdr_msg, flags_here, thr.group(1) if thr else None,
                            uid, email_addr, folder, meta_s,
                            body_loaded=False)
                        built["_raw"] = hdr_raw
                        stub_built[uid] = built
                    except Exception as e:
                        log.debug("Header-only parse failed %s: %s", uid, e)

        # ── NETWORK: re-sync FLAGS + labels for the visible window ──────────
        if window:
            typ, fl = imap.uid("FETCH", ",".join(window),
                               "(UID FLAGS X-GM-LABELS X-GM-THRID)")
            if typ == "OK":
                for item in fl:
                    metab = item[0] if isinstance(item, tuple) else item
                    if not metab:
                        continue
                    meta_s = (metab.decode("utf-8", "replace")
                              if isinstance(metab, (bytes, bytearray))
                              else str(metab))
                    um = _re.search(r"UID\s+(\d+)", meta_s)
                    if not um:
                        continue
                    uid = um.group(1)
                    ent = stored.get(uid)
                    if not ent:
                        continue
                    ent["flags"] = _flags_from_meta(metab)
                    ent["meta"]  = meta_s      # carries fresh X-GM-LABELS
                    # A header-only stub's unread/starred were computed from
                    # the header fetch's flags — refresh them too, so a read
                    # state changed elsewhere (another client, another window)
                    # is not stale here.
                    b = stub_built.get(uid)
                    if b is not None:
                        fl_lower = {f.lower() for f in ent["flags"]}
                        b["unread"]  = "\\seen" not in fl_lower
                        b["starred"] = "\\flagged" in fl_lower

        # ── DISK: prune, write headers, rebuild, save (lock held, no wire) ──
        results = []
        with _cache_lock(email_addr, folder):
            # Re-read and MERGE rather than overwrite: another fetch of this
            # same folder may have finished while we were on the wire, and its
            # entries must survive ours. Ours win where both have a uid —
            # they are the fresher flags.
            disk   = _cache_load_index(email_addr, folder)
            merged = dict(disk.get("uids", {}))
            merged.update(stored)

            # Whatever the server no longer has is deleted mail. Done after
            # the merge so a stale entry re-read from disk cannot come back.
            for uid in list(merged.keys()):
                if uid not in server_set:
                    for ext in (".eml", ".hdr"):
                        try:
                            os.remove(os.path.join(cache_dir, uid + ext))
                        except OSError:
                            pass
                    merged.pop(uid, None)

            for uid, hdr_raw in hdr_bytes.items():
                try:
                    with open(os.path.join(cache_dir, uid + ".hdr"), "wb") as hf:
                        hf.write(hdr_raw)
                except OSError as e:
                    log.debug("Header cache write failed %s: %s", uid, e)

            # Rebuild message dicts from cached bytes + fresh flags — except
            # header-only UIDs, which just use the stub built above.
            for uid in window:
                if uid in stub_built:
                    results.append(stub_built[uid])
                    continue
                ent  = merged.get(uid)
                path = os.path.join(cache_dir, uid + ".eml")
                if not ent or not _cached_body_ok(path):
                    # A truncated/zero-byte cache file is thrown away so the
                    # next refresh downloads the message properly, instead of
                    # leaving a blank row that can never repair itself.
                    if ent and os.path.isfile(path):
                        try:
                            size = os.path.getsize(path)
                            os.remove(path)
                            log.info("Discarded an unusable cache file "
                                     "(%s bytes) for %s/%s uid %s — it will be "
                                     "fetched again",
                                     size, email_addr, folder, uid)
                        except OSError:
                            pass
                    continue
                try:
                    with open(path, "rb") as f:
                        raw = f.read()
                    msg = _email.message_from_bytes(raw)
                except Exception:
                    continue
                built = _build_msg_dict(
                    msg, ent.get("flags", []),
                    ent.get("thrid") or None, uid,
                    email_addr, folder, ent.get("meta", ""))
                built["_raw"] = raw
                results.append(built)

            disk["uids"] = merged
            if uidvalidity is not None:
                disk["uidvalidity"] = uidvalidity
            _cache_save_index(email_addr, folder, disk)

        results.sort(key=lambda m: m.get("_sortkey", 0.0), reverse=True)
        return results
    except Exception:
        broken = True
        raise
    finally:
        _imap_release(email_addr, imap, broken, lane=lane)
        _fetch_wait_end()
        if interactive:
            _ui_wait_end()


def _fetch_folder_smart(email_addr, password, folder,
                        limit=FETCH_LIMIT, use_cache=True, interactive=False):
    """Cached fetch when enabled, with a hard fall back to the full fetch so a
    cache problem can never stop mail from loading.

    interactive=True when YOU clicked the folder and are watching it open. That
    puts the fetch on the "ui" lane, so it does not queue behind the auto-check
    and the read-ahead (Issu 2026-08-08: "går till Spam … det är fortfarande
    loading nu")."""
    if use_cache:
        try:
            msgs = _fetch_folder_cached(email_addr, password, folder, limit,
                                        interactive=interactive)
            _stall_clear(email_addr)
            return msgs
        except Exception as e:
            if _is_network_stall(e):
                # The cache was never the problem — the connection is. Trying
                # the FULL fetch now just spends another 30-second timeout on
                # the same dead socket, which is half of the minute the All
                # Accounts view sat on "updating…" (Issu 2026-08-17).
                _stall_note(email_addr)
                log.warning("Cached fetch for %s/%s stalled (%s) — not "
                            "retrying a full fetch over the same connection",
                            email_addr, folder, e)
                raise
            log.warning("Cached fetch failed for %s/%s — full fetch instead: %s",
                        email_addr, folder, e)
    try:
        msgs = _fetch_folder(email_addr, password, folder, limit,
                             interactive=interactive)
    except Exception as e:
        if _is_network_stall(e):
            _stall_note(email_addr)
        raise
    _stall_clear(email_addr)
    return msgs


def _fetch_single_full_body(email_addr, password, folder, uid,
                            interactive=True):
    """On-demand full fetch for the ONE message you just opened, whose body
    _fetch_folder_cached only fetched the headers for. Writes the normal
    on-disk .eml cache too, so opening it again later is exactly as instant
    as any other already-read message — this only ever runs once per
    message (Issu 2026-08-06).

    Returns a built message dict with _body_loaded=True, or None if the
    message could not be fetched (e.g. it was deleted server-side between
    listing the folder and opening it).

    TWO changes on 2026-08-08, both aimed at Issu's "loading… det tog nog
    cirka 30 sekunder":

      • it runs on the "ui" lane (lane=), so it does NOT queue behind the
        every-minute auto-check and the 21-mailbox unread-count pass;
      • the per-folder cache lock is no longer held across the NETWORK
        round-trip. It used to wrap the whole function, so opening a message
        while that folder happened to be refreshing meant waiting for the
        entire refresh first. The lock now guards only the few milliseconds
        of disk work at the end, which is all it was ever protecting.
    """
    lane = "ui" if interactive else "bg"
    if interactive:
        _ui_wait_begin()                # background loops stand aside
    imap = _imap_acquire(email_addr, password, lane=lane)
    broken = False
    try:
        mapping = _discover_mailboxes(imap)
        mailbox = mapping.get(folder, folder)
        typ, _ = imap.select(f'"{mailbox}"', readonly=True)
        if typ != "OK":
            return None
        typ, fetched = imap.uid(
            "FETCH", uid, "(UID FLAGS X-GM-THRID X-GM-LABELS BODY.PEEK[])")
        if typ != "OK" or not fetched:
            return None
        item = next((it for it in fetched if isinstance(it, tuple)), None)
        if item is None:
            return None
        meta = item[0] or b""
        raw  = item[1] or b""
        meta_s = meta.decode("utf-8", "replace")
        um = _re.search(r"UID\s+(\d+)", meta_s)
        real_uid = um.group(1) if um else uid
        thr = _re.search(r"X-GM-THRID\s+(\d+)", meta_s)
        flags_here = _flags_from_meta(meta)

        # ── Only THIS part needs the folder lock (disk, not network) ────────
        with _cache_lock(email_addr, folder):
            cache_dir = _cache_folder_dir(email_addr, folder)
            try:
                with open(os.path.join(cache_dir, real_uid + ".eml"), "wb") as f:
                    f.write(raw)
                # The header-only stand-in has done its job.
                try:
                    os.remove(os.path.join(cache_dir, real_uid + ".hdr"))
                except OSError:
                    pass
            except OSError as e:
                log.debug("Cache write failed %s: %s", real_uid, e)

            idx = _cache_load_index(email_addr, folder)
            idx.setdefault("uids", {})[real_uid] = {
                "thrid": thr.group(1) if thr else "",
                "meta":  meta_s,
                "flags": flags_here,
            }
            _cache_save_index(email_addr, folder, idx)

        msgobj = _email.message_from_bytes(raw)
        built = _build_msg_dict(
            msgobj, flags_here, thr.group(1) if thr else None,
            real_uid, email_addr, folder, meta_s, body_loaded=True)
        built["_raw"] = raw
        return built
    except Exception:
        broken = True
        raise
    finally:
        _imap_release(email_addr, imap, broken, lane=lane)
        if interactive:
            _ui_wait_end()


def _prefetch_bodies(email_addr, password, folder, uids, stop=None):
    """Quietly download the FULL bodies of messages whose headers we already
    have, so opening one is a local read with nothing to wait for.

    This is Issu's own suggestion, 2026-08-08: "kan inte programmet jobba med
    nya saker i bakgrunden, och läsa in lokalt?" — yes, and this is it. After
    a folder list arrives, the newest messages that are not yet on disk are
    fetched one at a time on the BACKGROUND lane, so by the time he clicks the
    new mail its body is already there.

    Deliberately unhurried and interruptible:
      • one message per round trip, never a big batch that hogs the wire;
      • `_background_yield(for_fetch=True)` before each one, so a click AND a
        folder fetch both go first — reading ahead only ever saves a wait
        later, while the check it was blocking is how new mail is found at all
        (Issu 2026-08-19; see _FETCH_WAITING for the morning it cost him);
      • `stop` (a callable returning True) aborts it — the app sets that when
        you change folder, so it never fetches things you have walked away
        from;
      • every failure is ignored. A prefetch that does not happen costs a
        wait later; it must never produce an error in front of the user.

    Returns how many bodies were fetched."""
    done = 0
    for uid in uids:
        if stop is not None and stop():
            break
        _background_yield(for_fetch=True)
        try:
            if _fetch_single_full_body(email_addr, password, folder, uid,
                                       interactive=False) is not None:
                done += 1
        except Exception as e:
            log.debug("prefetch %s/%s uid %s: %s", email_addr, folder, uid, e)
        # A short breather between messages keeps the account quiet — Gmail
        # throttles a connection that fetches flat out, and there is no hurry.
        time.sleep(0.15)
    if done:
        log.info("Prefetched %d message body/bodies for %s/%s — those open "
                 "instantly now", done, email_addr, folder)
    return done


def _locate_message(email_addr, password, message_id, folders=None,
                    interactive=True):
    """EVERY place this message exists in one account — not just the first.

    The sibling of _find_message_anywhere, which stops at the first hit because
    it only wants somewhere to fetch the body from. This one keeps looking,
    because the question it answers is Issu's most frequent one: "var ligger
    det här mailet?" — and on Gmail the honest answer is usually "in several
    places at once", since a message wears labels rather than living in a
    folder.

    Returns [{"folder", "uid", "labels"}], newest-looking first. READ-ONLY."""
    mid = _hdr_safe(message_id or "")
    if not mid:
        return []
    bare = mid.strip("<>")
    lane = "ui" if interactive else "bg"
    if interactive:
        _ui_wait_begin()
    found = []
    imap = _imap_acquire(email_addr, password, lane=lane)
    broken = False
    try:
        mapping = _discover_mailboxes(imap)
        if folders is None:
            folders = ["Inbox", "Sent", "Drafts", "Starred", "Spam", "Trash",
                       "All Mail"]
        for logical in folders:
            mailbox = mapping.get(logical, logical)
            try:
                typ, _ = imap.select(_mb_arg(mailbox), readonly=True)
                if typ != "OK":
                    continue
                try:
                    typ, data = imap.uid("SEARCH", "X-GM-RAW",
                                         f"rfc822msgid:{bare}")
                except Exception:
                    typ, data = imap.uid("SEARCH", None, "HEADER",
                                         "Message-ID", f'"{mid}"')
                if typ != "OK" or not data or not data[0]:
                    continue
                for u in data[0].split():
                    uid = u.decode()
                    labels = []
                    try:
                        typ2, meta = imap.uid("FETCH", uid, "(X-GM-LABELS)")
                        if typ2 == "OK" and meta:
                            blob = meta[0]
                            if isinstance(blob, tuple):
                                blob = blob[0]
                            labels = _parse_gm_labels(
                                (blob or b"").decode("utf-8", "replace"))
                    except Exception:
                        pass
                    found.append({"folder": logical, "uid": uid,
                                  "labels": labels})
            except Exception as e:
                log.debug("locate: %s/%s failed: %s", email_addr, logical, e)
    except Exception:
        broken = True
        raise
    finally:
        _imap_release(email_addr, imap, broken, lane=lane)
        if interactive:
            _ui_wait_end()
    return found


def _imap_scan_for_duplicates(email_addr, password, folder,
                              include_subfolders=True):
    """Group every message under one folder (and, if asked, everything nested
    under it) of ONE account by Message-ID. READ-ONLY: only headers and the
    message SIZE are fetched (BODY.PEEK[HEADER.FIELDS (MESSAGE-ID SUBJECT
    DATE)] + RFC822.SIZE — the size costs nothing extra, IMAP already knows
    it), nothing on the server is touched.

    Issu 2026-08-15: "kan du se om jag har massvis med dubletter?" — this is
    what actually answers that, by asking the real mailbox, rather than
    guessing from the activity log (which was never a folder inventory and
    does not record Message-ID at all).

    Size matters because Issu then noticed the real hazard: "vissa av dem
    får aldrig något meddelande (body)" — a message with an empty or
    near-empty body, same Message-ID as a real one. That is very likely a
    copy the OLD cross-account move made while the source's cached copy on
    the other account was still a header-only stub (body not fetched yet) —
    fixed on 2026-08-15, but it already had time to create these. The size
    is what lets the caller (see _find_duplicates_dialog's _pick_keep) tell
    a genuine copy from a stub, instead of guessing from folder depth alone,
    which knows nothing about whether either copy is actually intact.

    Returns {message_id: [{"folder", "uid", "subject", "date", "size"}, …]}
    for EVERY message seen — the caller decides what counts as a duplicate
    (normally: any group with more than one entry)."""
    groups: dict = {}
    imap = _imap_connect(email_addr, password)
    try:
        mapping = _discover_mailboxes(imap)
        target = mapping.get(folder, folder)
        folders_to_scan = [target]
        if include_subfolders:
            try:
                typ, data = imap.list('""', _mb_arg(target + "*"))
                if typ == "OK":
                    for raw in data or []:
                        if not raw:
                            continue
                        if isinstance(raw, tuple):
                            raw = raw[0]
                        if isinstance(raw, str):
                            raw = raw.encode("utf-8", "replace")
                        m = _LIST_RE.match(raw)
                        if not m:
                            continue
                        name = m.group("name")
                        if name.startswith(b'"'):
                            name = name[1:-1]
                        name_str = name.decode("utf-8", "replace")
                        if name_str not in folders_to_scan:
                            folders_to_scan.append(name_str)
            except Exception as e:
                log.warning("Duplicate scan: could not list subfolders of "
                           "%s: %s", target, e)
        for mailbox in folders_to_scan:
            try:
                typ, _sel = imap.select(_mb_arg(mailbox), readonly=True)
                if typ != "OK":
                    continue
                typ, data = imap.uid("SEARCH", None, "ALL")
                if typ != "OK" or not data or not data[0]:
                    continue
                uids = data[0].split()
                if not uids:
                    continue
                uid_set = ",".join(u.decode() for u in uids)
                typ, fetched = imap.uid(
                    "FETCH", uid_set,
                    "(UID RFC822.SIZE "
                    "BODY.PEEK[HEADER.FIELDS (MESSAGE-ID SUBJECT DATE)])")
                if typ != "OK":
                    continue
                for item in fetched:
                    if not isinstance(item, tuple) or len(item) < 2:
                        continue
                    meta, raw_hdr = item[0], item[1]
                    um = _re.search(rb"UID (\d+)", meta or b"")
                    uid = um.group(1).decode() if um else ""
                    sm = _re.search(rb"RFC822\.SIZE (\d+)", meta or b"")
                    size = int(sm.group(1)) if sm else 0
                    try:
                        hdr = _email.message_from_bytes(raw_hdr)
                    except Exception:
                        continue
                    mid = _re.sub(r"\s+", "",
                                 hdr.get("Message-ID", "") or "")
                    if not mid:
                        continue
                    subj = _dh(hdr.get("Subject", "") or "")
                    date = hdr.get("Date", "") or ""
                    groups.setdefault(mid, []).append(
                        {"folder": mailbox, "uid": uid, "subject": subj,
                         "date": date, "size": size})
            except Exception as e:
                log.warning("Duplicate scan failed in %s/%s: %s",
                           email_addr, mailbox, e)
    finally:
        try:
            imap.logout()
        except Exception:
            pass
    return groups


def _pick_duplicate_to_keep(hits):
    """Which copy of a duplicate group (from _imap_scan_for_duplicates) to
    KEEP. Content wins over position: a copy whose size is under half the
    largest one in the group is almost certainly a header-only stub — see
    _imap_scan_for_duplicates's docstring — and is never chosen just because
    it happens to sit in a "deeper" folder; Issu was right to be wary of
    exactly that. Among the reasonably-sized copies, a modern YYYY-MM month
    folder is preferred over an old two-digit one (the month-folder naming
    changed at some point, leaving an old- and new-style folder both holding
    the same mail), and otherwise the deepest folder wins — that is where
    filing actually put it on purpose."""
    sizes = [h.get("size") or 0 for h in hits]
    max_size = max(sizes) if sizes else 0
    real = [h for h in hits
           if (h.get("size") or 0) >= max_size * 0.5] or list(hits)
    def _key(h):
        modern = bool(_re.search(r"/\d{4}-\d{2}$", h["folder"]))
        return (modern, h["folder"].count("/"))
    return sorted(real, key=_key, reverse=True)[0]


# ==============================================================================
# DEL 04c-EMPTY — FIND (AND REPAIR) MAIL THAT ARRIVED WITHOUT ITS BODY
# ==============================================================================
#
# Issu 2026-08-16: "en del av dem verkar tappa sitt body-innehåll."
#
# He is right, and the copies are real — 0---Frakt & Kvitto/2026-08 alone holds
# eleven of them. They were made by the old cross-account move, which uploaded
# msg["_raw"] without ever asking whether those bytes were the whole message or
# just the header block a folder listing had fetched. That hole is closed (see
# _raw_is_headers_only and _deliver_cross_account), but closing it does nothing
# for the receipts already sitting on Gmail with nothing inside them.
#
# This is the other half: FIND them, and where the real message still exists
# somewhere — in another folder, or back in the account it was copied from —
# put the real one there and throw the empty one away. Read-only until the
# repair is confirmed, and nothing is ever erased: empties go to the Trash like
# every other delete in this program.


def _imap_scan_for_empty_bodies(email_addr, password, folder,
                                include_subfolders=True, progress=None):
    """Every message under one folder of one account, each marked as intact or
    EMPTY. READ-ONLY.

    "Empty" is not guessed from the size — a genuinely short receipt and a
    header-only stub are both about 4 KB. It is measured: the first 256 bytes
    of the message TEXT are fetched, and a message whose body part is
    literally empty is the stub. That is a definite answer, not a heuristic.

    Two FETCH commands rather than one on purpose. imaplib returns each literal
    as its own element, so a single FETCH asking for two literals per message
    (headers AND a slice of the text) comes back as a shape that has to be
    guessed at; two passes joined on UID cannot be misread.

    Returns [{"folder", "uid", "message_id", "subject", "date", "from",
              "size", "empty"}, …]."""
    out = []
    imap = _imap_connect(email_addr, password)
    try:
        mapping = _discover_mailboxes(imap)
        target = _resolve_mailbox(imap, folder, mapping) or folder
        boxes = [target]
        if include_subfolders:
            try:
                typ, data = imap.list('""', _mb_arg(target + "*"))
                if typ == "OK":
                    for raw in data or []:
                        if not raw:
                            continue
                        if isinstance(raw, tuple):
                            raw = raw[0]
                        if isinstance(raw, str):
                            raw = raw.encode("utf-8", "replace")
                        m = _LIST_RE.match(raw)
                        if not m:
                            continue
                        name = m.group("name")
                        if name.startswith(b'"'):
                            name = name[1:-1]
                        name_str = name.decode("utf-8", "replace")
                        if name_str not in boxes:
                            boxes.append(name_str)
            except Exception as e:
                log.warning("Empty-body scan: could not list sub-folders of "
                            "%s: %s", target, e)
        for mailbox in boxes:
            try:
                typ, _sel = imap.select(_mb_arg(mailbox), readonly=True)
                if typ != "OK":
                    continue
                typ, data = imap.uid("SEARCH", None, "ALL")
                if typ != "OK" or not data or not data[0]:
                    continue
                uids = [u.decode() for u in data[0].split()]
                if not uids:
                    continue
                if progress:
                    progress(f"Scanning {mailbox} — {len(uids)} message(s)…")
                for i in range(0, len(uids), 200):
                    chunk = uids[i:i + 200]
                    uid_s = ",".join(chunk)
                    # Pass 1 — headers and size.
                    info = {}
                    typ, fetched = imap.uid(
                        "FETCH", uid_s,
                        "(UID RFC822.SIZE BODY.PEEK[HEADER.FIELDS "
                        "(MESSAGE-ID SUBJECT DATE FROM)])")
                    if typ != "OK":
                        continue
                    for item in fetched:
                        if not isinstance(item, tuple) or len(item) < 2:
                            continue
                        meta, raw_hdr = item[0] or b"", item[1] or b""
                        um = _re.search(rb"UID (\d+)", meta)
                        if not um:
                            continue
                        uid = um.group(1).decode()
                        sm = _re.search(rb"RFC822\.SIZE (\d+)", meta)
                        try:
                            hdr = _email.message_from_bytes(raw_hdr)
                        except Exception:
                            continue
                        info[uid] = {
                            "folder": mailbox, "uid": uid,
                            "message_id": _re.sub(
                                r"\s+", "", hdr.get("Message-ID", "") or ""),
                            "subject": _dh(hdr.get("Subject", "") or ""),
                            "date": hdr.get("Date", "") or "",
                            "from": _dh(hdr.get("From", "") or ""),
                            "size": int(sm.group(1)) if sm else 0,
                            "empty": True,      # until proved otherwise below
                        }
                    # Pass 2 — is there anything in the body at all?
                    typ, fetched = imap.uid("FETCH", uid_s,
                                            "(UID BODY.PEEK[TEXT]<0.256>)")
                    if typ == "OK":
                        for item in fetched:
                            if not isinstance(item, tuple) or len(item) < 2:
                                continue
                            meta, body = item[0] or b"", item[1] or b""
                            um = _re.search(rb"UID (\d+)", meta)
                            if not um:
                                continue
                            rec = info.get(um.group(1).decode())
                            if rec is not None:
                                rec["empty"] = len(body.strip()) < 8
                    out.extend(info.values())
                    if progress:
                        progress(f"Scanning {mailbox} "
                                 f"({min(i + 200, len(uids))}/{len(uids)})…")
            except Exception as e:
                log.warning("Empty-body scan failed in %s/%s: %s",
                            email_addr, mailbox, e)
    finally:
        try:
            imap.logout()
        except Exception:
            pass
    return out


def _folder_has_intact_copy(email_addr, password, folder, message_id) -> bool:
    """Is there a copy of this Message-ID in this folder that actually HAS a
    body? READ-ONLY.

    The safety check the repair leans on. Gmail may quietly refuse to store a
    second message with a Message-ID the account already holds, and the empty
    copy being repaired holds exactly that ID — so an APPEND reporting OK is
    not proof that the real message is now there. Trashing the empty copy on
    the strength of an unverified OK is how a repair turns into a deletion.
    Nothing is removed unless this says yes."""
    mid = _hdr_safe(message_id or "")
    if not (mid and folder):
        return False
    imap = _imap_connect(email_addr, password)
    try:
        mapping = _discover_mailboxes(imap)
        mailbox = _resolve_mailbox(imap, folder, mapping) or folder
        typ, _ = imap.select(_mb_arg(mailbox), readonly=True)
        if typ != "OK":
            return False
        try:
            typ, data = imap.uid("SEARCH", "X-GM-RAW",
                                 f'rfc822msgid:{mid.strip("<>")}')
        except Exception:
            typ, data = imap.uid("SEARCH", None, "HEADER",
                                 "Message-ID", f'"{mid}"')
        if typ != "OK" or not data or not data[0]:
            return False
        for uid in data[0].split():
            typ, fetched = imap.uid("FETCH", uid.decode(),
                                    "(BODY.PEEK[TEXT]<0.256>)")
            if typ != "OK":
                continue
            item = next((it for it in fetched if isinstance(it, tuple)), None)
            if item and len((item[1] or b"").strip()) >= 8:
                return True
        return False
    except Exception as e:
        log.debug("Intact-copy check failed in %s/%s: %s",
                  email_addr, folder, e)
        return False
    finally:
        try:
            imap.logout()
        except Exception:
            pass


def _fetch_full_by_message_id(email_addr, password, message_id):
    """The COMPLETE bytes of a message, found anywhere in one account by its
    Message-ID. Returns (raw_bytes, where_found) or (b"", "").

    This is how an empty copy is repaired: the real message is very often
    still in the account the copy was made FROM (in its Trash, because the old
    cross-account move trashed the source after uploading the empty copy), and
    that original is intact. Read-only on the account it looks in."""
    mid = _hdr_safe(message_id or "")
    if not mid:
        return b"", ""
    imap = _imap_connect(email_addr, password)
    try:
        mapping = _discover_mailboxes(imap)
        for logical in ("All Mail", "Inbox", "Trash", "Spam"):
            mailbox = mapping.get(logical, logical)
            try:
                typ, _ = imap.select(_mb_arg(mailbox), readonly=True)
                if typ != "OK":
                    continue
                try:
                    typ, data = imap.uid("SEARCH", "X-GM-RAW",
                                         f'rfc822msgid:{mid.strip("<>")}')
                except Exception:
                    typ, data = imap.uid("SEARCH", None, "HEADER",
                                         "Message-ID", f'"{mid}"')
                if typ != "OK" or not data or not data[0]:
                    continue
                for uid in reversed(data[0].split()):
                    typ, fetched = imap.uid("FETCH", uid.decode(),
                                            "(BODY.PEEK[])")
                    if typ != "OK" or not fetched:
                        continue
                    item = next((it for it in fetched
                                 if isinstance(it, tuple)), None)
                    raw = (item[1] if item else b"") or b""
                    # The point of the whole exercise: only a message with a
                    # real body is worth carrying anywhere. Another empty copy
                    # is not a repair.
                    if raw and not _raw_is_headers_only(raw):
                        return raw, f"{email_addr} · {logical}"
            except Exception as e:
                log.debug("Full fetch by Message-ID failed in %s/%s: %s",
                          email_addr, logical, e)
        return b"", ""
    finally:
        try:
            imap.logout()
        except Exception:
            pass


def _imap_message_id_in_folder(email_addr, password, folder, message_id,
                               interactive=False) -> bool:
    """Does a message with this Message-ID already exist in this one folder
    of this one account? READ-ONLY. Used before a cross-account filter move
    appends a copy, so a message bouncing in and out of Trash on the source
    account (rescue_trash) can never pile up duplicate copies at the
    destination — see action_rescue_trash and _dispatch_filter_server_actions.

    On any error this returns False (assume "not there yet") rather than
    raising: a false negative costs at most one extra copy on a rare network
    hiccup, while a false positive would silently drop a delivery — the
    worse of the two failures for a shipping receipt Issu is waiting on."""
    mid = _hdr_safe(message_id or "")
    if not (mid and folder):
        return False
    lane = "ui" if interactive else "bg"
    if interactive:
        _ui_wait_begin()
    imap = None
    broken = False
    try:
        imap = _imap_acquire(email_addr, password, lane=lane)
        mapping = _discover_mailboxes(imap)
        mailbox = mapping.get(folder, folder)
        typ, _ = imap.select(_mb_arg(mailbox), readonly=True)
        if typ != "OK":
            return False
        try:
            typ, data = imap.uid("SEARCH", "X-GM-RAW",
                                 f'rfc822msgid:{mid.strip("<>")}')
        except Exception:
            typ, data = imap.uid("SEARCH", None, "HEADER",
                                 "Message-ID", f'"{mid}"')
        return typ == "OK" and bool(data and data[0])
    except Exception as e:
        log.debug("Message-ID existence check failed in %s/%s: %s",
                  email_addr, folder, e)
        return False
    finally:
        if imap is not None:
            _imap_release(email_addr, imap, broken, lane=lane)
        if interactive:
            _ui_wait_end()


def _imap_message_id_in_account(email_addr, password, message_id,
                                interactive=False) -> tuple:
    """Is this message ALREADY somewhere in this whole account?

    Returns (where, intact): `where` is the logical folder it was found in
    ("All Mail" / "Trash" / "Spam" / "Inbox") or "", and `intact` says whether
    the copy that is there actually HAS a body.

    `intact` exists because of the mess this whole batch is about. The copies
    the old cross-account move left behind are real messages with real
    Message-IDs and no contents, so "it is already there" can be true and
    useless at the same time. Delivering a second copy alongside is not the
    answer (Gmail may refuse it, and it would be a duplicate if it did not) —
    but saying nothing would leave Issu with a hollow receipt and the intact
    original quietly ageing out of the source account's Trash. So the caller
    is told, and points him at Tools → "Mail with no body…", which repairs it
    properly and verifies the result before removing anything.

    Issu 2026-08-16 — why the folder-scoped check above was not enough, and
    why it is the reason "de blir kopior":

    A cross-account rule delivers a receipt to
    ".../0---Frakt & Kvitto". Issu then files it on into
    ".../0---Frakt & Kvitto/2026-08" — a deliberate act, and the whole point
    of the month folders. The source copy, meanwhile, is sitting in the other
    account's Trash and keeps matching the same rule on every check
    (action_rescue_trash). The old check looked in the PARENT folder only,
    found nothing there any more, and appended a SECOND copy. File that one
    away too and the next check appends a third. The activity log shows this
    running 144 times in a week.

    Asking the account instead of one folder ends it: All Mail on Gmail holds
    every message whatever label it wears, so a copy filed three levels down
    is still found. Trash and Spam are checked too — a copy Issu deliberately
    threw away must stay thrown away, not quietly come back on the next
    check.

    Errors return ("", True) (assume "not delivered yet"): one extra copy on a
    network hiccup is recoverable, silently dropping a shipping receipt is
    not."""
    mid = _hdr_safe(message_id or "")
    if not mid:
        return "", True
    lane = "ui" if interactive else "bg"
    if interactive:
        _ui_wait_begin()
    imap = None
    broken = False
    try:
        imap = _imap_acquire(email_addr, password, lane=lane)
        mapping = _discover_mailboxes(imap)
        for logical in ("All Mail", "Trash", "Spam", "Inbox"):
            mailbox = mapping.get(logical, logical)
            try:
                typ, _ = imap.select(_mb_arg(mailbox), readonly=True)
                if typ != "OK":
                    continue
                try:
                    typ, data = imap.uid("SEARCH", "X-GM-RAW",
                                         f'rfc822msgid:{mid.strip("<>")}')
                except Exception:
                    # Not Gmail, or the extension was refused — the plain
                    # HEADER search works on every IMAP server.
                    typ, data = imap.uid("SEARCH", None, "HEADER",
                                         "Message-ID", f'"{mid}"')
                if typ == "OK" and data and data[0]:
                    # Found. Now: is what is sitting there a real message, or
                    # one of the hollow copies? 256 bytes of the body answers
                    # it, on the connection already open, and only ever once
                    # per message — the ledger remembers the verdict.
                    intact = True
                    try:
                        for u in data[0].split():
                            t2, f2 = imap.uid("FETCH", u.decode(),
                                              "(BODY.PEEK[TEXT]<0.256>)")
                            if t2 != "OK":
                                continue
                            it = next((x for x in f2
                                       if isinstance(x, tuple)), None)
                            intact = bool(it and
                                          len((it[1] or b"").strip()) >= 8)
                            if intact:
                                break
                    except Exception:
                        intact = True      # unsure → do not raise a false alarm
                    return logical, intact
            except Exception as e:
                log.debug("Account-wide Message-ID check failed in %s/%s: %s",
                          email_addr, logical, e)
        return "", True
    except Exception as e:
        log.debug("Account-wide Message-ID check failed for %s: %s",
                  email_addr, e)
        return "", True
    finally:
        if imap is not None:
            _imap_release(email_addr, imap, broken, lane=lane)
        if interactive:
            _ui_wait_end()


def _dedupe_messages(messages, across_accounts=False):
    """Drop repeats of the SAME message from a list, keeping the best copy.

    Issu 2026-08-07: "Jag har många dubletter med tomma meddelanden." Two
    things produce them. A cached header-only stub and the freshly fetched
    full copy can both end up in the same list (different objects, same mail);
    and on Gmail one message carries several labels, so a fetch that touches
    more than one folder brings the same message back more than once — the
    second copy typically header-only, which is why the duplicate looks EMPTY.

    The rule is simple: same Message-ID (in the same account and folder) means
    the same mail, and the copy that actually has a body wins. Where there is
    no Message-ID at all, sender+subject+date stands in for it. Order is
    preserved — this only removes, never rearranges.

    `across_accounts=True` widens it for the ALL ACCOUNTS view. Checking
    Issu's real cache on 2026-08-08 found SEVEN messages sitting in two of his
    accounts at once — DHL and Tradera write to both BGGGeekmarket and
    gotanetreserv, so "DHL Reklamation: 8020974067" was genuinely there twice.
    In one account's Inbox that is one message; in the merged view it was two
    identical rows. They now collapse to one, and `_also_in` names the other
    accounts so nothing is hidden — you can still see it reached both.
    Deliberately OFF for a single-account folder, where two copies would mean
    something quite different."""
    out, best = [], {}
    for m in messages or []:
        mid = _re.sub(r"\s+", "", (m.get("_message_id") or ""))
        # In the merged view the account is NOT part of the identity — that is
        # the whole point; everywhere else it is.
        scope = ("*" if across_accounts else m.get("account_email", ""),
                 "*" if across_accounts else m.get("_folder", ""))
        if mid:
            key = scope + (mid,)
        else:
            key = scope + (m.get("from", ""), m.get("subject", ""),
                           m.get("_dt", ""))
            # No Message-ID and nothing to identify it with: leave it alone
            # rather than risk collapsing two genuinely different mails.
            if not any(key[2:]):
                out.append(m)
                continue
        if key not in best:
            best[key] = len(out)
            out.append(m)
            continue
        i = best[key]
        kept = out[i]
        # Prefer the copy with a real body; between two loaded copies prefer
        # the one carrying more (an attachment list, flags, a thread id).
        def _score(x):
            return (1 if x.get("_body_loaded", True) else 0,
                    1 if (x.get("body") or "").strip() else 0,
                    len(x.get("attachments") or []),
                    1 if x.get("_thread_id") else 0)
        if _score(m) > _score(kept):
            m["_also_in"] = kept.get("_also_in", [])
            out[i] = m
            kept, m = m, kept
        # Remember the account the dropped copy came from, so the row can say
        # "also in gotanetreserv@gmail.com" instead of quietly losing it.
        other = m.get("account_email", "")
        if across_accounts and other and other != kept.get("account_email", ""):
            also = kept.setdefault("_also_in", [])
            if other not in also:
                also.append(other)
        log.debug("dedupe: dropped a duplicate of %r", m.get("subject", "")[:60])
    if len(out) != len(messages or []):
        log.info("Dropped %d duplicate message(s) from the list%s",
                 len(messages) - len(out),
                 " (same mail in more than one account)" if across_accounts
                 else "")
    return out


def _find_message_anywhere(email_addr, password, message_id):
    """Where does this message live NOW? Returns (folder, uid) or (None, None).

    Issu 2026-08-07, the mail-hunt from hell: a shipping receipt arrives in
    account 2, he opens it in the Inbox — and it vanishes. He looks in the
    folder his rule sends it to; it is there; he opens it; it vanishes again.
    Back in the original Inbox it reappears, he clicks, and the reading pane
    says "Loading" forever. Three or four rounds before it would open.

    The cause is not mysterious: a filter MOVES the message (his shipping
    rules do exactly that, some of them across accounts), and a message's UID
    is only valid in the mailbox it was in. The moment it moves, the UID the
    open window is holding points at nothing, the on-demand body fetch comes
    back empty, and the pane sits on "Loading" with no way out.

    So instead of giving up, we ask Gmail where it went. Gmail's own search
    understands rfc822msgid:, which finds the one message by its Message-ID
    across every label in the account in a single query — this is not a walk
    through folder after folder. All Mail is searched, so it finds the message
    whatever label it now carries."""
    mid = _hdr_safe(message_id or "")
    if not mid:
        return None, None
    # The "ui" lane: this only ever runs because you clicked a message that
    # turned out to have moved, and you are staring at the screen waiting.
    _ui_wait_begin()
    imap = _imap_acquire(email_addr, password, lane="ui")
    broken = False
    try:
        mapping = _discover_mailboxes(imap)
        # All Mail first: on Gmail it holds every non-deleted message whatever
        # its labels, so one look there answers the question in most cases.
        for logical in ("All Mail", "Inbox", "Trash", "Spam"):
            mailbox = mapping.get(logical, logical)
            try:
                typ, _ = imap.select(f'"{mailbox}"', readonly=True)
                if typ != "OK":
                    continue
                try:
                    typ, data = imap.uid("SEARCH", "X-GM-RAW",
                                         f'rfc822msgid:{mid.strip("<>")}')
                except Exception:
                    # Not Gmail (or the extension is refused) — the standard
                    # HEADER search works everywhere, just more slowly.
                    typ, data = imap.uid("SEARCH", None, "HEADER",
                                         "Message-ID", f'"{mid}"')
                if typ == "OK" and data and data[0]:
                    uid = data[0].split()[-1].decode()
                    log.info("Followed a moved message: %s is now in %s uid %s",
                             mid, logical, uid)
                    return logical, uid
            except Exception as e:
                log.debug("Message-ID search failed in %s/%s: %s",
                          email_addr, logical, e)
        return None, None
    except Exception:
        broken = True
        raise
    finally:
        _imap_release(email_addr, imap, broken, lane="ui")
        _ui_wait_end()


def _cache_load_folder(email_addr, folder, limit=FETCH_LIMIT):
    """Rebuild message dicts straight from the on-disk cache — NO network — so
    a folder can be shown INSTANTLY while the live refresh runs behind it.
    Returns [] when nothing is cached."""
    try:
        idx = _cache_load_index(email_addr, folder)
        stored = idx.get("uids", {})
        if not stored:
            return []
        cache_dir = _cache_folder_dir(email_addr, folder)
        out = []
        for uid, ent in stored.items():
            path = os.path.join(cache_dir, uid + ".eml")
            full = _cached_body_ok(path)
            if not full:
                # No body on disk — but the HEADERS may be, and a correct list
                # you can read at once beats a blank folder claiming there is
                # no mail in it (Issu 2026-08-08). The body is fetched when the
                # message is opened, exactly as it would have been anyway.
                path = os.path.join(cache_dir, uid + ".hdr")
                if not _cached_body_ok(path):
                    continue
            try:
                with open(path, "rb") as f:
                    raw = f.read()
                m = _email.message_from_bytes(raw)
                built = _build_msg_dict(m, ent.get("flags", []),
                                        ent.get("thrid") or None, uid,
                                        email_addr, folder, ent.get("meta", ""),
                                        body_loaded=full)
                built["_raw"] = raw
                out.append(built)
            except Exception:
                continue
        out.sort(key=lambda mm: mm.get("_sortkey", 0.0), reverse=True)
        return out[:limit]
    except Exception:
        return []


_UNSEEN_RE = _re.compile(rb"UNSEEN\s+(\d+)")


# Folders where "unseen" is a meaningless number and the badge must count
# MESSAGES instead (Issu 2026-08-07).
#
# A draft is something you wrote. It is not unread mail — but Gmail leaves
# drafts without the \Seen flag, so STATUS (UNSEEN) reports them and the
# sidebar sat on "Drafts (2)" for ever. Opening the folder corrected it to
# nothing, the next background count pass put the 2 straight back, and it
# looked exactly like a bug that could not be got rid of ("efter några
# sekunder så blir det (2) igen, trots att det är helt tomt").
#
# For these folders the honest number is simply how many messages are in
# there — which is also the number you can see once it opens.
_COUNT_BY_MESSAGES = {"Drafts"}
_MESSAGES_RE = _re.compile(rb"MESSAGES\s+(\d+)")


def _folder_unread_counts(email_addr, password, logical_folders,
                          custom_mailboxes) -> dict:
    """READ-ONLY. Return {key: count} for one account.

    Keys are the logical folder names passed in (Inbox, Spam, …) plus each
    custom mailbox PATH. Uses the IMAP STATUS command — no SELECT and no
    message fetch, so it is cheap even across many folders. One login for the
    whole account. Missing/short results are simply omitted.

    The count is UNSEEN everywhere except the folders in _COUNT_BY_MESSAGES,
    where it is the plain message count — see the note there."""
    imap = _imap_acquire(email_addr, password)
    out = {}
    broken = False
    try:
        mapping = _discover_mailboxes(imap)
        targets = [(lg, mapping.get(lg, lg)) for lg in logical_folders]
        targets += [(mb, mb) for mb in custom_mailboxes]
        for key, mb in targets:
            # Between every mailbox, stand aside if a click is waiting. On
            # issusbarn@gmail.com this loop walks TWENTY-ONE mailboxes every
            # minute (7 standard + 14 of his own labels) and used to hold the
            # account's only connection for the whole walk — which is a large
            # part of the half-minute he waited for one message to open
            # (2026-08-08).
            _background_yield()
            try:
                by_messages = key in _COUNT_BY_MESSAGES
                typ, data = imap.status(
                    f'"{mb}"', "(MESSAGES UNSEEN)" if by_messages
                    else "(UNSEEN)")
                if typ != "OK" or not data or not data[0]:
                    continue
                raw = data[0] if isinstance(data[0], bytes) else \
                    str(data[0]).encode("utf-8", "replace")
                m = (_MESSAGES_RE if by_messages else _UNSEEN_RE).search(raw)
                if m:
                    out[key] = int(m.group(1))
            except Exception:
                continue      # one bad mailbox must not sink the whole pass
    except Exception as e:
        broken = True
        log.warning("Unread-count pass failed for %s: %s", email_addr, e)
    finally:
        _imap_release(email_addr, imap, broken)
    return out


def _imap_quota(email_addr, password):
    """How full the mailbox is: (used_bytes, total_bytes), or None.

    Uses the IMAP QUOTA extension (RFC 2087), which Gmail supports and
    reports in kilobytes. Read-only — asking how full a box is cannot change
    anything in it."""
    imap = _imap_acquire(email_addr, password)
    broken = False
    try:
        typ, data = imap.getquotaroot("INBOX")
        if typ != "OK" or not data:
            return None
        # data looks like [[b'"INBOX" "Quota"'], [b'"Quota" (STORAGE 4194304 15728640)']]
        blob = b" ".join(
            part if isinstance(part, bytes) else b" ".join(part)
            for chunk in data for part in (chunk if isinstance(chunk, list)
                                           else [chunk]))
        m = _re.search(rb"STORAGE\s+(\d+)\s+(\d+)", blob)
        if not m:
            return None
        used_kb, total_kb = int(m.group(1)), int(m.group(2))
        return used_kb * 1024, total_kb * 1024
    except Exception as e:
        broken = True
        log.debug("Quota not available for %s: %s", email_addr, e)
        return None
    finally:
        _imap_release(email_addr, imap, broken)


def _verify_credentials(email_addr, password):
    """Raise if login fails; return True on success."""
    imap = _imap_connect(email_addr, password)
    try:
        imap.logout()
    except Exception:
        pass
    return True


# ── Recipient address hygiene (Issu 2026-08-01) ───────────────────────────────
# Something was slipping stray characters into addresses ("issusbarn@♣gmail.com",
# a mangled "@ugmail…") — corruption Issu never saw in Thunderbird. Two guards:
#   1) strip any character that simply cannot be in an email address, and
#   2) flag a domain that looks like a corrupted "gmail.com".
_ADDR_LOCAL_OK = set(
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.!#$%&'*+/=?^_`{|}~-")
_ADDR_DOMAIN_OK = set(
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-")
_EMAIL_RE = _re.compile(r"^[^@\s]+@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+$")


# ── Pasted "mailto:" links (Issu 2026-09-09) ──────────────────────────────────
# Copying an address off a web page gives you the LINK, not the address:
# "mailto:info@sallesror.se", often with a "?subject=…" tail behind it or an "@"
# written as "%40". Deleting that prefix by hand every single time is exactly
# the kind of chore the program should do for itself, so every address that
# enters F(re)email is run through here first.
#
# It is deliberately narrow: a string with no "mailto:" in it comes back
# untouched, and only the address token right after the "mailto:" is rewritten —
# so a display name keeps whatever it says, question mark and all
# ("Who? <mailto:a@b.se>" → "Who? <a@b.se>").
_MAILTO_URL_RE = _re.compile(r"(?i)(?:^|(?<=<))\s*mailto:\s*([^<>\s,;]*)")


def _strip_mailto(text: str) -> str:
    """Turn a pasted mailto: link into the plain address it points at.

        mailto:info@sallesror.se                → info@sallesror.se
        MAILTO:info@sallesror.se?subject=Hej    → info@sallesror.se
        <mailto:info%40sallesror.se>            → info@sallesror.se
        Salle <mailto:info@sallesror.se>        → Salle <info@sallesror.se>

    The "?subject=…&body=…" tail is dropped: this is an address field, and a
    subject smuggled into it would go out as part of the recipient. Percent
    escapes are decoded, because a mailto: URL is allowed to write "@" as
    "%40" and an address that still says "%40" is undeliverable."""
    s = str(text or "").strip()
    if "mailto:" not in s.lower():
        return s                      # the overwhelmingly common case: no-op

    def _plain(m):
        addr = m.group(1).split("?", 1)[0]      # drop ?subject=…&body=…
        if "%" in addr:
            try:
                from urllib.parse import unquote
                addr = unquote(addr)
            except Exception:
                pass
        return addr

    return _MAILTO_URL_RE.sub(_plain, s).strip()


def _clean_one_address(addr: str):
    """Return (clean_address, changed?). Removes any character not legal in an
    email address (control chars, spaces, ♣ and the like), and turns a pasted
    "mailto:" link into the bare address it points at. A display name, if
    present, is kept as-is."""
    addr = _strip_mailto(addr)
    name, email_ = parseaddr(addr or "")
    email_ = email_ or (addr or "")
    if "@" in email_:
        local, _, domain = email_.rpartition("@")
        clean_local  = "".join(c for c in local  if c in _ADDR_LOCAL_OK)
        clean_domain = "".join(c for c in domain if c in _ADDR_DOMAIN_OK)
        clean = f"{clean_local}@{clean_domain}"
    else:
        clean = "".join(c for c in email_ if c in _ADDR_LOCAL_OK or c == "@")
    changed = (clean != email_)
    if name:
        return (formataddr((name, clean)), changed)
    return (clean, changed)


def _gmail_lookalike(addr: str) -> str:
    """If the domain looks like a mangled gmail.com, return the address it was
    probably meant to be; otherwise ''. Catches 'ugmail.com', 'gmai.com',
    'gmaill.com', etc. — exactly the class of corruption Issu reported."""
    email_ = parseaddr(addr or "")[1] or (addr or "")
    if "@" not in email_:
        return ""
    local, _, domain = email_.rpartition("@")
    d = domain.lower()
    if d in ("gmail.com", "googlemail.com"):
        return ""
    if "gmail" in d:            # 'ugmail.com', 'gmail.co', 'gmail.con', …
        return f"{local}@gmail.com"
    return ""


# ── Address forensics: catch the corruption IN THE ACT ────────────────────────
# The root cause of "issusbarn@♣gmail.com" was never found — cleaning the field
# treats the symptom. So the moment a bad character is seen, everything needed to
# identify the source is written to Freemail.log: the exact original string as a
# repr, every illegal character with its Unicode code point and NAME and where in
# the string it sat, and WHICH path the address came down (compose, Smart Reply,
# unsubscribe, bounce retry, address book, …). Next time it happens, the log says
# what it was and where it came from instead of leaving us guessing again.

def _addr_forensics(raw: str) -> str:
    """Spell out every character of `raw` that cannot be in an address.

    Written as U+XXXX plus the official Unicode name, because a log file full of
    glyphs the viewer cannot render is exactly no help at all — "♣" and a
    zero-width space look identical in a text editor."""
    try:
        import unicodedata
    except Exception:
        unicodedata = None
    bits = []
    for i, ch in enumerate(raw or ""):
        if ch in _ADDR_LOCAL_OK or ch in "@<>, ;\"":
            continue
        name = ""
        if unicodedata is not None:
            try:
                name = unicodedata.name(ch)
            except ValueError:
                name = "unnamed control/private character"
        bits.append(f"position {i}: U+{ord(ch):04X} {name}".rstrip())
    return "; ".join(bits) or "(nothing illegal — the domain itself is wrong)"


def _clean_address_list(raw, source="", field=""):
    """Clean a whole To:/Cc:/Bcc: value. Returns (cleaned_string, problems).

    `raw` may be a string or a list. Cleaning is SILENT (the character could
    never have been delivered anyway); anything still suspect afterwards — a
    gmail lookalike, or something that is not an address at all — comes back in
    `problems` for the caller to decide about."""
    if isinstance(raw, (list, tuple)):
        segs = [str(s).strip() for s in raw]
    else:
        segs = [s.strip() for s in _re.split(r"[;,]", str(raw or ""))]
    cleaned, problems = [], []
    for s in segs:
        if not s:
            continue
        c, changed = _clean_one_address(s)
        if changed:
            log.error("ADDRESS CORRUPTION [%s%s]: %r  →  %r    %s",
                      source or "unknown source",
                      f" {field}" if field else "",
                      s, c, _addr_forensics(s))
        cleaned.append(c)
        look = _gmail_lookalike(c)
        bare = parseaddr(c)[1] or c
        if look:
            problems.append(f"{c}  (did you mean {look}?)")
            log.warning("ADDRESS LOOKALIKE [%s%s]: %r looks like %r",
                        source or "unknown source",
                        f" {field}" if field else "", c, look)
        elif bare and not _EMAIL_RE.match(bare):
            problems.append(f"{c}  (not a valid address)")
    return ", ".join(cleaned), problems


def _sanitize_payload_addresses(payload: dict, source: str) -> dict:
    """Clean every recipient field of an outgoing message, in place.

    This runs at the ONE choke point every message passes through (queue_send),
    so a path that never learned to sanitise — the unsubscribe mailer, a bounce
    retry, a restored draft, anything added later — still cannot put a corrupt
    address on the wire. The compose windows clean earlier as well, because
    there the field can visibly correct itself and the user can be asked; by the
    time we are here there is nobody to ask, so it is clean-and-log only."""
    try:
        for field in ("to", "cc"):
            val = payload.get(field, "")
            if val:
                payload[field], _ = _clean_address_list(val, source, field)
        bcc = payload.get("bcc") or []
        if bcc:
            joined, _ = _clean_address_list(bcc, source, "bcc")
            payload["bcc"] = [x.strip() for x in joined.split(",") if x.strip()]
    except Exception as e:
        # Never let hygiene stop a message going out — log and send as-is.
        log.error("Address sanitising failed (%s): %s", source, e)
    return payload


# ── Subject/body hygiene (Issu 2026-08-01) ────────────────────────────────────
# The same stray characters Issu saw in addresses (♣, invisible spaces) plus a
# DIFFERENT failure — an "ä" arriving as "?" or � — were reported in the
# SUBJECT and BODY of sent/bounced mail ("det hände ALDRIG i Thunderbird").
# Text is not an address, so the rule is deliberately looser than the recipient
# guard: every script, emoji and ordinary symbol is legal. Only genuinely
# invalid characters are removed, and the � replacement character is flagged
# because it is the fingerprint of a decode that already lost a letter.
_TEXT_STRIP_CATS = {"Cc", "Cf", "Co", "Cs", "Cn"}   # control/invisible/private/…
_TEXT_KEEP_CTRL  = {"\n", "\r", "\t"}               # real line breaks stay


def _scan_text_corruption(text: str):
    """Inspect a subject or body. Returns (clean, changed, forensics, has_repl).

    * control / invisible / private-use / surrogate / unassigned characters are
      stripped (real newlines and tabs are kept) — none of them belong in typed
      text and none can be typed on purpose;
    * U+FFFD REPLACEMENT CHARACTER (�) is COUNTED but LEFT IN. It is the mark of
      an earlier decode that already lost the original letter (this is where an
      "ä" turned into "?"/�); dropping it here would only hide the evidence, so
      the caller warns about it instead.
    Emoji and every real script pass untouched."""
    try:
        import unicodedata
    except Exception:
        return text, False, "", ("�" in (text or ""))
    kept, bits, has_repl = [], [], False
    for i, ch in enumerate(text or ""):
        if ch == "�":
            has_repl = True
            kept.append(ch)
            bits.append(f"position {i}: U+FFFD REPLACEMENT CHARACTER "
                        "(a letter was already lost decoding upstream)")
            continue
        if ch in _TEXT_KEEP_CTRL:
            kept.append(ch)
            continue
        if unicodedata.category(ch) in _TEXT_STRIP_CATS:
            try:
                nm = unicodedata.name(ch)
            except ValueError:
                nm = "unnamed control/private character"
            bits.append(f"position {i}: U+{ord(ch):04X} {nm}")
            continue                       # dropped
        kept.append(ch)
    clean = "".join(kept)
    return clean, (clean != (text or "")), "; ".join(bits), has_repl


def _sanitize_payload_text(payload: dict, source: str) -> dict:
    """Clean the subject and body of an outgoing message, in place, at the same
    choke point (queue_send) as the address sanitiser. Silent by design — there
    is nobody to ask this deep in the send path — but every change and every
    replacement character is logged so the corruption finally has a paper
    trail (grep the log for TEXT CORRUPTION)."""
    try:
        for field in ("subject", "body"):
            val = payload.get(field, "")
            if not val:
                continue
            clean, changed, forensics, has_repl = _scan_text_corruption(val)
            if changed or has_repl:
                log.error("TEXT CORRUPTION [%s %s]: %s%s",
                          source or "unknown source", field,
                          forensics or "(cleaned)",
                          "  — REPLACEMENT CHARACTER present, a letter was "
                          "already lost upstream" if has_repl else "")
            payload[field] = clean
        # A SUBJECT is a header, and a header is one line. A pasted subject can
        # easily carry a line break; the body must keep its newlines, so only
        # the subject is unfolded here (Issu 2026-08-07).
        if payload.get("subject"):
            payload["subject"] = _hdr_safe(payload["subject"])
        # Threading headers too — these are copied off the message being
        # answered and arrive folded on any long thread.
        for field in ("in_reply_to", "references"):
            if payload.get(field):
                payload[field] = _hdr_safe(payload[field])
    except Exception as e:
        log.error("Text sanitising failed (%s): %s", source, e)
    return payload


def _smtp_send(email_addr, password, to_addrs, cc_addrs, subject, body,
               attachment_paths=None, bcc_addrs=None, html_body=None,
               in_reply_to="", references="", message_id="", protected=False):
    """Send one message. BCC recipients are passed to the server but never
    written into a header — that is exactly what makes them blind.

    With html_body the message goes out as multipart/alternative: the plain
    `body` is the fallback and `html_body` the rich version, so a client that
    cannot render HTML still shows a clean, complete message (Smart Reply's
    two-part reply needs this — DEL 06b).

    in_reply_to/references thread a reply back to the message it answers —
    the original's Message-ID goes in both (References also carries the
    ORIGINAL's own References chain, if it had one, so a long thread stays
    one thread instead of breaking after a couple of hops). Without this,
    every reply looked like a brand-new, unrelated message to the recipient's
    client (Issu 2026-08-05: "det finns ingen In-Reply-To i headern").

    protected=True is "✉🔒 Send and save" (DEL 09p): the message goes out
    carrying X-Freemail-Protected, which is what makes Gmail's own copy in
    Sent refuse to go along with a bulk delete. message_id, when given, is
    written as the Message-ID header — Gmail may well replace it with one of
    its own, so it is a bonus and never the thing protection depends on."""
    em = EmailMessage()
    # Every header value is unfolded first — see _hdr_safe. Without this a
    # perfectly ordinary reply into a long thread is rejected outright.
    em["From"] = _hdr_safe(email_addr)
    em["To"]   = _hdr_safe(", ".join(to_addrs))
    if cc_addrs:
        em["Cc"] = _hdr_safe(", ".join(cc_addrs))
    em["Subject"] = _hdr_safe(subject)
    if in_reply_to:
        em["In-Reply-To"] = _hdr_safe(in_reply_to)
    if references:
        em["References"] = _hdr_safe(references)
    if message_id:
        em["Message-ID"] = _hdr_safe(message_id)
    if protected:
        # ONE header is the whole mechanism (DEL 09p). It survives everything
        # a local note would not: a wiped settings folder, another machine,
        # another mail client, and any rule that moves the mail about.
        em[_PROTECT_HEADER] = "1"
    em.set_content(body or "")
    if html_body:
        em.add_alternative(html_body, subtype="html")
    for path in (attachment_paths or []):
        try:
            with open(path, "rb") as f:
                data = f.read()
            ctype, _ = mimetypes.guess_type(path)
            maintype, subtype = (ctype.split("/", 1) if ctype
                                 else ("application", "octet-stream"))
            em.add_attachment(data, maintype=maintype, subtype=subtype,
                              filename=os.path.basename(path))
        except Exception as e:
            log.warning("Could not attach %s: %s", path, e)
    ctx = ssl.create_default_context()
    with smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT, context=ctx) as s:
        s.login(email_addr, password)
        everyone = list(to_addrs) + list(cc_addrs or []) + list(bcc_addrs or [])
        if bcc_addrs:
            # send_message() would derive the recipients from the headers,
            # and BCC is deliberately not in them — so name them explicitly.
            s.send_message(em, from_addr=email_addr, to_addrs=everyone)
        else:
            s.send_message(em)


# ── Smart Reply: the two-part reply body (Issu 2026-08-03) ────────────────────
#
# A Smart Reply now always produces TWO parts and sends both:
#
#   • "My reply"        — just your answers, in order, with none of the
#                         sender's text. The clean version, for a quick read.
#   • "The full message"— the sender's original text with your answers placed
#                         exactly where you wrote them (the classic inline reply).
#
# A checkbox (default ON) puts "My reply" first; unticked, the full version
# leads. Between them is a separator line, and a one-line hint says how far
# down the other part is. The PLAIN-text hint carries an exact line number,
# which is deterministic (it does not depend on the reader's mail program);
# the HTML version adds clickable anchors on top of that.
#
# The message goes out as multipart/alternative, so a client that cannot render
# HTML still gets the whole thing as clean plain text.

# What property the sender's quoted text carries in the HTML full-version.
# Plain text always uses the universal "> " quote marker regardless.
_SR_QUOTE_STYLES = ["none", "grey", "italic", "bold", "blockquote"]
_SR_QUOTE_LABELS = {
    "none":       "No special style",
    "grey":       "Grey text",
    "italic":     "Grey italic",
    "bold":       "Bold",
    "blockquote": "Quote bar (grey, indented)",
}


def _sr_quote_css(style: str) -> str:
    return {
        "none":       "",
        "grey":       "color:#777777;",
        "italic":     "color:#777777;font-style:italic;",
        "bold":       "font-weight:bold;",
        "blockquote": ("color:#777777;border-left:3px solid #bbbbbb;"
                       "padding-left:10px;"),
    }.get(style, "color:#777777;")


_SR_PART_LOWER = {
    "answers": "my reply",
    "full":    "the full message with the original text",
}
_SR_SEP = "─" * 56

# ── The line BETWEEN the two parts (Issu 2026-08-08) ──────────────────────────
#
# The old build opened with a caretaker's note on top of everything —
#
#     You'll find my reply first. The full message with the original text
#     begins on line 11 below.
#     ===  MY REPLY  ===
#
# — which is the first thing the recipient reads, before a single word you
# actually wrote. "Bättre, att oavsett vilken version först... att man börjar
# som det är... och först mellan versionerna har 'my message is finished but
# here it comes again'".
#
# So: the message now STARTS with content, whichever version you put first,
# with no heading and no preamble at all. The explanation appears once, in the
# middle, where it is genuinely needed — at the point the reader hits the
# second copy and would otherwise wonder why they are reading it twice.
_SR_BRIDGE = {
    "answers": ("That is my reply. Below it comes again — this time the whole "
                "original message, with each of my answers written in "
                "directly under the paragraph it belongs to."),
    "full":    ("That is the whole original message with my answers written "
                "in. Below is my reply on its own, with none of the original "
                "text — the short version."),
}


def _sr_indent(text: str, steps: int) -> str:
    """Push every line of the sender's text right by `steps` spaces.

    Issu 2026-08-08: "Ge möjlighet att man kan TABba avsändarens alla rader …
    Då blir det väldigt tydligt vem som svarar." 0 leaves the text exactly as
    it was."""
    if not steps or not text:
        return text
    pad = " " * int(steps)
    return "\n".join(pad + ln for ln in text.split("\n"))


def _sr_answers_plain(pairs, anchors=False) -> str:
    """Just your answers, in order. With `anchors` each one says which
    paragraph it belongs to, so the short version can still be followed back
    into the long one (the plain-text stand-in for an <a href="#…"> link)."""
    out = []
    n = 0
    for _s, a in pairs:
        n += 1
        if not a.strip():
            continue
        if anchors:
            out.append(f"[{n}]  {a.strip()}")
        else:
            out.append(a.strip())
    return "\n\n".join(out)


def _sr_full_plain(pairs, indent=0, anchors=False) -> str:
    out = []
    n = 0
    for s, a in pairs:
        n += 1
        s = (s or "").strip()
        if s:
            quoted = _sr_indent("\n".join("> " + ln for ln in s.split("\n")),
                                indent)
            if anchors:
                # The [n] label stays at the left margin — it is a signpost,
                # not part of what they wrote, so it should not move with the
                # indent.
                quoted = f"[{n}]\n" + quoted
            out.append(quoted)
        if a.strip():
            out.append(a.strip())
    return "\n\n".join(out)


def _sr_answers_html(pairs, anchors=False) -> str:
    """Your answers alone. Each carries an id AND a link back to the same
    paragraph in the full version, so a reader can jump straight to the
    context of any single answer and back again — Issu's `<a href="#namn">`
    (2026-08-08), applied per paragraph rather than only per part."""
    out = []
    n = 0
    for _s, a in pairs:
        n += 1
        if not a.strip():
            continue
        body = _htmllib.escape(a.strip()).replace(chr(10), "<br>")
        if anchors:
            out.append(
                f'<p id="a{n}">{body} '
                f'<a href="#p{n}" style="color:#2a6ab0;font-size:11px;'
                f'text-decoration:none;">[to their paragraph {n} &#8595;]</a>'
                f'</p>')
        else:
            out.append(f"<p>{body}</p>")
    return "\n".join(out)


def _sr_full_html(pairs, style: str, indent=0, anchors=False) -> str:
    """The original message with your answers in place. `indent` pushes THEIR
    text right (in em, matched to the plain-text spaces) so the two voices sit
    in two columns."""
    css, out = _sr_quote_css(style), []
    pad = (f"margin-left:{indent * 0.55:.2f}em;" if indent else "")
    n = 0
    for s, a in pairs:
        n += 1
        s = (s or "").strip()
        if s:
            esc = _htmllib.escape(s).replace("\n", "<br>")
            anc = f' id="p{n}"' if anchors else ""
            back = ""
            if anchors and a.strip():
                back = (f' <a href="#a{n}" style="color:#2a6ab0;font-size:11px;'
                        f'text-decoration:none;">[my answer {n} &#8593;]</a>')
            if style == "blockquote":
                out.append(f'<blockquote{anc} style="{css}{pad}margin-top:8px;'
                           f'margin-bottom:8px;">{esc}{back}</blockquote>')
            else:
                out.append(f'<p{anc} style="{css}{pad}">{esc}{back}</p>')
        if a.strip():
            out.append(f'<p>{_htmllib.escape(a.strip()).replace(chr(10), "<br>")}</p>')
    return "\n".join(out)


def _smart_reply_bodies(pairs, answers_on_top=True, style="grey",
                        signature="", indent=0, anchors=True) -> tuple:
    """Build (plain_text, html) for a Smart Reply.

    `pairs` is a list of (sender_paragraph, answer); an empty answer means that
    paragraph was not replied to (it still appears, for context, in the full
    version). Returns the plain-text fallback and the HTML alternative, both
    carrying the same two parts in the same order.

    The message opens with real content — no heading, no "you'll find X first"
    preamble. The one explanatory sentence sits BETWEEN the two copies, which
    is the only place a reader needs it (Issu 2026-08-08).

    `indent`  pushes the sender's lines right by that many spaces (0/5/10).
    `anchors` numbers every paragraph and cross-links answer ⇄ original in the
              HTML copy, and marks them [1] [2] … in the plain-text copy so the
              same navigation survives in a client that shows no HTML."""
    first, second = (("answers", "full") if answers_on_top
                     else ("full", "answers"))

    def _plain(kind):
        return (_sr_answers_plain(pairs, anchors) if kind == "answers"
                else _sr_full_plain(pairs, indent, anchors))

    def _html(kind):
        return (_sr_answers_html(pairs, anchors) if kind == "answers"
                else _sr_full_html(pairs, style, indent, anchors))

    # ── Plain text ───────────────────────────────────────────────────────────
    # Content first. Then the separator, the one explaining sentence, and the
    # second copy. The "(from line N)" pointer stays, because a line number is
    # the only reliable way to point at something in plain text — but it is now
    # part of the middle sentence instead of a banner over the whole message.
    bridge = _SR_BRIDGE[first] + "  (It starts on line {JUMP} below.)"
    blocks = [
        _plain(first),
        _SR_SEP,
        bridge,
        _SR_SEP,
        _plain(second),
    ]
    if signature.strip():
        blocks.append("-- \n" + signature.strip())
    plain_tok = "\n\n".join(b for b in blocks if b.strip())
    # The second copy begins two lines after the second separator (separator,
    # blank line, content) — and the pointer is 1-based, so that is index+3.
    lines = plain_tok.split("\n")
    sep_positions = [i for i, ln in enumerate(lines) if ln == _SR_SEP]
    jump = (sep_positions[1] + 3) if len(sep_positions) > 1 else len(lines)
    # Replacing the token on ONE line never shifts the line count, so `jump`
    # stays valid.
    plain = plain_tok.replace("{JUMP}", str(jump))

    # ── HTML ─────────────────────────────────────────────────────────────────
    sig_html = ""
    if signature.strip():
        sig_html = (f'<p style="color:#999999;">--<br>'
                    f'{_htmllib.escape(signature.strip()).replace(chr(10), "<br>")}'
                    f'</p>')
    # Same shape: straight into the content, one sentence in the middle, with
    # a link each way between the two copies.
    html = f"""<div style="font-family:Segoe UI,Arial,sans-serif;font-size:14px;color:#222222;line-height:1.45;">
<a id="sr_first"></a>
<div>{_html(first)}</div>
<hr style="border:none;border-top:2px dashed #bbbbbb;margin:20px 0;">
<p style="color:#555555;font-size:12px;"><a id="sr_second"></a>{_htmllib.escape(_SR_BRIDGE[first])}
<a href="#sr_first" style="color:#2a6ab0;">&#8593; back to the top</a></p>
<div>{_html(second)}</div>
{sig_html}
</div>"""
    return plain, html


def _split_reply_paragraphs(raw: str) -> list:
    """Split a message body into answerable paragraphs.

    Blank-line paragraphs first — but a great many mails (and anything you
    typed yourself) have NO blank lines, and the old split then handed back the
    whole message as one block, which makes a point-by-point reply pointless
    (Issu 2026-08-03: "första stycket = HELA MAILET"). So when blank lines give
    only one paragraph, fall back to one paragraph per non-empty LINE. The user
    can still merge/split by hand in the window."""
    raw = (raw or "").replace("\r\n", "\n").replace("\r", "\n")
    paras = [p.strip() for p in _re.split(r"\n[ \t]*\n", raw) if p.strip()]
    if len(paras) > 1:
        return paras
    lines = [ln.strip() for ln in raw.split("\n") if ln.strip()]
    if len(lines) > 1:
        return lines
    return paras or lines or [""]


def _reply_to_address(msg, my_emails) -> str:
    """The address a reply should be sent TO.

    Reply-To wins when present; otherwise the sender. BUT if that address is
    one of your OWN accounts — you are replying to a message you sent, or to a
    note to yourself — the reply goes to the ORIGINAL recipients instead, never
    back to yourself (Issu 2026-08-03: a reply came back addressed From == To ==
    me, and a copy landed in my own inbox)."""
    my = {(e or "").strip().lower() for e in (my_emails or []) if e}
    rt  = parseaddr(msg.get("_reply_to_hdr", "") or "")[1]
    frm = parseaddr(msg.get("from", "") or "")[1] or (msg.get("from", "") or "")
    cand = (rt or frm).strip()
    if cand and cand.lower() not in my:
        return cand
    others = []
    for a in (msg.get("_to_hdr", "") or "").split(","):
        addr = parseaddr(a)[1]
        if addr and addr.lower() not in my and addr not in others:
            others.append(addr)
    return ", ".join(others) if others else cand


def _parse_addr_list(header_value) -> list:
    """Split a To:/Cc: header string into bare email addresses, in order,
    dropping anything that doesn't parse to an address."""
    out = []
    for a in (header_value or "").split(","):
        addr = parseaddr(a)[1]
        if addr:
            out.append(addr)
    return out


def _other_recipients(msg, my_emails) -> list:
    """Everyone on the original message (its To: and Cc:) other than you —
    i.e. exactly who else besides you received it. Used both to show a
    recipient count in the reading pane and to build Reply All's Cc: list
    (Issu 2026-08-04: no way to see if a message went to more than just me,
    and no Reply All)."""
    my = {(e or "").strip().lower() for e in (my_emails or []) if e}
    seen = set(my)
    out = []
    for addr in (_parse_addr_list(msg.get("_to_hdr", "")) +
                 _parse_addr_list(msg.get("_cc_hdr", ""))):
        low = addr.strip().lower()
        if low and low not in seen:
            seen.add(low)
            out.append(addr)
    return out


def _reply_all_cc(msg, my_emails, primary_to) -> str:
    """The Cc: line for a REPLY ALL: everyone else who was on the original
    message, minus your own accounts and minus whoever already goes in
    To: (the primary reply address), de-duplicated, comma-joined."""
    primary = {parseaddr(a)[1].strip().lower()
               for a in (primary_to or "").split(",") if a.strip()}
    out = [addr for addr in _other_recipients(msg, my_emails)
           if addr.strip().lower() not in primary]
    return ", ".join(out)


def _reply_threading_headers(msg) -> tuple:
    """The In-Reply-To: / References: values for a reply to `msg`.

    In-Reply-To is just the original's Message-ID. References is the
    original's own References chain (if it had one — i.e. IT was itself a
    reply) with the original's Message-ID appended, so a long back-and-forth
    stays ONE thread in the recipient's client instead of breaking after a
    couple of hops. Without either header, every reply looks like a brand
    new, unrelated message (Issu 2026-08-05)."""
    mid = _hdr_safe(msg.get("_message_id") or "")
    if not mid:
        return "", ""
    # The original's References arrives FOLDED (…>\r\n <…>) because that is how
    # a long chain travels on the wire. Carried over as-is it made the send fail
    # outright — see _hdr_safe (Issu 2026-08-07, three Mirall replies stuck).
    prior_refs = _hdr_safe(msg.get("_references_hdr") or "")
    references = f"{prior_refs} {mid}".strip() if prior_refs else mid
    return mid, references


# ── Attachment auto-save engine (pure, offline-testable) ──────────────────────

def _safe_name(name: str) -> str:
    """Make a string safe to use as a Windows file/folder name."""
    name = _re.sub(r'[\\/:*?"<>|]+', "_", name or "").strip().strip(".")
    return name or "unknown"


def _expand_prefix(prefix: str, msg: dict) -> str:
    """Expand {tokens} in a rule's prefix using the message's own data.

    Tokens: {YYYY-MM} {YYYY-MM-DD} {YYYY} {MM} {DD}
            {sender}  (display name, else address local-part)
            {sender_email} {account} {subject}
    Uses msg['_dt'] (the EMAIL's date, ISO) so e.g. an electricity bill that
    arrives in June for May keeps the email's month, not today's."""
    dt_iso = msg.get("_dt", "") or ""
    ymd = dt_iso[:10]            # 'YYYY-MM-DD' or ''
    parts = ymd.split("-") if ymd else ["", "", ""]
    yyyy = parts[0] if len(parts) > 0 else ""
    mm   = parts[1] if len(parts) > 1 else ""
    dd   = parts[2] if len(parts) > 2 else ""
    sender_name = (msg.get("from_name") or "").strip()
    sender_addr = (msg.get("from") or "").strip()
    if not sender_name:
        sender_name = sender_addr.split("@")[0] if sender_addr else "unknown"
    repl = {
        "{YYYY-MM-DD}": ymd,
        "{YYYY-MM}":    f"{yyyy}-{mm}" if yyyy and mm else "",
        "{YYYY}":       yyyy,
        "{MM}":         mm,
        "{DD}":         dd,
        "{sender}":       sender_name,
        "{sender_email}": sender_addr,
        "{account}":      msg.get("account_email", ""),
        "{subject}":      msg.get("subject", ""),
    }
    out = prefix or ""
    # ── Be forgiving about the brackets and the case (Issu 2026-09-01) ───────
    # He typed "[YYYY-MM]" and got the letters back: on a Swedish keyboard
    # "{" is AltGr+7 and "[" is AltGr+8, one key apart, and the help writes
    # tokens in curly braces the way documentation writes placeholders — so
    # square brackets are the obvious guess and it failed silently. Any
    # bracket around a name we RECOGNISE now counts; anything else is left
    # exactly as typed, so a real "[note]" in a filename is never eaten.
    names = {t.strip("{}").lower(): t for t in repl}

    def _fix(m):
        tok = names.get(m.group(2).strip().lower())
        return tok if tok else m.group(0)

    out = _re.sub(r"([\[\(<\{])([^\[\]\(\)<>\{\}]{1,16})([\]\)>\}])", _fix, out)
    for tok, val in repl.items():
        out = out.replace(tok, val)
    return out


# ── The date part of a filename prefix, chosen instead of typed ───────────────
# Issu 2026-09-01: "Kanske det bör ändras till att man väljer vilket format som
# man vill ha, OM man vill ha datum… Bara bestämma om det ska vara före eller
# efter." Hand-typed tokens are a trap — one wrong bracket and the rule quietly
# writes the letters YYYY-MM into every filename, and nothing says so. These
# helpers are what the dropdown drives; they are pure so the fiddly bit (taking
# the old token out again without leaving a double separator behind) is
# testable without a window.
_DATE_TOKEN_CHOICES = [
    ("",             "no date"),
    ("{YYYY-MM}",    "2026-09        (year-month)"),
    ("{YYYY-MM-DD}", "2026-09-01     (year-month-day)"),
    ("{YYYY}",       "2026           (year)"),
    ("{MM}",         "09             (month)"),
    ("{DD}",         "01             (day)"),
]
_DATE_TOKENS = tuple(t for t, _ in _DATE_TOKEN_CHOICES if t)
_SEP_CHARS = "-_. "

def _prefix_date_token(prefix: str) -> str:
    """Which date token a prefix already carries ("" if none). The longest
    match wins, so {YYYY-MM-DD} is not mistaken for {YYYY}."""
    p = prefix or ""
    for tok in sorted(_DATE_TOKENS, key=len, reverse=True):
        if tok in p:
            return tok
    return ""

def _strip_date_token(prefix: str) -> str:
    """Take every date token out, swallowing ONE run of adjacent separators so
    "GELF---{YYYY-MM}---" comes back as "GELF---" and not "GELF------"."""
    out = prefix or ""
    for tok in sorted(_DATE_TOKENS, key=len, reverse=True):
        while tok in out:
            i = out.index(tok)
            j = i + len(tok)
            k = j
            while k < len(out) and out[k] in _SEP_CHARS:
                k += 1
            if k > j:                       # separators after it → drop those
                out = out[:i] + out[k:]
                continue
            h = i
            while h > 0 and out[h - 1] in _SEP_CHARS:
                h -= 1
            out = out[:h] + out[j:]         # else the ones before it
    return out

def _prefix_separator(prefix: str) -> str:
    """The joining string the prefix already uses ("---" in his GELF example),
    so an inserted date matches the style instead of imposing one."""
    runs = _re.findall(r"[-_.]+", prefix or "")
    return max(runs, key=len) if runs else "-"

def _set_date_token(prefix: str, token: str, where: str = "after") -> str:
    """Put `token` at the front or the back of `prefix`, replacing whatever
    date token was there. An empty token just removes it.

    The prefix is glued STRAIGHT onto the attachment's own filename
    (`prefix + fname` in _autosave_run), which is why his example ends in
    "---": without it the rule writes "2026-09kvitto.pdf". So a trailing
    separator is preserved through every move — losing it while shuffling the
    date from last to first would quietly ruin every filename the rule makes.
    An empty prefix gains one for the same reason."""
    original = prefix or ""
    sep = _prefix_separator(original)
    trailing = bool(_re.search(r"[-_. ]+$", original))
    base = _re.sub(r"[-_. ]+$", "", _strip_date_token(original))
    if not token:
        return (base + sep) if (base and trailing) else base
    if not base:
        return token + sep          # nothing else in the name — still needs
                                    # to be kept off the filename
    parts = [token, base] if where == "before" else [base, token]
    out = sep.join(parts)
    return out + sep if trailing else out


def _fname_match(name: str, pattern: str) -> bool:
    """Does a filename match a pattern? A pattern containing * or ? is a
    wildcard (so "*QR*.png" matches "my-QR-code.png"); anything else is a plain
    substring (so "QR" or ".png" still work). Shared by the message-level
    attachment condition and the per-file "save only" filter (Issu 2026-08-01)."""
    name = (name or "").lower()
    pattern = (pattern or "").strip().lower()
    if not pattern:
        return True
    if any(ch in pattern for ch in "*?"):
        import fnmatch
        return fnmatch.fnmatch(name, pattern)
    return pattern in name


def _rule_matches(rule: dict, msg: dict) -> bool:
    """Does an attachment auto-save rule apply to this message?

    Every filled-in criterion must match; empty ones are ignored. Beyond the
    sender there are now two CONTENT tests, because a bill is still a bill
    when it arrives from a new address:

      match_subject    — text in the subject line
      match_attachment — text in an attachment's FILENAME, e.g. "faktura"
                         or ".pdf". This is what makes a rule survive the
                         supplier changing their sending address, which the
                         sender-only version did not.
    """
    if not rule.get("enabled", True):
        return False
    mf = (rule.get("match_from") or "").strip().lower()
    if mf:
        hay = (msg.get("from", "") + " " + msg.get("from_name", "")).lower()
        if mf not in hay:
            return False
    ms = (rule.get("match_subject") or "").strip().lower()
    if ms and ms not in (msg.get("subject", "") or "").lower():
        return False
    ma = (rule.get("match_attachment") or "").strip().lower()
    if ma:
        names = [n.lower() for n in (msg.get("attachments") or [])]
        # A pattern with * or ? is treated as a wildcard (so "*.png" matches
        # every PNG); anything else is a plain substring (so ".png" or
        # "faktura" still work exactly as before).
        if any(ch in ma for ch in "*?"):
            import fnmatch
            if not any(fnmatch.fnmatch(n, ma) for n in names):
                return False
        elif not any(ma in n for n in names):
            return False
    acct = (rule.get("account") or "").strip()
    if acct and acct != msg.get("account_email", ""):
        return False
    # A rule with NO criteria at all would grab every attachment from every
    # message — almost certainly not what was meant, so it is inert.
    if not (mf or ms or ma or acct):
        return False
    return True


def _autosave_run(messages, store: dict) -> list:
    """Save attachments for messages matching any rule. Idempotent (skips a
    file that already exists with the same size). Returns list of saved paths."""
    default_dir = (store.get("default_dir") or "").strip()
    rules = store.get("rules", [])
    if not default_dir or not rules:
        return []
    saved = []
    for msg in messages:
        data_map = msg.get("_attachment_data") or {}
        if not data_map:
            continue
        rule = next((r for r in rules if _rule_matches(r, msg)), None)
        if rule is None:
            continue
        # Resolve target directory
        mode = (rule.get("subfolder") or "common").strip()
        if mode in ("", "common"):
            target_dir = default_dir
        elif mode == "per_sender":
            sender = (msg.get("from_name") or msg.get("from") or "unknown")
            target_dir = os.path.join(default_dir, _safe_name(sender))
        else:
            # Any other value is a TOKEN PATH, e.g. "{YYYY}/{MM}" or
            # "{YYYY-MM}" — expanded against the message date and split into
            # real sub-directories, which are created automatically. This is
            # how mail from several accounts lands in month/year folders.
            expanded = _expand_prefix(mode, msg)
            parts = [_safe_name(p) for p in _re.split(r"[\\/]+", expanded)
                     if p.strip()]
            target_dir = (os.path.join(default_dir, *parts) if parts
                          else default_dir)
        try:
            os.makedirs(target_dir, exist_ok=True)
        except Exception as e:
            log.warning("autosave: cannot create %s: %s", target_dir, e)
            continue
        prefix = _expand_prefix(rule.get("prefix", ""), msg)
        # "Save only" — restrict to attachments whose FILENAME matches, so a
        # rule can grab just the *QR* PNGs and ignore the other files on the
        # same message (Issu 2026-08-01). Empty = save every attachment.
        save_only = (rule.get("save_only") or "").strip()
        for fname, payload in data_map.items():
            if not payload:
                continue
            if save_only and not _fname_match(fname, save_only):
                continue
            out_name = _safe_name(prefix + fname)
            out_path = os.path.join(target_dir, out_name)
            try:
                if (os.path.isfile(out_path) and
                        os.path.getsize(out_path) == len(payload)):
                    continue   # already saved — idempotent
                with open(out_path, "wb") as f:
                    f.write(payload)
                saved.append(out_path)
                log.info("autosave: wrote %s", out_path)
            except Exception as e:
                log.warning("autosave: failed %s: %s", out_path, e)
    return saved


# ******************************************************************************
# DEL 04d — PERSISTENT STORES: signatures, templates, filters, snooze,
#           block list, outbox (send later / undo send) and drafts
# ******************************************************************************
#
# Every store lives in Helpfiles/Accounts/ next to the ones that already
# existed, EXCEPT drafts, which get their own folder because there is one file
# per unsent message. All of them are plain JSON so they can be inspected,
# hand-edited or copied to another machine — nothing here is secret (app
# passwords stay in accounts.json, DPAPI-encrypted).
#
# Each store follows the exact same shape as the older ones: a _load_x() that
# never raises and always returns a dict with its keys present, and a
# _save_x() that creates the folder first. That way a corrupt or missing file
# degrades to "empty" instead of taking the program down.

import uuid as _uuid
import zipfile
import zlib                 # the PDF reader in DEL 09m unpacks content streams
import shutil
import webbrowser
import urllib.parse as _urlparse
from datetime import timedelta

_DRAFTS_DIR = os.path.join(_FM_DIR, "Drafts")


def _now_iso() -> str:
    """Local wall-clock time as ISO — used for every timestamp in the stores."""
    return datetime.now().isoformat(timespec="seconds")


def _parse_iso(value: str):
    """Parse one of our ISO timestamps back to a datetime, or None."""
    try:
        return datetime.fromisoformat(value)
    except Exception:
        return None


def _parse_msg_dt(value: str):
    """Parse a MESSAGE's date (msg["_dt"]) as a NAIVE local datetime.

    A message's date comes from the Date: header and therefore carries a
    timezone offset, while everything this program generates — reminders,
    snoozes, plans — is naive local time. Subtracting one from the other
    raises "can't subtract offset-naive and offset-aware datetimes", which is
    exactly the kind of bug that only shows up on real mail and never on
    hand-written test data. So: convert to local time, then drop the offset.
    Use THIS for anything that compares a message date with datetime.now()."""
    dt = _parse_iso(value)
    if dt is None:
        return None
    if dt.tzinfo is not None:
        try:
            dt = dt.astimezone()
        except Exception:
            pass
        dt = dt.replace(tzinfo=None)
    return dt


def _new_id() -> str:
    return _uuid.uuid4().hex[:12]


def _load_json_store(path: str, defaults: dict, what: str) -> dict:
    """Shared body of every _load_x() below."""
    try:
        if os.path.isfile(path):
            with open(path, "r", encoding="utf-8") as f:
                data = json.load(f)
            if not isinstance(data, dict):
                raise ValueError("not a JSON object")
            for k, v in defaults.items():
                data.setdefault(k, v() if callable(v) else v)
            return data
    except Exception as e:
        log.warning("Could not load %s: %s", what, e)
    return {k: (v() if callable(v) else v) for k, v in defaults.items()}


def _save_json_store(path: str, store: dict, what: str):
    """Shared body of every _save_x() below. Writes via a temporary file and
    replaces the real one, so a crash mid-write can never leave a half-written
    (unreadable) store behind — important for the outbox, which is written
    every time a message is queued or sent."""
    try:
        os.makedirs(os.path.dirname(path), exist_ok=True)
        tmp = path + ".tmp"
        with open(tmp, "w", encoding="utf-8") as f:
            json.dump(store, f, indent=2)
        os.replace(tmp, path)
    except Exception as e:
        log.warning("Could not save %s: %s", what, e)


# ── Signatures ────────────────────────────────────────────────────────────────
# {"signatures": [{"name": "Private", "text": "..."} , ...],
#  "assign":     {"me@gmail.com": "Private", "work@gmail.com": "Private"}}
#
# The assignment is account -> signature NAME (not a copy of the text), which
# is exactly what makes several accounts able to share one signature: edit the
# signature once and every account pointing at it changes too.
_SIGNATURES_F = os.path.join(_ACCOUNTS_DIR, "signatures.json")

def _load_signatures() -> dict:
    return _load_json_store(_SIGNATURES_F,
                            {"signatures": list, "assign": dict}, "signatures")

def _save_signatures(store: dict):
    _save_json_store(_SIGNATURES_F, store, "signatures")

def _signature_for(store: dict, account_email: str) -> str:
    """Return the signature TEXT assigned to an account, or ''."""
    name = (store.get("assign") or {}).get(account_email or "", "")
    if not name:
        return ""
    for s in store.get("signatures", []):
        if s.get("name") == name:
            return s.get("text", "") or ""
    return ""


# ── Templates (canned replies) ────────────────────────────────────────────────
# {"templates": [{"name": ..., "subject": ..., "body": ...}, ...]}
# subject/body accept the same {tokens} as the attachment auto-save rules.
_TEMPLATES_F = os.path.join(_ACCOUNTS_DIR, "templates.json")

def _load_templates() -> dict:
    return _load_json_store(_TEMPLATES_F, {"templates": list}, "templates")

def _save_templates(store: dict):
    _save_json_store(_TEMPLATES_F, store, "templates")


# ── Snippets (short "often-used text", DEL 04d2) ──────────────────────────────
# {"snippets": [{"id": ..., "name": ..., "text": ...}, ...],
#  "slot1": "<id>", "slot2": "<id>"}
#
# Issu 2026-09-01: "Sådant som inte ska vara i alla meddelande men i flera" —
# his mail address, a payment-details block, a sign-off. Deliberately NOT the
# same thing as a TEMPLATE: a template is a whole message (it fills the
# Subject too and is meant to start one), a snippet is a scrap dropped in at
# the caret in the middle of something you are already writing. Keeping them
# apart also keeps his template list from filling up with one-liners.
#
# ONE list, and the two one-click buttons just point into it by id — so a
# snippet can be reached from the ▾ menu as well as from its button, and
# reordering or renaming never breaks the buttons.
_SNIPPETS_F = os.path.join(_ACCOUNTS_DIR, "snippets.json")

def _load_snippets() -> dict:
    return _load_json_store(_SNIPPETS_F, {"snippets": list}, "snippets")

def _save_snippets(store: dict):
    _save_json_store(_SNIPPETS_F, store, "snippets")

def _snippet_by_id(store: dict, sid: str):
    """The snippet record with this id, or None. Ids are stable; names are not."""
    if not sid:
        return None
    for s in (store.get("snippets") or []):
        if s.get("id") == sid:
            return s
    return None

def _snippet_spaced(text: str, before: str, after: str, want: bool = True) -> str:
    """The snippet text with a space added where it would otherwise run into
    the word next to it (Issu 2026-09-01: "issusbarn@gmail.comoch").

    Pure, so the rule can be tested without a window. It only ever ADDS a
    single space, and only when all three are true on that side: the tick-box
    is on, there IS a neighbouring character, and neither it nor the snippet's
    own edge is already whitespace. A snippet that starts or ends with a
    newline is a BLOCK (a sign-off, payment details) and is left alone by that
    same rule — its own newline is the whitespace.

    `before`/`after` are the single characters either side of the caret, or ""
    at the very start/end of the box."""
    if not want or not text:
        return text
    if (before and not before.isspace()
            and text[:1] and not text[:1].isspace()):
        text = " " + text
    if (after and not after.isspace()
            and text[-1:] and not text[-1:].isspace()):
        text = text + " "
    return text

def _snip_preview(rec: dict, limit: int = 220) -> str:
    """The snippet's text, short enough for a tooltip or a list row."""
    txt = (rec or {}).get("text") or ""
    return txt if len(txt) <= limit else txt[:limit - 1] + "…"

def _snippet_button_label(store: dict, slot: str, fallback: str) -> str:
    """What the one-click button says: the snippet's own name when the slot is
    filled, otherwise "Add 1"/"Add 2". Trimmed hard — this sits in a toolbar,
    and a 40-character name would push everything else off the edge."""
    rec = _snippet_by_id(store, store.get(slot) or "")
    if not rec:
        return fallback
    name = (rec.get("name") or "").strip() or fallback
    return name if len(name) <= 14 else name[:13] + "…"


# ── Mail filters (Phase-1-safe, applied to every fetched message) ─────────────
# {"filters": [{
#     "id": ..., "name": ..., "enabled": True,
#     "match_from": "", "match_to": "", "match_subject": "", "match_body": "",
#     "match_folder": "",            # "" = every folder
#     "has_attachment": False,       # True = only messages with attachments
#     "action_color": "",            # "#rrggbb" tint for the list row
#     "action_read":   False,        # mark read LOCALLY (never on Gmail)
#     "action_hide":   False,        # keep out of the message list
#     "action_star":   False,        # star LOCALLY
#     "action_snooze_min": 0,        # >0 = snooze that many minutes on arrival
#     "action_notify": "default",    # "default" | "always" | "never"
#  }, ...]}
_FILTERS_F = os.path.join(_ACCOUNTS_DIR, "filters.json")

_FILTER_DEFAULTS = {
    "id": "", "name": "", "enabled": True,
    # Multi-row conditions (DEL 04z): [{field, op, value}, …] + how they combine.
    "conditions": None,           # None = derive from the legacy fields below
    # "any" by default (Issu 2026-08-01): a junk-cleanup rule is usually a list
    # of senders/subjects where matching ANY one should fire.
    # "groups" — the conditions carry their own section (see _split_conditions)
    # "every"  — match every message, ignore the conditions.
    # "all" / "any" are the pre-2026-08-03 whole-rule modes; _load_filters
    # migrates them into per-condition sections on the way in, and
    # _split_conditions still reads them correctly if one ever slips past.
    "match_mode": "groups",
    "match_from": "", "match_to": "", "match_subject": "", "match_body": "",
    "match_folder": "", "has_attachment": False,
    # How each text criterion is compared (DEL 04x). Default "contains" =
    # exactly the old behaviour, so filters written before this keep working.
    "op_from": "contains", "op_subject": "contains", "op_body": "contains",
    # Auto = checked whenever new mail arrives (and on a manual run). When
    # False the rule only runs when you press "Run filters now".
    "run_on_fetch": True,
    # Extra automatic triggers (DEL 04z2), on top of run_on_fetch:
    "run_on_archive": False,   # run when a message is archived out of the inbox
    "run_on_sent":    False,   # run over a message right after it is sent
    # Run-on-a-chosen-folder (DEL 04z2): comma-separated folder names the rule
    # is restricted to. Empty = every folder. A rule is simply skipped for any
    # message whose folder is not in this list — a scope, not a match test, so
    # it stacks on top of the conditions.
    "run_folders": "",
    # For this account only (Issu 2026-08-15): every rule runs on every
    # account by default — a shipping-receipt rule SHOULD catch that mail
    # wherever it lands. Set this to one account's email to restrict the
    # rule to it alone, the same kind of scope as run_folders but for
    # accounts instead of folders.
    "match_account": "",
    "action_color": "", "action_read": False, "action_hide": False,
    "action_unread": False,  # keep/mark unread LOCALLY (Thunderbird parity; on
                             # an auto-run rule this holds matching mail unread)
    "action_star": False, "action_snooze_min": 0, "action_notify": "default",
    "action_tag": "",        # tag id to put on anything this rule matches
    # ── Unsubscribe from what this rule catches (DEL 04e2, Issu 2026-08-29) ──
    # "Jag har auto-trash på den; det hade varit gott om jag även kunnat välja
    # avregistrera... för de fall som det finns med länk för sådant."
    #
    # ""      off — what every existing rule does, and the default.
    # "offer" the rule puts the list on the unsubscribe QUEUE and contacts
    #         nobody. You clear the queue in one pass (Tools ▸ Unsubscribes
    #         waiting). This is the recommended setting and what the editor
    #         picks for you.
    # "auto"  the rule performs the unsubscribe by itself, WITHOUT asking —
    #         but only through a route the sender declared in a header:
    #         RFC 8058 one-click, or the List-Unsubscribe mailto:. A link
    #         merely scraped out of the message body is never fired
    #         automatically; that one is this program guessing, and guessing
    #         is not something to do unattended against somebody else's
    #         server. Such a message drops back to the queue and says so.
    #
    # Either way the unsubscribe LOG (_UNSUB_F) is checked first, so a list
    # you have already left is never asked to stop twice — a newsletter keeps
    # arriving for days afterwards, and a rule that re-fired on every one of
    # those would look exactly like a rule that does not work.
    "action_unsub": "",
    "action_spam": False,    # mark matching mail as spam (local flag + hidden)
    "action_spam_domain": False,  # also block the WHOLE sending domain (ignore
                                  # the local part before @) — future mail from
                                  # anyone at that domain is auto-spammed
    # ── SERVER-side actions (DEL 04y) — real changes on Gmail, so they run
    # ONLY when allow_server_changes is on. Off by default; each is logged.
    "action_move":        "",     # target Gmail folder/label ("" = off)
    "action_move_account": "",    # move to a folder on ANOTHER account ("" =
                                  # same account as the message). Cross-account
                                  # is an APPEND to that account + trash source.
    # Protect destination folder (Issu 2026-08-15), default ON: the moment a
    # rule with a move destination is saved (and again whenever it actually
    # moves mail there), that destination folder is added to
    # cfg["protected_folders"] — see _ensure_protected. So filed mail stays
    # filed even if a later rule, or the month-folder sweep, would otherwise
    # have picked it back up. Uncheck only for a destination you WANT other
    # automatic moves to keep touching.
    "action_protect_dest": True,
    "action_trash":       False,  # move matching mail to the Gmail Trash
    "action_seen_server": False,  # add \Seen on Gmail (syncs "read" to phone)
    "action_flag_server": False,  # add \Flagged (star) on Gmail
    # Rescue from Trash (Issu 2026-08-06, corrected 2026-08-15): some mail
    # (Tradera/DHL/PostNord shipping notes on certain accounts) arrives in
    # Gmail's own Trash before this program ever sees it — nothing here put
    # it there, so nothing here can stop Gmail doing it in the first place.
    # What this DOES do is notice it immediately and deliver it straight to
    # THIS rule's own destination — the same account_move/action_move_account
    # the rest of the rule already uses — in one hop, instead of parking it
    # in Inbox and hoping a later check finishes the job.
    #   • Same-account destination: an ordinary move, Trash → target folder.
    #     Nothing special — Trash is exactly as safe to move out of as any
    #     other folder, so this is really just the normal action running one
    #     pass earlier than it otherwise would.
    #   • Cross-account destination: a copy is appended to the target
    #     account/folder — but ONLY after checking (by Message-ID) that a
    #     copy is not already sitting there. The Trash original is left
    #     alone: _imap_trash_message refuses to re-delete an already-trashed
    #     source, and this program never permanently erases mail
    #     automatically, so there is nothing further to do to it — it ages
    #     out of Gmail's own Trash on its own 30-day timer. The Message-ID
    #     check is what stops the SAME message being re-copied on every
    #     later poll while its Trash copy still exists.
    "action_rescue_trash": False,

    # ── WAIT BEFORE ACTING (Issu 2026-08-17) ─────────────────────────────────
    # "Jag vill ha en möjlighet att göra delay på filterregler. Det ska vara
    # undantag men möjligt. T.ex. 'I'm interested in…'-mailen från/via BGG. De
    # kan med fördel skickas till Temporär/Köpare, efter 26 timmar."
    #
    # THE DELAY IS A MATCH CONDITION, NOT A QUEUE. The rule simply does not
    # match a message younger than `delay_min`; on a later pass the same
    # message is old enough and the rule fires normally. Nothing is written
    # down, nothing has to be replayed, and there is no pending job pointing at
    # mail that has meanwhile been read, moved or deleted by hand — the rule is
    # re-judged against the real state of the mailbox every time. It survives a
    # restart for free, and a week with the program closed simply means
    # everything now overdue is filed on the next check.
    #
    # Measured from the message's OWN date (its Date: header, via
    # _parse_msg_dt), not from when this program first saw it, so "after 26
    # hours" means 26 hours after the buyer wrote — the thing he is actually
    # counting from. A message with no readable date acts at once and says so;
    # a rule that silently never fires would be the worse failure.
    #
    # 0 = act immediately, which is what every existing rule does and stays
    # doing — this is deliberately an exception ("undantag men möjligt").
    "delay_min": 0,
    # A delayed rule may not mark anything read ("MEN, där så måste alla
    # olästa kvarstå som olästa"). With this on — the default whenever a delay
    # is set — the rule's own mark-read actions are refused, and the mail it
    # files is exempt from the destination folder's auto-read property. It
    # never makes READ mail unread again: what is unread stays unread, until
    # he opens it himself.
    "delay_keep_unread": True,
}

def _split_protected(groups: dict, is_protected) -> tuple:
    """Split {(account, folder): [msgs]} into what may be moved and what is
    protected.

    Pulled out as its own function because the promise "nothing automatic
    moves mail out of a protected folder" is now made in TWO places — the
    filter dispatcher and the whole-mailbox sweep — and a promise implemented
    twice is a promise that will eventually be kept only once.

    `is_protected(account, folder) -> bool`."""
    allowed, blocked = {}, {}
    for key, msgs in (groups or {}).items():
        acct, folder = key
        try:
            stop = bool(is_protected(acct, folder))
        except Exception:
            stop = False
        (blocked if stop else allowed)[key] = msgs
    return allowed, blocked


def _folder_norm(name: str) -> str:
    """A folder path reduced to something two names can be COMPARED by.

    The same folder reaches this code under three different spellings: the raw
    modified-UTF-7 IMAP name a message carries ("INBOX/Tempor&AOQ-r/0---Frakt
    &- Kvitto"), the decoded path a rule stores ("INBOX/Temporär/0---Frakt &
    Kvitto"), and whatever separator the server uses. Decode, unify the
    separator, drop a trailing one, casefold."""
    s = (name or "").strip().strip('"')
    if not s:
        return ""
    try:
        s = _imap_utf7_decode(s)
    except Exception:
        pass
    s = s.replace("\\", "/").replace(".", "/") if "/" not in s and "." in s \
        else s.replace("\\", "/")
    return s.strip("/").casefold()


def _already_filed_there(msg_folder: str, target: str) -> bool:
    """Is the message ALREADY at `target`, or inside a sub-folder of it?

    Issu 2026-08-08, the regression that undid his month folders: his shipping
    rules move mail to "INBOX/Temporär/0---Frakt & Kvitto". Once the mail had
    been filed on into ".../0---Frakt & Kvitto/2026-08", opening that month
    folder ran the rules over it again on fetch — they still matched (the
    sender has not changed) — and moved every message straight back UP to the
    parent. "Jag kollade i augustikatalogen, och där fanns mail, i 1 sekund…
    innan de försvann."

    A move to where the message already is, is not a move; it is the mail
    hopping about for nothing. Sub-folders count as "already there" because
    filing deeper is a deliberate act — by you, or by the month filer — and a
    rule aimed at the parent has no business undoing it."""
    cur = _folder_norm(msg_folder)
    tgt = _folder_norm(target)
    if not cur or not tgt:
        return False
    return cur == tgt or cur.startswith(tgt + "/")


# The server-side filter actions, in one place so the engine, the log and the
# "does this rule touch Gmail?" check all agree.
_SERVER_ACTION_KEYS = ("action_move", "action_trash",
                       "action_seen_server", "action_flag_server",
                       "action_rescue_trash")

def _filter_has_server_action(flt: dict) -> bool:
    return bool((flt.get("action_move") or "").strip()
                or flt.get("action_trash")
                or flt.get("action_seen_server")
                or flt.get("action_flag_server")
                or flt.get("action_rescue_trash"))

# The comparison operators offered per text criterion (Thunderbird-style).
_FILTER_OPS = ["contains", "not_contains", "is", "is_not", "begins", "ends"]
_FILTER_OP_LABELS = {
    "contains": "contains", "not_contains": "doesn't contain",
    "is": "is", "is_not": "is not",
    "begins": "begins with", "ends": "ends with",
}

def _op_match(op: str, hay: str, needle: str) -> bool:
    """Compare one field with one operator. An EMPTY needle always matches
    (the criterion is simply not in use)."""
    needle = (needle or "").strip().lower()
    if not needle:
        return True
    hay = (hay or "").lower()
    h = hay.strip()
    if op == "not_contains":
        return needle not in hay
    if op == "is":
        return h == needle
    if op == "is_not":
        return h != needle
    if op == "begins":
        return h.startswith(needle)
    if op == "ends":
        return h.endswith(needle)
    return needle in hay            # "contains" (default)

def _load_filters() -> dict:
    store = _load_json_store(_FILTERS_F, {"filters": list}, "mail filters")
    # Fill in keys added by later versions so old files keep working.
    for f in store.get("filters", []):
        for k, v in _FILTER_DEFAULTS.items():
            f.setdefault(k, v)
        if not f.get("id"):
            f["id"] = _new_id()
        # Drop the old "Rule for " prefix from names ALREADY saved. New rules
        # stopped adding it on 2026-08-03, but Issu's thirteen existing rules
        # still carried it — and it ate the first nine characters of every name
        # in a 24-column list, which is exactly the part of an address you need
        # to tell two rules apart. Renaming one by hand still works.
        name = (f.get("name") or "")
        if name.startswith("Rule for "):
            f["name"] = name[len("Rule for "):].strip() or name
        # Migrate a pre-DEL-04z filter to the conditions model, once.
        if f.get("conditions") is None:
            f["conditions"] = _legacy_conditions(f)
            f.setdefault("match_mode", "all")
        # Migrate to condition SECTIONS (2026-08-03). A rule that was "match
        # all" becomes all-MUST rows; one that was "match any" becomes all
        # either/or rows. Both mean EXACTLY what they meant before — that is
        # the whole point — and match_mode then only ever says "every" or
        # "groups". "every" is left alone.
        mode = f.get("match_mode", "all")
        if mode in ("all", "any"):
            for c in f.get("conditions") or []:
                c.setdefault("group", "any" if mode == "any" else "all")
            f["match_mode"] = "groups"
    return store

def _save_filters(store: dict):
    _save_json_store(_FILTERS_F, store, "mail filters")


# ── Block list (local; "unsubscribe + block sender") ──────────────────────────
# {"blocked": [{"match": "news@shop.com", "added": iso, "reason": ...}, ...]}
# Phase 1 CANNOT block anything on Gmail's side, so a blocked sender is simply
# hidden from every list here. Nothing is deleted and Refresh does not undo it.
_BLOCKLIST_F = os.path.join(_ACCOUNTS_DIR, "blocklist.json")

def _load_blocklist() -> dict:
    # "trusted" lives here too — it is the same kind of list (a local opinion
    # about a sender), just pointing the other way. "always_unread" as well:
    # senders whose mail should stay marked unread while it sits in an Inbox,
    # so it keeps standing out until you deal with it (Issu's request).
    return _load_json_store(_BLOCKLIST_F,
                            {"blocked": list, "spam": list, "trusted": list,
                             "always_unread": list},
                            "block list")

def _save_blocklist(store: dict):
    _save_json_store(_BLOCKLIST_F, store, "block list")

def _is_blocked(store: dict, msg: dict) -> bool:
    hay = (msg.get("from", "") + " " + msg.get("from_name", "")).lower()
    for b in store.get("blocked", []):
        m = (b.get("match") or "").strip().lower()
        if m and m in hay:
            return True
    return False

def _is_local_spam(store: dict, msg: dict) -> bool:
    hay = (msg.get("from", "") + " " + msg.get("from_name", "")).lower()
    for b in store.get("spam", []):
        m = (b.get("match") or "").strip().lower()
        if m and m in hay:
            return True
    return False

def _is_always_unread(store: dict, msg: dict) -> bool:
    """Should this sender's mail be kept marked unread while in an Inbox?"""
    hay = (msg.get("from", "") + " " + msg.get("from_name", "")).lower()
    for b in store.get("always_unread", []):
        m = (b.get("match") or "").strip().lower()
        if m and m in hay:
            return True
    return False


# ── Snooze (local "hide until") ───────────────────────────────────────────────
# {"snoozed": [{"key": <stable message key>, "until": iso, "subject": ...,
#               "from": ..., "account": ..., "folder": ...}, ...]}
_SNOOZE_F = os.path.join(_ACCOUNTS_DIR, "snooze.json")

def _load_snooze() -> dict:
    return _load_json_store(_SNOOZE_F, {"snoozed": list}, "snooze list")

def _save_snooze(store: dict):
    _save_json_store(_SNOOZE_F, store, "snooze list")


# ── Quick timers (DEL 04f3) — "stand up / oven off" countdowns ────────────────
# {"timers": [{"id": .., "label": .., "fire_at": iso}, ...]}. Persisted so an
# oven timer survives a restart (re-armed on start-up; one whose time passed
# while closed still fires once, so you are not left with a burnt dinner).
_TIMERS_F = os.path.join(_ACCOUNTS_DIR, "timers.json")

def _load_timers() -> dict:
    return _load_json_store(_TIMERS_F, {"timers": list}, "timers")

def _save_timers(store: dict):
    _save_json_store(_TIMERS_F, store, "timers")


# ── Hidden message parts (DEL 04t) ────────────────────────────────────────────
# Lets you fold away the parts of a message you have already dealt with, so a
# long mail collapses to just what is left to answer. Purely visual and 100%
# LOCAL — the text on Gmail is never touched, nothing is deleted, and one click
# brings any hidden part straight back. Keyed per message (_msg_key) so it
# survives a re-fetch; each entry is the list of exact substrings that were
# folded away for that message.
#   {"hidden": {"<msg key>": ["quoted signature", "handled paragraph", ...]}}
_HIDDENPARTS_F = os.path.join(_ACCOUNTS_DIR, "hidden_parts.json")

def _load_hidden_parts() -> dict:
    return _load_json_store(_HIDDENPARTS_F, {"hidden": dict},
                            "hidden message parts")

def _save_hidden_parts(store: dict):
    _save_json_store(_HIDDENPARTS_F, store, "hidden message parts")


def _segment_body(body: str, hidden_list: list):
    """Split the raw body into a run of ("text", str) / ("hidden", substr)
    segments, given the exact substrings the user chose to fold away.

    Every occurrence of a hidden substring is folded (hiding one quote of a
    repeated block hides them all — which is what you want for a signature or
    disclaimer that appears more than once)."""
    segments = [("text", body)]
    for h in hidden_list:
        if not h:
            continue
        newsegs = []
        for kind, val in segments:
            if kind != "text" or h not in val:
                newsegs.append((kind, val))
                continue
            parts = val.split(h)
            for i, p in enumerate(parts):
                if p:
                    newsegs.append(("text", p))
                if i < len(parts) - 1:
                    newsegs.append(("hidden", h))
        segments = newsegs
    return segments


# ==============================================================================
# DEL 04t2 — BOILERPLATE TRIMMING: text that is in EVERY mail from a sender
# ==============================================================================
#
# Issu 2026-08-16: "att kunna autodölja saker i meddelanden … Resten kommer i
# alla de meddelanden och kan döljas helt, alltid."
#
# DEL 04t already lets you select a piece of ONE message and fold it away. This
# is the standing version: a rule that folds the same boilerplate in every
# message that carries it, for ever, without being asked again.
#
# THREE PROPERTIES THAT ARE NOT NEGOTIABLE:
#
#   • DISPLAY ONLY. Nothing here touches msg["body"], the .eml on disk, or the
#     server. `_segment_body` (the existing renderer contract) is the only
#     consumer. That matters more than it looks: Tradera's footer carries
#     "Behåll detta i mailet när du svarar [[id:…]]" — hide that from the
#     screen and a REPLY must still contain it, or the reply is lost. It does,
#     because replies quote msg["body"] and this never edits it.
#   • ALWAYS REVERSIBLE, per message, in one click. A folded block leaves a
#     marker saying which rule hid it; clicking shows it again for that
#     message. The rule is not touched — undoing a rule is a separate,
#     deliberate act in the editor.
#   • NEVER GUESSES. A rule hides what it literally matches and nothing else.
#     A "hide everything after this line" rule (kind "tail") exists because
#     some footers really are terminal, but it is never the default: the BGG
#     block, for instance, has the seller's own notes AFTER the boilerplate,
#     so hiding the tail would eat real content. Line rules, not ranges.
#
# Rule shape (trim_rules.json):
#   {"id", "name", "enabled", "builtin",
#    "from_contains": "",        # scope; "" = every sender
#    "subject_contains": "",
#    "kind": "line" | "block" | "tail" | "strip" | "orphan",
#    "patterns": ["…", "…"],     # one rule can carry many lines
#    "end_pattern": "",          # "block" only
#    "regex": False}
#
#   line   — fold every LINE that contains (or matches) a pattern
#   block  — fold from a line matching a pattern to a line matching end_pattern
#   tail   — fold from the matching line to the end of the message
#   strip  — remove just the matched TEXT, keeping the rest of the line
#            (BBCode wrappers like [geekurl=…] … [/geekurl])
#   orphan — fold the matching line ONLY when nothing follows it (Issu
#            2026-08-17: "att det kan stå 'they wrote … but nothing'"). A reply
#            attribution — "On 27/02/2026 11:23, Lars Olsson wrote:" — is worth
#            reading when the quote it introduces is there, and is pure noise
#            when the quote is empty. One rule cannot tell those apart by the
#            line alone, so this kind looks at what comes AFTER it: the line
#            goes only if everything below is blank (bare "&gt;" quote markers
#            count as blank). Never a guess — if one word of the quote survived,
#            the attribution stays.
#
# LINKS ARE NEVER FOLDED BY ACCIDENT (Issu 2026-08-17: "just den länken vill jag
# kunna se"). A rule whose own patterns say nothing about links may not hide a
# line that carries one — see `_trim_rule_targets_links`. Tradera's rule DOES
# name its URLs, so it keeps working; a rule made from a selection can no longer
# take a link away with the boilerplate around it. cfg["trim_keep_links"].

_TRIM_F = os.path.join(_ACCOUNTS_DIR, "trim_rules.json")

_TRIM_KINDS = ("line", "block", "tail", "strip", "orphan")

_TRIM_DEFAULTS = {
    "id": "", "name": "", "enabled": True, "builtin": False,
    "from_contains": "", "subject_contains": "",
    "kind": "line", "patterns": [], "end_pattern": "", "regex": False,
}

# The rules shipped with the program, written from Issu's own mail. Seeded once
# per SEED VERSION (cfg["trim_seed_version"]); after that they are ordinary
# rules he can edit, disable or delete, and re-seeding never resurrects one he
# removed — a rule is only ever offered while its own "seed" number is newer
# than the version already recorded, so adding a built-in here reaches an
# existing installation exactly once and leaves every deletion standing.
_TRIM_SEED_VERSION = 2

_TRIM_BUILTINS = [
    {
        "id": "bgg-geekmarket",
        "name": "BoardGameGeek — GeekMarket standard paragraph",
        "from_contains": "boardgamegeek.com",
        "kind": "line",
        "patterns": [
            "The above message was sent regarding your GeekMarket Listing",
            "Reply to this message to work out any details of the sale",
            "Sellers shipping an item should use a method that provides",
            "If you sell the item go to",
            "contact form for additional help",
            "For reference, below is additional information from the listing",
        ],
    },
    {
        "id": "bgg-messagecenter",
        "name": "BoardGameGeek — MessageCenter footer (keeps the link)",
        "from_contains": "boardgamegeek.com",
        "kind": "line",
        # ONE line, and one line only. The footer is three lines:
        #
        #     This message was forwarded to you from the BoardGameGeek …
        #     Link to the original message:
        #     https://boardgamegeek.com/geekmail/message/137599071
        #
        # and the first build folded the middle one too, on the reasoning that
        # the URL underneath speaks for itself. It does not: a bare URL under a
        # fold marker reads as part of what was hidden, and Issu (2026-08-17)
        # reported the link as gone — "just den länken vill jag kunna se". The
        # label is what makes the URL a link to somewhere, so both stay. Only
        # the sentence that says nothing goes.
        "patterns": [
            "This message was forwarded to you from the BoardGameGeek",
        ],
    },
    {
        # Issu 2026-08-17: "och även att det kan stå 'they wrote … but
        # nothing'". His own mail has them — INBOX_Rail/179 ends on "On
        # 27/02/2026 11:23, Lars Olsson wrote:" and then simply stops, and a
        # Proton thread carries "…Lars Olsson <issusbarn@gmail.com> wrote:"
        # over an empty quote. Kind "orphan", so the SAME line is left alone
        # whenever the quote it introduces actually arrived.
        #
        # Not scoped to a sender on purpose: an empty attribution is noise
        # whoever sends it. Scoping one to a single sender is two clicks away
        # (right-click the line → "Never show this line again…"), which is what
        # "eller från avsändare-X-specifikt" asks for.
        "id": "empty-attribution",
        "seed": 2,
        "name": "“… wrote:” with nothing under it",
        "kind": "orphan",
        "regex": True,
        # Swedish "skrev:" too — the mail is his, not the program's, and mail
        # from a Swedish client says skrev. (This is a PATTERN, not program
        # text: nothing here is ever shown on screen.)
        "patterns": [
            r"wrote\s*:\s*$",
            r"skrev\s*:\s*$",
        ],
    },
    {
        "id": "bgg-bbcode",
        # No brackets in the NAME: it is printed inside the fold markers, and
        # "[geekurl]" sitting in a marker reads as leaked markup.
        "name": "BoardGameGeek — quote and link tags (keeps the words)",
        "from_contains": "boardgamegeek.com",
        "kind": "strip",
        "regex": True,
        # The opening bracket is OPTIONAL on the quote tags. That is not
        # defensive programming, it is his actual mail: message 99110 contains
        # a bare  q="Hyperides"]  with the "[" missing, alongside two
        # well-formed ones. BGG mangles its own markup, so the rule matches
        # what arrives rather than what the format says should arrive.
        "patterns": [
            r"\[geekurl=[^\]]*\]", r"\[/geekurl\]",
            r"\[?q=\"[^\"]*\"\]", r"\[/q\]",
        ],
    },
    {
        # Issu 2026-08-16: "Tradera har jobbiga mail... inte mycket är
        # specifikt för mitt spel där." Correct — a "din vara är såld" mail is
        # mostly shop navigation, social icons and app-store links, all of it
        # identical in every message. What IS specific survives untouched: the
        # headline, "Ordernummer …", the item title and its link, Objektnr,
        # the price, the shipping line, and "Kontakta köparen".
        #
        # Anchored with ^\s* on purpose. A bare tracking URL sitting on its own
        # line is navigation; the SAME URL in parentheses after the item title
        # is the link to your own sale, and hiding that would be wrong. The
        # anchor is what tells them apart. (\s covers \xa0, which these mails
        # are full of.)
        "id": "tradera-navigation",
        "name": "Tradera — shop navigation, social and app links",
        "from_contains": "tradera.com",
        "kind": "line",
        "regex": True,
        "patterns": [
            r"^\s*Skapa annons \(https://www\.tradera\.com/selling",
            r"^\s*Minneslista \(https://www\.tradera\.com/my/wish-list",
            r"^\s*Inspiration \(https://www\.tradera\.com/inspiration",
            r"^\s*Kundservice \(https://info\.tradera\.com",
            r"^\s*Hantera dina e-postinställningar \(",
            r"^\s*https://www\.tradera\.com/open/\?utm_source=",
            r"^\s*https://www\.tradera\.com/item/\S+utm_source=",
            r"^\s*https://www\.facebook\.com/Tradera",
            r"^\s*https://tiktok\.com/@tradera",
            r"^\s*https://instagram\.com/tradera",
            r"^\s*https://www\.linkedin\.com/company/tradera",
            r"^\s*https://itunes\.apple\.com/se/app/tradera",
            r"^\s*https://play\.google\.com/store/apps/details\?id=com\.tradera",
        ],
    },
    {
        "id": "tradera-footer",
        "name": "Tradera — standard footer",
        "from_contains": "tradera.com",
        "kind": "line",
        "regex": True,
        "patterns": [
            r"^Gå till Tradera för att svara",
            r"^Det här mailet får du eftersom du är medlem",
            r"^Behåll detta i mailet när du svarar",
            r"^©\s*\d{4}\s+Tradera",
        ],
    },
]


def _load_trim_rules() -> dict:
    store = _load_json_store(_TRIM_F, {"rules": list}, "message trim rules")
    for r in store.get("rules", []):
        for k, v in _TRIM_DEFAULTS.items():
            r.setdefault(k, v() if callable(v) else v)
        if not r.get("id"):
            r["id"] = _new_id()
        if isinstance(r.get("patterns"), str):      # hand-edited file
            r["patterns"] = [p for p in r["patterns"].splitlines() if p.strip()]
    return store


def _save_trim_rules(store: dict):
    _save_json_store(_TRIM_F, store, "message trim rules")


def _seed_trim_rules(store: dict, since: int = 0) -> int:
    """Add any built-in rule not already present, BY ID. Returns how many were
    added.

    `since` is the seed version this installation has already been offered
    (cfg["trim_seed_version"]). Only built-ins NEWER than that are considered,
    which is what keeps a deleted rule deleted: version 1's rules are never
    offered again to someone who already saw version 1, however many versions
    come after it."""
    have = {r.get("id") for r in store.get("rules", [])}
    added = 0
    for b in _TRIM_BUILTINS:
        if int(b.get("seed", 1)) <= int(since) or b["id"] in have:
            continue
        rec = dict(_TRIM_DEFAULTS)
        rec.update(b)
        rec.pop("seed", None)          # bookkeeping, not part of a rule
        rec["builtin"] = True
        store.setdefault("rules", []).append(rec)
        added += 1
    return added


# A shipped rule that turned out to hide something it should have kept cannot
# be fixed by editing _TRIM_BUILTINS alone: the copy that matters is the one
# already sitting in his trim_rules.json, seeded months ago. Each entry here is
# {rule id: [patterns to drop]}, applied ONCE (gated by the same seed version),
# and only to a rule still marked builtin — a pattern he typed himself is his.
_TRIM_REPAIRS = {
    # 2026-08-17: this hid the "Link to the original message:" label as well as
    # the sentence above it, which left the geekmail URL orphaned under a fold
    # marker and reading as hidden. See the built-in's own comment.
    "bgg-messagecenter": ["Link to the original message:"],
}


def _repair_trim_rules(store: dict) -> int:
    """Drop patterns a shipped rule should never have carried. Returns how many
    rules were changed. A rule left with no patterns at all is switched off
    rather than deleted, so nothing vanishes behind his back."""
    changed = 0
    for r in store.get("rules", []):
        drops = _TRIM_REPAIRS.get(r.get("id"))
        if not drops or not r.get("builtin"):
            continue
        keep = [p for p in (r.get("patterns") or []) if p not in drops]
        if len(keep) != len(r.get("patterns") or []):
            r["patterns"] = keep
            if not keep:
                r["enabled"] = False
            changed += 1
    return changed


def _collapse_blank_runs(text: str, keep: int = 1) -> str:
    """Squeeze a run of blank lines down to `keep` of them.

    Issu 2026-08-16: "det kanske borde vara en generell dölja-regel, att fler
    än 2 tomma rader visas som 1 tom rad". It should, and as a general rule
    rather than a per-sender one — the gaps come from HTML table layout, so
    every sender that builds mail that way produces them.

    A line counts as blank when it holds nothing but whitespace, non-breaking
    spaces included (they are exactly what made these lines look blank while
    testing as full). DISPLAY ONLY, like everything else in DEL 04t2: the
    caller applies it to the text it is about to draw, never to msg["body"]."""
    if not text:
        return text
    out, blanks = [], 0
    for line in text.split("\n"):
        if not line.strip().strip("\xa0"):
            blanks += 1
            if blanks > keep:
                continue
            out.append("")
        else:
            blanks = 0
            out.append(line)
    return "\n".join(out)


def _trim_rule_applies(rule: dict, msg: dict) -> bool:
    """Is this rule in scope for this message? Sender/subject only — cheap, and
    checked before any pattern work is done."""
    if not rule.get("enabled", True):
        return False
    f = (rule.get("from_contains") or "").strip().lower()
    if f:
        hay = ((msg.get("from", "") or "") + " " +
               (msg.get("from_name", "") or "")).lower()
        if f not in hay:
            return False
    s = (rule.get("subject_contains") or "").strip().lower()
    if s and s not in (msg.get("subject", "") or "").lower():
        return False
    return True


def _trim_line_hit(line: str, patterns, use_regex: bool) -> bool:
    for p in patterns:
        if not p:
            continue
        try:
            if use_regex:
                if _re.search(p, line):
                    return True
            elif p.lower() in line.lower():
                return True
        except _re.error:
            continue            # a broken hand-typed regex never matches
    return False


def _trim_rule_targets_links(rule) -> bool:
    """Does this rule SAY it is about links?

    The test is deliberately crude — "http" or "www." somewhere in its own
    patterns — because it decides only one thing: whether the rule is allowed
    to fold a line that carries a URL. Tradera's navigation rule lists its URLs
    in full, so it passes and keeps working exactly as before. A rule built out
    of ordinary sentences does not, so it can never quietly take a link with
    the boilerplate around it."""
    for p in (rule.get("patterns") or []):
        low = (p or "").lower()
        if "http" in low or "www." in low:
            return True
    return bool((rule.get("end_pattern") or "").lower().count("http"))


def _trim_tail_is_empty(lines, i: int) -> bool:
    """Is there nothing but blank lines after line i?

    "Nothing" means nothing a reader would call text: whitespace, non-breaking
    spaces, and bare quote markers ("&gt;", "&gt; &gt;") — an empty quote is
    still an empty quote when the client indented it. One real word anywhere
    below and the answer is no."""
    for ln in lines[i + 1:]:
        if _re.sub(r"[>\s\xa0]+", "", ln):
            return False
    return True


def _trim_hidden_parts(body: str, rules: list, msg: dict, keep_links: bool = True):
    """Work out what a set of rules would fold away in one message.

    Returns (parts, labels, silent):
      parts  — the exact substrings to hand to _segment_body, in body order
      labels — {substring: rule name}, so the marker can say WHAT hid it
      silent — the subset that should vanish WITHOUT leaving a marker

    `silent` is what "strip" rules produce, and it exists because the first
    build was unusable without it: a BGG mail carries a dozen [/q] and
    [geekurl=…] tags, each of which became its own "⟨1 line hidden — click to
    show⟩" marker. Fourteen markers in one message is not a tidier message. A
    markup tag is not content being kept from you — it is noise being cleaned
    — so it simply goes, and the message-level "↺ Show boilerplate" button
    still brings everything back at once.

    Pure: no Tk, no I/O, no mutation of `msg`. That is what makes it testable
    and what guarantees the body itself is never altered."""
    if not body or not rules:
        return [], {}, set()
    active = [r for r in rules if _trim_rule_applies(r, msg)]
    if not active:
        return [], {}, set()

    # ── Line spans over the ORIGINAL body, separators intact ────────────────
    # NOT body.splitlines() + "\n".join(). Real mail is CRLF; rejoining with
    # "\n" builds a string that is not a substring of the body at all, so
    # _segment_body finds nothing and the rule silently does nothing. That bug
    # made every "line" rule here a no-op on first test — the strip rules
    # worked only because they slice the body directly. Offsets cannot drift.
    spans = []                        # (start, end_of_text, end_with_newline)
    pos, n = 0, len(body)
    while pos < n:
        nl = body.find("\n", pos)
        if nl == -1:
            spans.append((pos, n, n))
            break
        text_end = nl
        if text_end > pos and body[text_end - 1] == "\r":
            text_end -= 1
        spans.append((pos, text_end, nl + 1))
        pos = nl + 1
    lines = [body[s:e] for s, e, _f in spans]

    # owner[i] = name of the rule folding line i, or None
    owner = [None] * len(lines)
    strips = []                       # (pattern, regex?, rule name)

    for r in active:
        pats = [p for p in (r.get("patterns") or []) if p.strip()]
        if not pats:
            continue
        kind = r.get("kind", "line")
        rx = bool(r.get("regex"))
        nm = r.get("name") or "rule"
        # A rule that does not mention links may not hide one (see the header
        # note). `linkable` is worked out once per rule, not per line.
        linkable = (not keep_links) or _trim_rule_targets_links(r)

        def _may_fold(text: str) -> bool:
            return linkable or not _URL_RE.search(text)

        if kind == "strip":
            strips.extend((p, rx, nm, linkable) for p in pats)
            continue
        for i, ln in enumerate(lines):
            if owner[i] is not None or not _trim_line_hit(ln, pats, rx):
                continue
            if kind == "line":
                if _may_fold(ln):
                    owner[i] = nm
            elif kind == "orphan":
                # Only when the quote it introduces never arrived.
                if _trim_tail_is_empty(lines, i) and _may_fold(ln):
                    owner[i] = nm
            elif kind == "tail":
                if not _may_fold(ln):
                    continue
                for j in range(i, len(lines)):
                    if owner[j] is None and _may_fold(lines[j]):
                        owner[j] = nm
                break
            elif kind == "block":
                if not _may_fold(ln):
                    continue
                end = (r.get("end_pattern") or "").strip()
                owner[i] = nm
                for j in range(i + 1, len(lines)):
                    if owner[j] is None and _may_fold(lines[j]):
                        owner[j] = nm
                    if end and _trim_line_hit(lines[j], [end], rx):
                        break

    # Contiguous folded lines become ONE part, so six boilerplate bullets
    # collapse to a single marker instead of six.
    parts, labels = [], {}
    i = 0
    while i < len(lines):
        if owner[i] is None:
            i += 1
            continue
        j = i
        while j + 1 < len(lines) and owner[j + 1] == owner[i]:
            j += 1
        # Sliced straight out of the body, so it is an exact substring whatever
        # the line endings are. Ends at the TEXT end of the last folded line,
        # leaving that line's newline visible — the folded block collapses to
        # one marker without welding the paragraphs around it together.
        chunk = body[spans[i][0]:spans[j][1]]
        if chunk.strip():
            parts.append(chunk)
            labels[chunk] = owner[i]
        i = j + 1

    # "strip" rules act on the text that SURVIVED, so a tag inside a folded
    # block is not reported twice. These are SILENT — see the docstring.
    silent = set()
    for pat, rx, nm, linkable in strips:
        try:
            hits = ([m.group(0) for m in _re.finditer(pat, body)] if rx
                    else ([pat] if pat in body else []))
        except _re.error:
            hits = []
        for h in hits:
            # A wrapper that turns out to hold a whole URL is left ON SCREEN
            # rather than removed silently: [geekurl=/market/product/…] is
            # markup, [geekurl=https://…] is an address, and "strip" hits leave
            # no marker behind to click. Ugly beats gone.
            if not h or h in labels:
                continue
            if keep_links and not linkable and _URL_RE.search(h):
                continue
            parts.append(h)
            labels[h] = nm
            silent.add(h)
    return parts, labels, silent


class _BoundedSet:
    """A set that forgets its OLDEST entries once it passes a cap.

    Three "have I already done this?" sets grow for as long as the program
    runs: the seen-messages set behind new-mail toasts, the filter-log dedupe,
    and the done-server-actions guard. Issu leaves this running for days with a
    check every minute, so all three creep upwards for ever — and the filter
    one is worse than untidy: `_filter_log` itself is trimmed to 500 entries
    while the set guarding it remembered everything, so the two disagreed about
    what had been seen (found by a static pass, 2026-08-08).

    Forgetting the oldest is safe for all three uses: an entry that has aged
    out refers to mail long gone from the fetch window, and every action it
    guards is checked again on its own merits before anything happens.

    Behaves like a set for the operations these callers use."""

    def __init__(self, cap=5000):
        self._cap = int(cap)
        self._d = {}                 # dict preserves insertion order

    def add(self, item):
        if item in self._d:
            return
        self._d[item] = None
        if len(self._d) > self._cap:
            # Drop the oldest tenth in one go — cheaper than one at a time,
            # and the exact boundary does not matter.
            for k in list(self._d)[:max(1, self._cap // 10)]:
                self._d.pop(k, None)

    def discard(self, item):
        self._d.pop(item, None)

    def clear(self):
        self._d.clear()

    def __contains__(self, item):
        return item in self._d

    def __len__(self):
        return len(self._d)

    def __iter__(self):
        return iter(self._d)


def _msg_key(msg: dict) -> str:
    """A key that survives a re-fetch. UIDs are unique per mailbox only, so we
    qualify them with the account and folder; when there is no UID (demo data)
    we fall back to sender+subject+date, which is stable enough for the local
    features that use it (snooze, seen-tracking)."""
    uid = msg.get("uid")
    if uid:
        return f"{msg.get('account_email','')}|{msg.get('_folder','')}|{uid}"
    return (f"{msg.get('account_email','')}|{msg.get('from','')}|"
            f"{msg.get('subject','')}|{msg.get('_dt','')}")


# ==============================================================================
# DEL 09p — PROTECTED MESSAGES ("✉🔒 Send and save")
# ==============================================================================
#
# Issu 2026-09-15: "en funktion där send-mailet blir skyddat så även om det
# hamnar i vanlig Sent-katalog, så raderas det inte om jag mängdmarkerar filer
# i send e.d.. Det ignoreras då. Jag måste markera sådana mail 'ett i taget'
# och får en popup om jag verkligen vill radera det."
#
# So a protected message means exactly two things, and deliberately nothing
# more than that:
#
#   • A delete that takes SEVERAL messages at once walks straight past it. No
#     question, no dialog — it is simply not in the batch. The status bar says
#     how many were left behind, because "some of them just didn't go" is the
#     kind of silence that turns a safety feature into a bug report.
#   • A delete that takes THAT ONE message on its own asks first, in a dialog
#     that also offers to take the protection off.
#
# The only way to lose one is therefore to single it out by hand and answer a
# question — which is the whole point. Ticking forty rows in Sent and pressing
# Delete must not be able to take the one mail you cannot afford to lose.
#
# WHERE THE MARK LIVES — in two places, on purpose:
#
#   1. IN THE MESSAGE. "Send and save" puts "X-Freemail-Protected: 1" in the
#      outgoing headers, and Gmail keeps custom headers on its own copy in
#      Sent. That mark survives a wiped settings folder, a fresh install, a
#      second machine — and, crucially, being MOVED, which is the one thing a
#      UID never survives.
#   2. IN protected.json, keyed on Message-ID. This is what lets you protect
#      mail that is ALREADY in the mailbox (right-click → 🔒 Protect), which
#      no outgoing header can ever do retroactively.
#
# Message-ID rather than _msg_key, for the same reason delivered.json uses it:
# a UID dies the instant the mail moves, and moving is exactly what happens to
# mail here. Demo messages have no Message-ID at all, so those fall back to
# _msg_key — good enough for something that never leaves the session.
_PROTECTED_F = os.path.join(_ACCOUNTS_DIR, "protected.json")

# The header name, in ONE place — it is written by _smtp_send and read back by
# _build_msg_dict, and the two must never drift apart.
_PROTECT_HEADER = "X-Freemail-Protected"


def _protect_id(msg: dict) -> str:
    """The key one message is remembered by: its Message-ID with the folding
    whitespace squeezed out, or — only when it has none — the local key."""
    mid = _re.sub(r"\s+", "", (msg.get("_message_id") or ""))
    return mid or ("key:" + _msg_key(msg))


def _load_protected() -> dict:
    """{"ids":    {protect_id: {"subject", "to", "when"}},
        "exempt": {protect_id: when}}

    `ids` is what was locked BY HAND. `exempt` is the opposite and exists for
    one reason: a "Send and save" mail carries its lock in its own headers on
    Gmail's server, and this program cannot rewrite a message sitting there.
    So "🔓 Unprotect" on one of those is remembered as an exception — without
    it the padlock would simply come back on the next fetch, and unprotecting
    would be a lie.

    The values under `ids` let a list say WHAT is protected without a round
    trip to the server; nothing depends on them."""
    store = _load_json_store(_PROTECTED_F,
                             {"ids": dict, "exempt": dict}, "protected")
    if not isinstance(store.get("ids"), dict):
        store["ids"] = {}
    if not isinstance(store.get("exempt"), dict):
        store["exempt"] = {}
    return store


def _save_protected(store: dict):
    _save_json_store(_PROTECTED_F, store, "protected")


def _protect_add(store: dict, key: str, subject="", to="", when=""):
    if not key:
        return
    store.setdefault("ids", {})[key] = {
        "subject": subject or "", "to": to or "", "when": when or _now_iso()}
    # Protecting again cancels any earlier release — otherwise a message let
    # go once could never be locked again, which is the sort of one-way door
    # that only shows up months later.
    store.setdefault("exempt", {}).pop(key, None)
    _save_protected(store)


def _protect_remove(store: dict, key: str) -> bool:
    """Take the lock off. Returns True if there was one to take off."""
    if (store.get("ids") or {}).pop(key, None) is not None:
        _save_protected(store)
        return True
    return False


def _is_protected_msg(store: dict, msg: dict) -> bool:
    """Is this message protected — by its own header, or by our ledger?

    A deliberate release wins over both, so "🔓 Unprotect" stays undone. Then
    the header, which needs nothing on disk: a "Send and save" mail is
    protected even where protected.json has never existed."""
    if not isinstance(msg, dict):
        return False
    key = _protect_id(msg)
    if key in (store.get("exempt") or {}):
        return False
    if str(msg.get("_protected_hdr") or "").strip():
        return True
    return key in (store.get("ids") or {})


# ==============================================================================
# DEL 04d-DELIVERED — "this message has already been delivered there" ledger
# ==============================================================================
#
# Issu 2026-08-16: "de skickas runt… blir kopior".
#
# A cross-account rule delivers a receipt to the Main account and trashes the
# source. The source then sits in the other account's Trash and keeps matching
# the very same rule on every single check, for ever — 144 such matches in one
# week of his activity log. The only thing standing between that and an endless
# stream of duplicates was a live IMAP question ("is it in the target folder
# already?"), which is both slow and wrong the moment the delivered copy is
# filed one level deeper into a month folder.
#
# So the answer is written down. One line per Message-ID that this program has
# EVER delivered to another account: what account, what folder, when. It is
# consulted before the network is, it survives a restart, and it means the
# promise "this program will not deliver the same message twice" is kept by
# something that remembers rather than by something that re-checks.
#
# Deliberately keyed on the Message-ID and NOT on the account/uid: a UID dies
# the instant the mail moves, which is precisely what happens here.
_DELIVERED_F = os.path.join(_ACCOUNTS_DIR, "delivered.json")

# The ledger is trimmed to this many entries (newest kept). Two years of Issu's
# shipping mail is a few thousand lines, so this never throws away anything
# that could still be matched by a rule.
_DELIVERED_MAX = 8000

# The ledger is read and written from the filter dispatcher's background
# thread while the GUI thread may be reading it too — one lock, so a delivery
# decision is never made against a half-written store.
_delivered_lock = threading.Lock()


# A folder whose name means "on its way out", not "filed". Compared
# lower-case, and the Swedish names are here because Gmail reports the
# LOCALISED label to a Swedish account ("[Gmail]/Papperskorgen").
_NOT_A_DELIVERY_FOLDERS = {
    "trash", "spam", "bin", "junk", "deleted", "deleted items",
    "papperskorgen", "papperskorg", "skräppost", "skrappost",
}


def _is_discard_folder(folder: str) -> bool:
    """Is this folder the Trash or the Spam pile (in any of the names Gmail
    uses for them)? A message sitting there has NOT been filed anywhere."""
    f = (folder or "").strip().lower()
    f = f.rsplit("/", 1)[-1]          # "[Gmail]/Papperskorgen" → the leaf
    return f in _NOT_A_DELIVERY_FOLDERS


def _delivered_heal(store: dict) -> int:
    """Throw out ledger entries that were never a delivery. Returns how many.

    Issu 2026-08-18 — this is the repair for the mess he found: "massvis av
    0---frakt & kvitto-mail i ALL Accounts Trash … varför skickas de inte
    enligt reglerna".

    The old cross-account move uploaded header-only copies, so ~80 hollow
    shells ended up in the target account and were then thrown away, which
    put them in its TRASH. On the next check _deliver_cross_account asked the
    account "is this Message-ID anywhere in you?", found the shell in Trash,
    called that "already delivered" and WROTE IT DOWN — permanently. From then
    on step 1 of the delivery answered "yes, done" without ever asking the
    server again, so:

      • the receipt was never filed in 0---Frakt & Kvitto,
      • the intact original sat in the source account's Trash ageing towards
        Gmail's 30-day purge,
      • and restoring one by hand changed nothing, because the very next
        filter run consulted the same poisoned entry and threw it back.

    A ledger row pointing at Trash/Spam is therefore not evidence of anything
    and is dropped, EXCEPT when it recorded that the copy it found had a real
    body (`intact: true`) — that one means "you deliberately threw this away",
    which is a decision worth keeping. Entries written before this field
    existed have no `intact` key at all, so they go: that is precisely the
    damaged set."""
    d = store.get("delivered") or {}
    bad = [k for k, v in d.items()
           if _is_discard_folder(v.get("folder", ""))
           and v.get("intact") is not True]
    for k in bad:
        d.pop(k, None)
    return len(bad)


def _load_delivered() -> dict:
    store = _load_json_store(_DELIVERED_F, {"delivered": dict},
                             "delivered-mail ledger")
    healed = _delivered_heal(store)
    if healed:
        log.warning("delivered-mail ledger: dropped %d entry/entries that "
                    "pointed at a Trash/Spam copy with no body — those were "
                    "never deliveries, and they were blocking the real "
                    "message from being filed. They will be delivered "
                    "properly on the next check.", healed)
        try:
            _save_delivered(store)
        except Exception as e:
            log.warning("Could not save the healed delivery ledger: %s", e)
    return store


def _save_delivered(store: dict):
    d = store.get("delivered") or {}
    if len(d) > _DELIVERED_MAX:
        # Newest kept — "when" is an ISO timestamp, so a plain sort is right.
        keep = sorted(d.items(), key=lambda kv: kv[1].get("when", ""),
                      reverse=True)[:_DELIVERED_MAX]
        store["delivered"] = dict(keep)
    _save_json_store(_DELIVERED_F, store, "delivered-mail ledger")


def _delivered_key(message_id: str, account: str) -> str:
    """One ledger key. The TARGET account is part of it on purpose: delivering
    the same receipt to two different accounts is a legitimate thing to ask
    for, and each destination gets its own once-only promise."""
    return f"{(message_id or '').strip()}|{(account or '').strip().lower()}"


def _delivered_already(store: dict, message_id: str, account: str) -> dict:
    """The ledger entry for this delivery, or {} if it never happened."""
    if not message_id:
        return {}
    with _delivered_lock:
        return (store.get("delivered") or {}).get(
            _delivered_key(message_id, account)) or {}


def _delivered_record(store: dict, message_id: str, account: str, folder: str,
                      subject: str = "", source: str = "", intact: bool = True):
    """Write down that this message reached that account. Called ONLY after a
    successful APPEND (or after finding the copy already sitting there), never
    optimistically — a delivery that failed must be free to try again.

    `intact` says whether the copy that is there actually has a body. A hollow
    one is NOT a delivery and is never written down (Issu 2026-08-18): writing
    it is what turned a repairable mess into a permanent one, because step 1
    of _deliver_cross_account then answered "already done" for ever without
    asking the server again. See _delivered_heal."""
    if not message_id:
        return
    if not intact:
        log.info("delivery NOT recorded for %r in %s/%s — that copy has no "
                 "body, so it does not count as delivered",
                 (subject or "")[:60], account, folder)
        return
    with _delivered_lock:
        store.setdefault("delivered", {})[
            _delivered_key(message_id, account)] = {
                "account": account, "folder": folder,
                "when": _now_iso(), "subject": (subject or "")[:120],
                "source": source, "intact": True,
            }
        _save_delivered(store)


# ── Smart Reply progress: "I am not finished answering this one" ──────────────
# Issu 2026-08-08: "Bra om det kan minnas vad jag har svarat på, ifall jag inte
# svarar hela meddelandet vid samma tillfälle."
#
# A long mail is often answered in two or three sittings. Everything you have
# typed — plus how you cut the message into paragraphs, plus which paragraphs
# you have set aside — is written here the moment you close the window, and
# read back the next time you open Smart Reply on the SAME message.
#
# Deliberately keyed on the Message-ID, not on _msg_key: the UID changes the
# instant a filter moves the mail to another folder or another account, and
# then the same message would look like a different one and your half-finished
# reply would be gone (which is exactly what his shipping-mail filters do).
_REPLY_PROGRESS_F = os.path.join(_ACCOUNTS_DIR, "reply_progress.json")

# How long an untouched, unsent draft answer is kept before the store tidies
# itself. A month is plenty for "I'll finish this at the weekend".
_REPLY_PROGRESS_DAYS = 30


def _reply_key(msg: dict) -> str:
    """A message identity that survives being MOVED.

    Message-ID first — it is assigned by the sender and never changes, whatever
    folder or account the message ends up in. Only when there is none (demo
    data, a local note) does this fall back to sender+subject+date."""
    mid = (msg or {}).get("_message_id", "") or ""
    mid = _re.sub(r"\s+", "", mid)
    if mid:
        return mid
    return (f"{(msg or {}).get('from','')}|{(msg or {}).get('subject','')}|"
            f"{(msg or {}).get('_dt','')}")


def _load_reply_progress() -> dict:
    return _load_json_store(_REPLY_PROGRESS_F, {"replies": dict},
                            "reply progress")


def _save_reply_progress(store: dict):
    _save_json_store(_REPLY_PROGRESS_F, store, "reply progress")


def _reply_progress_get(key: str) -> dict:
    """What was typed against this message last time, or {}."""
    if not key:
        return {}
    try:
        return _load_reply_progress().get("replies", {}).get(key, {}) or {}
    except Exception as e:
        log.warning("Could not read reply progress: %s", e)
        return {}


def _reply_progress_put(key: str, paragraphs, answers, skipped, subject=""):
    """Remember an unfinished reply. Also prunes anything older than
    _REPLY_PROGRESS_DAYS so the file cannot grow forever."""
    if not key:
        return
    try:
        store = _load_reply_progress()
        replies = store.setdefault("replies", {})
        replies[key] = {
            "saved":      _now_iso(),
            "subject":    subject,
            "paragraphs": list(paragraphs),
            "answers":    list(answers),
            "skipped":    sorted(int(i) for i in (skipped or [])),
        }
        cutoff = datetime.now() - timedelta(days=_REPLY_PROGRESS_DAYS)
        for k in [k for k, v in replies.items()
                  if (_parse_iso(v.get("saved", "")) or datetime.now()) < cutoff]:
            replies.pop(k, None)
        _save_reply_progress(store)
    except Exception as e:
        log.warning("Could not save reply progress: %s", e)


def _reply_progress_drop(key: str):
    """Forget this message's saved answers — the reply went out, or you threw
    it away on purpose."""
    if not key:
        return
    try:
        store = _load_reply_progress()
        if store.get("replies", {}).pop(key, None) is not None:
            _save_reply_progress(store)
    except Exception as e:
        log.warning("Could not clear reply progress: %s", e)


# ── Activity log: "what happened to my mail while I wasn't looking?" ──────────
#
# Issu 2026-08-08: "Behöver ha en knapp-log där jag kan få upp en popup som
# visar vad som hänt senast, kortfattat. (Jag får meddelande på mobilen att jag
# har mail men de kan ha hanterats av filter innan jag hinner se.)"
#
# The phone says "new mail". By the time the program is opened the rules have
# already read it, moved it, or thrown it away, and nothing on screen explains
# where it went. There WAS a filter log, but it lived only in memory: closing
# the program erased exactly the history that matters, because the whole point
# is looking at it AFTERWARDS.
#
# This store survives restarts. One line per event, in plain words:
#
#   14:32  From PostNord  →  Main  ·  rule "Frakt Postnord"  ·  moved to
#          INBOX/Temporär/0---Frakt & Kvitto
#
_ACTIVITY_F = os.path.join(_ACCOUNTS_DIR, "activity_log.json")

# How much history to keep. 600 entries is a few weeks of ordinary traffic and
# a file of well under a megabyte.
_ACTIVITY_MAX = 600


def _load_activity() -> dict:
    return _load_json_store(_ACTIVITY_F, {"entries": list}, "activity log")


def _save_activity(store: dict):
    _save_json_store(_ACTIVITY_F, store, "activity log")


def _activity_add(store: dict, kind: str, account="", sender="", subject="",
                  detail="", rule=""):
    """Append one event and trim the store. Returns the entry."""
    entry = {
        "when":    _now_iso(),
        "kind":    kind,          # filtered / moved / sent / deleted / fetched…
        "account": account,
        "sender":  sender,
        "subject": (subject or "")[:160],
        "rule":    rule,
        "detail":  detail,
    }
    lst = store.setdefault("entries", [])
    lst.append(entry)
    if len(lst) > _ACTIVITY_MAX:
        del lst[:len(lst) - _ACTIVITY_MAX]
    return entry


# ── Rule health: how much is each filter actually doing? ──────────────────────
#
# Issu 2026-08-08. Counting his own log showed the thing he could not see:
# some rules do all the work (Frakt Tradera 2247 matches), one has NEVER
# matched anything (Estore-rabatt, 0), and — worse, because it looks like it
# works — his shipping rules match plenty historically but catch 0 of the 38
# shipping mails sitting in his inboxes TODAY, because each carries a narrow
# subject condition the carriers stopped using.
#
# None of that was visible anywhere. The filter log was session-only and the
# whole-history answer needed grepping a 24 MB text file. This keeps a tiny
# running tally instead: one line per rule, updated when it fires.
_RULESTATS_F = os.path.join(_ACCOUNTS_DIR, "rule_stats.json")


def _load_rule_stats() -> dict:
    return _load_json_store(_RULESTATS_F, {"rules": dict}, "rule stats")


def _save_rule_stats(store: dict):
    _save_json_store(_RULESTATS_F, store, "rule stats")


def _rule_stat_bump(store: dict, fid: str, name: str, n: int = 1):
    """Record that a rule fired. Cheap enough to call on every match."""
    if not fid:
        return
    r = store.setdefault("rules", {}).setdefault(
        fid, {"name": name, "hits": 0, "first": _now_iso(), "last": ""})
    r["name"] = name or r.get("name", "")
    r["hits"] = int(r.get("hits", 0)) + int(n)
    r["last"] = _now_iso()


def _rule_stat_for(store: dict, fid: str) -> dict:
    return (store.get("rules", {}) or {}).get(fid, {}) or {}


def _rule_blocking_conditions(flt: dict, messages) -> list:
    """Which condition rows are the reason this rule matches nothing?

    Runs the rule against `messages` and counts, per condition, how often it
    said NO while every OTHER condition said yes. A row that is the sole
    objection again and again is the one to look at — which is exactly the
    "From matches, the Subject phrase does not" shape of Issu's carrier rules.

    A WHOLE EITHER/OR GROUP is considered as well as each single row. That is
    not a refinement — it is the case that matters most here. Issu's DHL rule
    is "From contains @dhl.com AND (Subject is 'Ditt kvitto' OR Subject is
    'Inlämningskvitto')": removing ONE of those two subject rows still leaves
    the other, which still says no, so a row-by-row analysis reports nothing
    wrong while the rule quietly catches none of his DHL mail. Dropping the
    either/or section as a unit is what actually unblocks it.

    Returns candidates sorted worst-first, each:
      {"kind": "row"|"group", "index"|"group", "label",
       "blocked", "would_match"}
    Pure — no GUI, no network, testable."""
    conds = flt.get("conditions") or []
    if not conds or not messages:
        return []

    def _measure(keep, label, kind, **extra):
        """How many messages does the rule match with only `keep`, and how
        many of the ones it misses does this candidate explain?"""
        trimmed = dict(flt)
        trimmed["conditions"] = keep
        blocked = would = 0
        for m in messages:
            try:
                if _filter_matches(flt, m):
                    continue                    # already matches — not blocked
                if keep:
                    ok_without = _filter_matches(trimmed, m)
                else:
                    ok_without = True           # nothing left = matches all
                if ok_without:
                    would += 1
                    blocked += 1
            except Exception:
                continue
        d = {"kind": kind, "label": label,
             "blocked": blocked, "would_match": would}
        d.update(extra)
        return d

    out = []
    # 1. Each row on its own.
    for i, c in enumerate(conds):
        keep = [x for j, x in enumerate(conds) if j != i]
        out.append(_measure(
            keep,
            f"{c.get('field','')} {c.get('op','')} “{c.get('value','')}”",
            "row", index=i))
    # 2. Each either/or section as a whole — but only when it HAS more than
    #    one row, otherwise it is the same thing as case 1 and would just show
    #    the user the same offer twice.
    groups = {}
    for i, c in enumerate(conds):
        groups.setdefault(c.get("group", "all"), []).append(i)
    for gname, idxs in groups.items():
        if len(idxs) < 2 or len(idxs) == len(conds):
            continue
        keep = [x for j, x in enumerate(conds) if j not in idxs]
        rows = ", ".join(f"“{conds[j].get('value','')}”" for j in idxs)
        out.append(_measure(
            keep,
            f"the whole “{_SECTION_TITLE.get(gname, gname)}” section "
            f"({len(idxs)} rows: {rows})",
            "group", group=gname, indexes=sorted(idxs)))

    # Best = explains the most misses; on a tie prefer removing LESS.
    out.sort(key=lambda d: (d["blocked"],
                            -(len(d.get("indexes", [0])))), reverse=True)
    return out


def _snooze_lookup(store: dict) -> dict:
    """{key: until_datetime} for every entry that is still in the future."""
    out = {}
    now = datetime.now()
    for s in store.get("snoozed", []):
        dt = _parse_iso(s.get("until", ""))
        if dt and dt > now:
            out[s.get("key", "")] = dt
    return out

def _snooze_due(store: dict) -> list:
    """Entries whose time has come (and that therefore should be dropped)."""
    now = datetime.now()
    due = []
    for s in store.get("snoozed", []):
        dt = _parse_iso(s.get("until", ""))
        if dt is None or dt <= now:
            due.append(s)
    return due


# ── Outbox — the single queue behind BOTH "send later" and "undo send" ────────
# {"messages": [{
#     "id": ..., "state": "queued"|"sending"|"failed",
#     "created": iso, "send_at": iso,
#     "kind": "normal"|"undo"|"unsubscribe",
#     "from": ..., "to": ..., "cc": ..., "subject": ..., "body": ...,
#     "attachments": [path, ...],
#     "error": "", "tries": 0,
#  }, ...]}
#
# Why one queue for both: "undo send" is just "send later, in 10 seconds",
# and a scheduled message obviously also wants to be cancellable. Keeping a
# single list means one scheduler, one crash-recovery path and one dialog.
_OUTBOX_F = os.path.join(_ACCOUNTS_DIR, "outbox.json")

def _load_outbox() -> dict:
    """Read the queue — and REPAIR anything in it that the folded-header bug
    left stranded (Issu 2026-08-07).

    Three real replies sat in the outbox marked "failed" with

        Header values may not contain linefeed or carriage return characters

    because their References: header was carried over folded. The sending code
    can no longer produce that (see _hdr_safe), but messages queued by the OLD
    code are already on disk with the broken value. So: unfold every header
    field on the way in, and put anything that failed with exactly that error
    back in the queue. It then goes out by itself on the next tick — nothing to
    find, nothing to re-type, no lost text."""
    store = _load_json_store(_OUTBOX_F, {"messages": list}, "outbox")
    repaired = 0
    try:
        for item in store.get("messages", []):
            before = (item.get("subject", ""), item.get("in_reply_to", ""),
                      item.get("references", ""), item.get("to", ""),
                      item.get("cc", ""), item.get("from", ""))
            for field in ("subject", "in_reply_to", "references",
                          "to", "cc", "from"):
                if item.get(field):
                    item[field] = _hdr_safe(item[field])
            after = (item.get("subject", ""), item.get("in_reply_to", ""),
                     item.get("references", ""), item.get("to", ""),
                     item.get("cc", ""), item.get("from", ""))
            changed = (before != after)
            if (item.get("state") == "failed"
                    and "linefeed" in (item.get("error", "") or "").lower()):
                item["state"] = "queued"
                item["error"] = ""
                changed = True
            if changed:
                repaired += 1
        if repaired:
            _save_outbox(store)
            log.info("Outbox repair: unfolded headers / re-queued %d message(s) "
                     "stranded by the folded-References bug", repaired)
    except Exception as e:
        log.warning("Outbox repair failed (queue left untouched): %s", e)
    return store

def _save_outbox(store: dict):
    _save_json_store(_OUTBOX_F, store, "outbox")

# Attachments of a queued message are COPIED here. A message scheduled for
# tomorrow morning cannot rely on the file still being where it was when you
# wrote it — a temp file from another program, a download you tidied away, or
# a USB stick that has been unplugged would all turn into a silent "sent
# without the attachment" hours later.
_OUTBOX_ATTACH_DIR = os.path.join(_FM_DIR, "Outbox")


def _outbox_store_attachments(item_id: str, paths: list) -> list:
    """Copy each attachment next to the queue; return the new paths.

    A file that cannot be copied keeps its original path — worse, but no
    worse than before, and the send will report the real problem."""
    if not paths:
        return []
    folder = os.path.join(_OUTBOX_ATTACH_DIR, _safe_name(item_id))
    out = []
    try:
        os.makedirs(folder, exist_ok=True)
    except Exception as e:
        log.warning("Could not create outbox attachment folder: %s", e)
        return list(paths)
    for i, src in enumerate(paths):
        try:
            dst = os.path.join(folder, f"{i:02d}_{_safe_name(os.path.basename(src))}")
            shutil.copy2(src, dst)
            out.append(dst)
        except Exception as e:
            log.warning("Could not copy attachment %s: %s", src, e)
            out.append(src)
    return out


def _outbox_clear_attachments(item: dict):
    """Remove the copies once the message has gone out (or been cancelled)."""
    folder = os.path.join(_OUTBOX_ATTACH_DIR, _safe_name(item.get("id", "")))
    try:
        if os.path.isdir(folder):
            shutil.rmtree(folder, ignore_errors=True)
    except Exception as e:
        log.warning("Could not clean outbox attachments: %s", e)


def _outbox_prune_attachments(store: dict):
    """Drop attachment folders whose message is no longer in the queue —
    housekeeping for the case where a crash landed between the two."""
    try:
        if not os.path.isdir(_OUTBOX_ATTACH_DIR):
            return
        live = {_safe_name(m.get("id", ""))
                for m in store.get("messages", [])}
        for name in os.listdir(_OUTBOX_ATTACH_DIR):
            if name not in live:
                shutil.rmtree(os.path.join(_OUTBOX_ATTACH_DIR, name),
                              ignore_errors=True)
    except Exception as e:
        log.warning("Outbox attachment prune failed: %s", e)


# ── Sending windows (DEL 04r) ─────────────────────────────────────────────────
#
# "Never send before 08:00." You write at midnight because that is when you
# have time; it arrives at a civilised hour because that is when they should
# read it. Optionally weekdays only, and optionally skipping Swedish public
# holidays (the calendar already knows which days those are).
#
# This only ever moves a message FORWARD to the next allowed moment — it can
# delay mail, never send it earlier than you asked. A message you scheduled
# yourself for 03:00 on purpose is still held to the window, because that is
# what turning the window on means; the outbox shows the real time and lets
# you push it out by hand.


def _parse_hhmm(text, fallback=(8, 0)):
    try:
        h, _sep, m = (text or "").strip().replace(".", ":").partition(":")
        return max(0, min(23, int(h))), max(0, min(59, int(m or 0)))
    except Exception:
        return fallback


def _send_window_next(when, cfg, max_days=14):
    """The first moment at or after `when` that the sending window allows.

    Returns `when` unchanged when the window is off or already satisfied."""
    if not (cfg or {}).get("send_window_on", False):
        return when
    from_h, from_m = _parse_hhmm(cfg.get("send_window_from", "08:00"), (8, 0))
    to_h, to_m     = _parse_hhmm(cfg.get("send_window_to", "20:00"), (20, 0))
    weekdays_only  = bool(cfg.get("send_window_weekdays", False))
    skip_holidays  = bool(cfg.get("send_window_skip_holidays", False))

    start_min = from_h * 60 + from_m
    end_min   = to_h * 60 + to_m
    cur = when

    for _ in range(max_days * 2 + 2):
        day_ok = True
        if weekdays_only and cur.weekday() >= 5:
            day_ok = False
        if skip_holidays and _holiday_name(cur):
            day_ok = False

        if day_ok:
            cur_min = cur.hour * 60 + cur.minute
            if start_min <= end_min:
                # An ordinary window, e.g. 08:00–20:00.
                if cur_min < start_min:
                    return cur.replace(hour=from_h, minute=from_m,
                                       second=0, microsecond=0)
                if cur_min <= end_min:
                    return cur
            else:
                # A window over midnight, e.g. 22:00–06:00.
                if cur_min >= start_min or cur_min <= end_min:
                    return cur
                return cur.replace(hour=from_h, minute=from_m,
                                   second=0, microsecond=0)
        # Not today (or too late today) — try the start of the next day.
        cur = (cur + timedelta(days=1)).replace(hour=from_h, minute=from_m,
                                                second=0, microsecond=0)
    return when      # nothing allowed within a fortnight: do not swallow it


def _outbox_due(store: dict) -> list:
    """Queued messages whose send_at has passed."""
    now = datetime.now()
    out = []
    for m in store.get("messages", []):
        if m.get("state") != "queued":
            continue
        dt = _parse_iso(m.get("send_at", ""))
        if dt is None or dt <= now:
            out.append(m)
    return out


# ── Drafts (crash-safe autosave, one JSON file per open compose window) ───────
# A draft file is written a few seconds after you stop typing, and again on
# every change, so an unexpected shutdown costs at most those few seconds.
# {"id":..., "saved": iso, "queued": iso|"", "sent": iso|"",
#  "kind": "compose"|"smart",
#  "from":..., "to":..., "cc":..., "subject":..., "body":...,
#  "attachments": [...], "reply_subject": ...}
#
# THE THREE STATES matter, because a message must never exist in two places
# that can both send it:
#   neither key  — still being written; offered back after a crash.
#   "queued"     — handed to the outbox, which now OWNS it. NOT offered back
#                  on start-up: reopening it while the queued copy is still
#                  waiting would let the same message go out twice.
#   "sent"       — SMTP confirmed it left. Kept `draft_keep_min` minutes as a
#                  safety net, then swept.

def _draft_path(draft_id: str) -> str:
    return os.path.join(_DRAFTS_DIR, f"draft_{_safe_name(draft_id)}.json")

def _save_draft(draft: dict):
    try:
        os.makedirs(_DRAFTS_DIR, exist_ok=True)
        draft["saved"] = _now_iso()
        _save_json_store(_draft_path(draft.get("id", "unknown")), draft, "draft")
    except Exception as e:
        log.warning("Could not save draft: %s", e)

def _delete_draft(draft_id: str):
    try:
        p = _draft_path(draft_id)
        if os.path.isfile(p):
            os.remove(p)
    except Exception as e:
        log.warning("Could not delete draft %s: %s", draft_id, e)

def _list_drafts() -> list:
    """Every draft on disk, newest first."""
    out = []
    try:
        if not os.path.isdir(_DRAFTS_DIR):
            return []
        for fn in os.listdir(_DRAFTS_DIR):
            if not (fn.startswith("draft_") and fn.endswith(".json")):
                continue
            try:
                with open(os.path.join(_DRAFTS_DIR, fn), "r",
                          encoding="utf-8") as f:
                    d = json.load(f)
                if isinstance(d, dict) and d.get("id"):
                    out.append(d)
            except Exception as e:
                log.warning("Skipping unreadable draft %s: %s", fn, e)
    except Exception as e:
        log.warning("Could not list drafts: %s", e)
    out.sort(key=lambda d: d.get("saved", ""), reverse=True)
    return out

def _draft_looks_sent(draft: dict, sent_msgs) -> dict:
    """Has this draft's message already gone out? Returns the matching Sent
    message and why, or {}.

    Issu 2026-08-08: "någon funktion för att kolla Drafts om meddelanden sedan
    skickats = drafts är onödiga." It happens easily — you finish the mail in
    Gmail on the phone, or the draft was written before a send that this
    program did not mark, and the half-written copy sits here for ever looking
    like unfinished work.

    Matching is deliberately CONSERVATIVE, because deleting the wrong draft
    loses writing that cannot be recovered:
      • same recipient (at least one address in common), AND
      • same subject once "Re:"/"Sv:"/"Fwd:" and case are stripped, AND
      • the Sent copy is NOT OLDER than the draft.
    A subject of nothing at all never matches — too many drafts share it."""
    subj = _norm_subject(draft.get("subject", ""))
    if not subj:
        return {}
    d_to = {a.lower() for a in _parse_addr_list(draft.get("to", ""))}
    if not d_to:
        return {}
    saved = _parse_iso(draft.get("saved", "")) or datetime.min

    for s in sent_msgs:
        if _norm_subject(s.get("subject", "")) != subj:
            continue
        s_to = {a.lower() for a in
                (_parse_addr_list(s.get("_to_hdr", ""))
                 + _parse_addr_list(s.get("_cc_hdr", "")))}
        if not (d_to & s_to):
            continue
        # _parse_msg_dt takes the ISO STRING, not the message dict — and it
        # can return a TIMEZONE-AWARE datetime (message dates carry an
        # offset) while everything this program generates is naive, so it is
        # flattened before any comparison. Subtracting one from the other is
        # a TypeError that only shows up on real mail.
        when = _parse_msg_dt(s.get("_dt", "") or "")
        try:
            if when is not None and when.tzinfo is not None:
                when = when.replace(tzinfo=None)
        except Exception:
            when = None
        if when is not None and when < saved - timedelta(minutes=5):
            continue                     # the Sent copy predates the draft
        return {"sent": s,
                "why": f"“{s.get('subject','')[:44]}” went to "
                       f"{', '.join(sorted(d_to & s_to))} on "
                       f"{s.get('date','')[:16]}"}
    return {}


def _norm_subject(s: str) -> str:
    """A subject reduced for comparison: reply/forward prefixes off, collapsed
    whitespace, casefolded. "Re: Sv: Faktura 1571" and "Faktura 1571" are the
    same conversation."""
    s = _hdr_safe(s or "")
    prev = None
    while prev != s:
        prev = s
        s = _re.sub(r"^\s*(re|sv|fwd|fw|vb|aw)\s*(\[\d+\])?\s*:\s*", "", s,
                    flags=_re.I)
    return _re.sub(r"\s+", " ", s).strip().casefold()


def _sweep_drafts(keep_minutes: int):
    """Delete drafts belonging to messages that were sent more than
    `keep_minutes` ago. Drafts that were never sent are NEVER swept — they are
    only removed when you send or explicitly discard them."""
    cutoff = datetime.now() - timedelta(minutes=max(0, int(keep_minutes)))
    for d in _list_drafts():
        sent = _parse_iso(d.get("sent", "") or "")
        if sent is not None and sent <= cutoff:
            _delete_draft(d.get("id", ""))
            log.info("Swept sent draft %s", d.get("id"))


def _draft_is_empty(draft: dict, ignore_prefill: bool = False) -> bool:
    """True when there is nothing worth keeping — an empty compose window that
    was opened and closed again should not litter the Drafts folder.

    ignore_prefill=True is for replies: To: and Subject: are always
    pre-filled with the sender's address and "Re: ..." before you've typed a
    single character, and with Reply All (or Smart Reply's own reply-all)
    Cc: is pre-filled too — none of that is something you wrote. In that
    mode only your own body text, attachments, and Bcc (never auto-filled)
    count, so an untouched reply doesn't ask to keep/discard on close
    (Issu 2026-08-05)."""
    if ignore_prefill:
        return not any([
            (draft.get("body") or "").strip(),
            draft.get("attachments") or [],
            (draft.get("bcc") or "").strip(),
        ])
    return not any([
        (draft.get("to") or "").strip(),
        (draft.get("cc") or "").strip(),
        (draft.get("subject") or "").strip(),
        (draft.get("body") or "").strip(),
        draft.get("attachments") or [],
    ])


# ******************************************************************************
# DEL 04e — ENGINES: phishing scan, unsubscribe, forgotten attachment,
#           PDF writer, backup, filters, all-folder IMAP search, mailto
# ******************************************************************************
#
# Everything in this section is deliberately PURE: functions that take data and
# return data, with no Tkinter and no global state. That keeps them testable
# from a plain Python prompt and keeps the GUI sections (DEL 06/09) readable.


# ── 1. Phishing analysis ──────────────────────────────────────────────────────
#
# This does NOT try to be a spam filter and it never hides or deletes anything.
# It looks for the handful of tells that actually catch real phishing, and
# tells you in plain English what it found so you can judge for yourself.

# Extensions that should never arrive unannounced.
_DANGEROUS_EXT = {
    ".exe", ".scr", ".com", ".pif", ".bat", ".cmd", ".js", ".jse", ".vbs",
    ".vbe", ".wsf", ".wsh", ".hta", ".msi", ".msc", ".jar", ".ps1", ".reg",
    ".lnk", ".cpl", ".dll", ".iso", ".img",
}

# Extensions that look harmless and are used to hide a dangerous one, as in
# "invoice.pdf.exe" — we flag any file whose SECOND-to-last extension is one
# of these while the real one is executable.
_DECOY_EXT = {".pdf", ".doc", ".docx", ".xls", ".xlsx", ".jpg", ".png", ".txt"}

# Wording that, TOGETHER WITH A LINK, is the classic credential-phish pattern.
# English first (this program is English), Swedish added because that is what
# actually lands in the mailbox this program was written for.
_URGENCY_WORDS = [
    "verify your account", "confirm your account", "confirm your identity",
    "update your payment", "unusual activity", "suspended", "within 24 hours",
    "click here immediately", "your account will be closed", "act now",
    "verify your password", "re-enter your password", "security alert",
    "verifiera ditt konto", "bekräfta ditt konto", "ditt konto stängs",
    "inom 24 timmar", "ovanlig aktivitet", "uppdatera dina betalnings",
    "klicka här omgående", "spärrat", "verifiera dina uppgifter",
]

# Square brackets are OUT (Issu 2026-08-17). They are not part of an address in
# any mail he has — the only thing that puts one against a URL is markup around
# it — and swallowing one breaks the link that gets drawn:
#     https://tracking.postnord.com/?id=LY021950964SE]   ← his PostNord tracking
#     https://www.instagram.com/pixlr/]
#     https://boardgamegeek.com/market/product/3710133[/q][/q]
#     https://www.amazon.se/help/terms-of-use](https://www.amazon.se/gp/help/…
# — measured over all 497 cached messages: 48 URLs carried a bracket, not one
# of them legitimately. (A bracket is legal in a URL only as an IPv6 literal
# host, http://[::1]/ — which no mail here contains, and which would still be
# safer left unclickable than a tracking link that opens the wrong page.)
_URL_RE  = _re.compile(r'https?://[^\s<>"\')\[\]]+', _re.I)
# A reply attribution: "On 27/02/2026 11:23, Lars Olsson wrote:" (and the
# Swedish "skrev:", which is what his own client sends). Used to spot the line
# that is worth hiding ONLY when the quote under it never arrived — see the
# "orphan" rule kind in DEL 04t2.
_ATTRIB_RE = _re.compile(r'(?:wrote|skrev)\s*:\s*$', _re.I)
_HREF_RE = _re.compile(r'(?is)<a\b[^>]*?href\s*=\s*["\']([^"\']+)["\'][^>]*>(.*?)</a>')
_IPV4_RE = _re.compile(r'^\d{1,3}(\.\d{1,3}){3}$')


def _domain_of(url_or_addr: str) -> str:
    """Registrable-ish domain of a URL or an email address, lower-cased.

    'Registrable-ish' because doing this properly needs the public-suffix
    list; the last two labels are right often enough for a WARNING (which a
    human then reads), and wrong in a harmless direction for things like
    .co.uk — it would compare 'co.uk' to 'co.uk' and simply not warn."""
    s = (url_or_addr or "").strip().lower()
    if "@" in s and "://" not in s:
        s = s.rsplit("@", 1)[-1]
    else:
        try:
            netloc = _urlparse.urlsplit(s if "://" in s else "http://" + s).netloc
            s = netloc.rsplit("@", 1)[-1].split(":")[0]
        except Exception:
            pass
    s = s.strip(".")
    if _IPV4_RE.match(s):
        return s
    parts = [p for p in s.split(".") if p]
    return ".".join(parts[-2:]) if len(parts) >= 2 else s


# Warnings a trusted sender does NOT get to suppress. Trust is about the
# heuristics that produce false positives (a newsletter whose links go via a
# tracking domain, a mail server that stamps a soft DKIM failure). An
# executable attachment is not a false positive — if a trusted sender's
# account is taken over, that warning is the one that matters most, so it is
# never silenced.
_UNSUPPRESSABLE = ("is disguised:", "is an executable/script file")


def _is_trusted_sender(store: dict, msg: dict) -> bool:
    hay = (msg.get("from", "") + " " + msg.get("from_name", "")).lower()
    for t in store.get("trusted", []):
        m = (t.get("match") or "").strip().lower()
        if m and m in hay:
            return True
    return False


# Free / consumer mail providers. A big brand ("Swedbank", "Amazon") never
# sends its official mail from one of these, so a brand word in the display
# name combined with a from-address here is a very strong phishing tell.
_FREE_MAIL = {
    "gmail.com", "googlemail.com", "outlook.com", "hotmail.com", "live.com",
    "yahoo.com", "yahoo.se", "icloud.com", "me.com", "aol.com", "proton.me",
    "protonmail.com", "mail.ru", "yandex.com", "gmx.com", "gmx.net",
    "web.de", "zoho.com", "hotmail.se", "live.se", "msn.com",
}

# Brand names that are impersonated often (Swedish + global). Matched as a
# lower-case substring of the display name. Kept short and high-value on
# purpose — the check that uses it is only as trustworthy as this list.
_BRAND_WORDS = (
    "amazon", "paypal", "swedbank", "nordea", "handelsbanken", "länsförsäkringar",
    "lansforsakringar", "klarna", "netflix", "spotify", "microsoft", "apple",
    "icloud", "google", "facebook", "instagram", "postnord", "dhl", "fedex",
    "ups", "telia", "tele2", "comviq", "skatteverket", "kronofogden",
    "försäkringskassan", "forsakringskassan", "bankid", "visa", "mastercard",
    "coinbase", "binance", "revolut", "wise",
)


def _brand_impersonation_warning(msg: dict, level: str = "balanced") -> str:
    """One warning string (or "") for a display NAME that claims a brand/domain
    the real sending address does not back up — the "Amazon.se scammer" case.

    Levels: "off" | "domain" | "balanced" | "aggressive" (see settings)."""
    if level == "off":
        return ""
    from_addr = (msg.get("from") or "").strip()
    from_name = (msg.get("from_name") or "").strip()
    if not from_addr or not from_name:
        return ""
    from_dom  = _domain_of(from_addr)
    name_low  = from_name.lower()

    # If the NAME already contains a full e-mail address, the main scan's
    # check (a) handles that — do not duplicate the warning here.
    if _re.search(r'[\w.+-]+@[\w.-]+\.\w+', from_name):
        return ""

    # (i) A domain-like token in the name — "Amazon.se", "paypal.com".
    dom_in_name = _re.search(r'\b([a-z0-9][a-z0-9-]*\.[a-z]{2,})\b', name_low)
    if dom_in_name:
        claimed = _domain_of(dom_in_name.group(1))
        if (claimed and from_dom and claimed != from_dom
                and claimed not in from_dom and from_dom not in claimed):
            return (f'The sender NAME shows "{dom_in_name.group(1)}" but the '
                    f'mail actually comes from "{from_dom}".')
        return ""   # a domain in the name that DID match — nothing to say

    if level == "domain":
        return ""

    # (ii) A known brand word with no matching domain part.
    for brand in _BRAND_WORDS:
        if brand in name_low and brand not in from_dom:
            if level == "aggressive" or from_dom in _FREE_MAIL:
                pretty = brand[:1].upper() + brand[1:]
                return (f'The sender NAME mentions "{pretty}" but the mail '
                        f'comes from "{from_addr}", which is not a {pretty} '
                        f'address.')
            break
    return ""


def _phishing_scan(msg: dict, trusted=False, brand_level="balanced") -> list:
    """Return a list of human-readable warnings. Empty list = nothing found.

    `trusted=True` keeps only the warnings that must never be suppressed
    (see _UNSUPPRESSABLE)."""
    warn = []
    from_addr = (msg.get("from") or "").strip()
    from_name = (msg.get("from_name") or "").strip()
    from_dom  = _domain_of(from_addr)
    body      = msg.get("body") or ""
    html      = msg.get("_html") or ""

    # (a) Display name that itself contains a DIFFERENT email address —
    #     "Swedbank <no-reply@totally-not-swedbank.ru>" style.
    m = _re.search(r'[\w.+-]+@[\w.-]+\.\w+', from_name)
    if m and from_addr and m.group(0).lower() != from_addr.lower():
        warn.append(
            f'The sender NAME shows "{m.group(0)}" but the mail actually '
            f'comes from "{from_addr}".')

    # (a2) Display name claims a BRAND or a DOMAIN (not a full e-mail address)
    #      that the real sending address does not back up — the "Amazon.se
    #      scammer" case that (a) cannot catch. Sensitivity is a setting.
    brand_w = _brand_impersonation_warning(msg, brand_level)
    if brand_w:
        warn.append(brand_w)

    # (b) Reply-To on another domain than From — replies would go elsewhere.
    reply_to = (msg.get("_reply_to_hdr") or "").strip()
    if reply_to:
        rdom = _domain_of(parseaddr(reply_to)[1] or reply_to)
        if rdom and from_dom and rdom != from_dom:
            warn.append(
                f'Replies would NOT go to the sender: From is "{from_dom}" '
                f'but Reply-To points at "{rdom}".')

    # (c) Link text says one domain, the link goes somewhere else. Only
    #     compared when the visible text looks like a domain/URL at all —
    #     "click here" is not a mismatch, it is just vague.
    for href, text in _HREF_RE.findall(html)[:200]:
        vis = _re.sub(r"(?is)<.*?>", "", text)
        vis = _htmllib.unescape(vis).strip()
        if not vis or "." not in vis or " " in vis.strip():
            continue
        if not _re.match(r'^(https?://)?[\w.-]+\.\w{2,}(/|$)', vis):
            continue
        vdom, hdom = _domain_of(vis), _domain_of(href)
        if vdom and hdom and vdom != hdom:
            warn.append(
                f'A link shows "{vdom}" but actually goes to "{hdom}".')
            break   # one example is enough — the banner stays readable

    # (d) Raw-IP links and punycode (xn--) look-alike domains.
    urls = _URL_RE.findall(body) + [h for h, _ in _HREF_RE.findall(html)]
    for u in urls[:200]:
        d = _domain_of(u)
        if _IPV4_RE.match(d):
            warn.append(f'A link points straight at an IP address ({d}) '
                        f'instead of a domain name.')
            break
    for u in urls[:200]:
        if "xn--" in _domain_of(u):
            warn.append('A link uses a punycode (xn--) domain, which is how '
                        'look-alike addresses hide non-Latin letters.')
            break

    # (e) Attachments: dangerous type, or a decoy double extension.
    for fn in (msg.get("attachments") or []):
        low = fn.lower()
        root, ext = os.path.splitext(low)
        if ext in _DANGEROUS_EXT:
            _, ext2 = os.path.splitext(root)
            if ext2 in _DECOY_EXT:
                warn.append(f'Attachment "{fn}" is disguised: it looks like a '
                            f'{ext2[1:].upper()} but is really a {ext[1:].upper()} '
                            f'program file.')
            else:
                warn.append(f'Attachment "{fn}" is an executable/script file '
                            f'({ext}) — do not open it unless you asked for it.')

    # (f) Urgency/credential wording together with at least one link.
    if urls:
        low = (body + " " + html).lower()
        hit = next((w for w in _URGENCY_WORDS if w in low), None)
        if hit:
            warn.append(f'The text pushes urgency ("{hit}") and contains a '
                        f'link — the classic pattern for credential theft.')

    # (g) Authentication-Results, when the server bothered to add one.
    auth = (msg.get("_auth_results") or "").lower()
    for mech in ("dkim", "spf", "dmarc"):
        if f"{mech}=fail" in auth:
            warn.append(f'The receiving server says {mech.upper()} FAILED — '
                        f'the sender address may well be forged.')

    if trusted:
        warn = [w for w in warn if any(u in w for u in _UNSUPPRESSABLE)]
    return warn


# ── 2. Unsubscribe ────────────────────────────────────────────────────────────

# The words that mean "stop sending me this", in the two languages his mail
# actually arrives in. Kept as ONE pattern so the anchor scan and the
# plain-text scan can never disagree about what counts as an unsubscribe link.
_UNSUB_WORDS = (r'unsubscribe|un-subscribe|opt.?out|manage\s+(?:your\s+)?'
                r'(?:email\s+)?preferences|email\s+preferences|'
                r'avregistrera|avanm(?:ä|a)l|avprenumerera|'
                r'sluta\s+prenumerera|avsluta\s+prenumeration|'
                r'hantera\s+prenumeration|prenumerationsinst(?:ä|a)llningar|'
                r'sluta\s+f(?:å|a)\s+(?:dessa\s+)?(?:mail|utskick)')

_UNSUB_TEXT_RE = _re.compile(
    r'(?is)<a\b[^>]*?href\s*=\s*["\']([^"\']+)["\'][^>]*>((?:(?!</a>).){0,160}?'
    r'(?:' + _UNSUB_WORDS + r')'
    r'(?:(?!</a>).){0,160}?)</a>')

_UNSUB_WORD_RE = _re.compile(r'(?is)(?:' + _UNSUB_WORDS + r')')


def _unsub_links_in_text(text, window=120) -> list:
    """URLs in a PLAIN-TEXT body that sit near an unsubscribe word.

    The fallback for a sender with no HTML part at all, and for the
    "label (URL)" shape _html_to_text produces.

    Deliberately NOT one regex with the URL inside it. A pattern like
    `(https?://\\S+).{0,80}?(?:unsubscribe|…)` looks right and is quietly
    wrong: to make the tail fit, the engine backtracks INTO the captured URL,
    so "…(https://shop.example/unsubscribe/abc) to stop" hands back
    "https://shop.example/" — a real address, pointing at the wrong page, with
    nothing to show it was truncated. Tightening it with a lookahead only
    moves the truncation ("https://shop"), because a dot ends a sentence as
    well as separating a domain. Finding the URLs FIRST and asking about their
    surroundings afterwards cannot truncate at all."""
    out = []
    text = text or ""
    for m in _URL_RE.finditer(text):
        url = m.group(0).rstrip('.,);:"\'')
        near = text[max(0, m.start() - window):m.end() + window]
        if _UNSUB_WORD_RE.search(near):
            out.append(url)
    return out

# A URL whose PATH looks like an unsubscribe endpoint, regardless of what the
# link text says. Catches the very common case of a bare tracking URL whose
# only clue is the word buried in the path.
_UNSUB_URL_RE = _re.compile(
    r'(?i)(?:unsub|unsubscribe|optout|opt-out|remove|avreg|avanmal|'
    r'listunsub|email[-_]?prefs?|preferences)')


def _one_click_ok(msg: dict) -> bool:
    """Does this message carry RFC 8058's one-click promise?"""
    return "one-click" in (msg.get("_list_unsub_post") or "").lower()


def _find_unsubscribe(msg: dict) -> dict:
    """Locate an unsubscribe route for a message.

    Returns {"mailto", "mailto_subject", "http", "source", "one_click",
             "candidates"} where `candidates` is [(url, link_text), ...] —
    every unsubscribe-looking link found in the body, best guess first, so a
    page that turns out to be the wrong one ("manage preferences" when you
    wanted "unsubscribe from everything") has an alternative to offer instead
    of a dead end.

    The List-Unsubscribe header is the correct, machine-readable route and is
    tried first; links in the body are the fallback for senders who never
    bothered with the header.

    `one_click` is True only when the sender declared RFC 8058 AND gave an
    https route in the header — never for a link scraped out of the body. That
    distinction matters: the header is the sender stating a machine endpoint,
    a body link is this program guessing, and only the first is safe to fire
    without a human looking at the page."""
    out = {"mailto": "", "mailto_subject": "Unsubscribe", "http": "",
           "source": "", "one_click": False, "candidates": []}
    hdr = (msg.get("_list_unsub") or "").strip()
    if hdr:
        for part in _re.findall(r'<([^>]+)>', hdr) or [hdr]:
            p = part.strip()
            if p.lower().startswith("mailto:") and not out["mailto"]:
                addr = p[7:]
                subj = ""
                if "?" in addr:
                    addr, _, query = addr.partition("?")
                    qs = _urlparse.parse_qs(query)
                    subj = (qs.get("subject") or [""])[0]
                out["mailto"] = addr.strip()
                if subj:
                    out["mailto_subject"] = subj
                out["source"] = "header"
            elif p.lower().startswith("http") and not out["http"]:
                out["http"]   = p
                out["source"] = "header"
        if out["http"] and _one_click_ok(msg):
            out["one_click"] = True

    # ── Body links: collect them ALL, not just the first ─────────────────
    html = msg.get("_html") or ""
    body = msg.get("body") or ""
    seen = set()

    def _add(url, label=""):
        url = _htmllib.unescape((url or "").strip()).rstrip('.,);"\'>')
        if not url.lower().startswith(("http://", "https://", "mailto:")):
            return
        key = url.lower()
        if key in seen:
            return
        seen.add(key)
        out["candidates"].append((url, " ".join((label or "").split())[:80]))

    for href, label in _UNSUB_TEXT_RE.findall(html):
        _add(href, _re.sub(r"(?is)<.*?>", "", label))
    for url in _unsub_links_in_text(body):
        _add(url, "near the word “unsubscribe”")
    # Last resort: any link in the message whose ADDRESS looks like an
    # unsubscribe endpoint even though its text said nothing of the sort.
    # Deliberately last — it is the weakest signal of the three.
    for url in _links_in_message(msg, limit=60):
        path = _urlparse.urlsplit(url).path + "?" + \
            (_urlparse.urlsplit(url).query or "")
        if _UNSUB_URL_RE.search(path):
            _add(url, "the address itself says unsubscribe")

    if not (out["mailto"] or out["http"]) and out["candidates"]:
        first = out["candidates"][0][0]
        if first.lower().startswith("mailto:"):
            out["mailto"] = first[7:].split("?")[0].strip()
        else:
            out["http"] = first
        out["source"] = "body"
    return out


# ── 2a. The mini-mini web view (Issu 2026-08-29) ──────────────────────────────
#
# "Kanske att det inte ens behöver öppna min webläsare utan Freemail kan ha en
# mini-mini-webläsare som bara öppnas för att gå till avregistrerasidor e.d."
#
# WHAT THIS IS. Enough of a browser to finish an unsubscribe, and deliberately
# nothing more: fetch a page, show its text, show its forms as real Tk widgets,
# and send one back when YOU press its button. Standard library only, like the
# rest of the program — `urllib.request` for the fetching, `html.parser` for
# the forms, `_html_to_text` (already here, written for mail) for the reading.
#
# WHAT IT IS NOT, on purpose:
#   • No JavaScript. An unsubscribe page that needs JS says so and offers a
#     one-click button through to the real browser.
#   • No images, no fonts, no CSS, no third-party requests — ONE request per
#     page you actually asked for, so a tracking pixel farm has nothing to
#     work with.
#   • No cookies from your real browser, and none kept after the window
#     closes: the jar lives on the window object and dies with it. A
#     multi-step "confirm → done" flow works; nothing outlives it.
#   • It NEVER submits a form by itself. Every POST/GET is a button you
#     pressed, and the exact bytes that will be sent are one click away
#     ("Show exactly what will be sent") before you press it.
#   • It refuses anything that is not http/https, so a javascript:, data: or
#     file: link in a mail is inert.
#
# WHY IT IS SAFE ENOUGH TO EXIST. The alternative is not "nothing happens" —
# it is opening the same URL in the real browser, signed in to everything, with
# JS and the full cookie jar. This window is strictly less exposed than that,
# and the URL is on screen the whole time.
import urllib.request as _urlreq
import urllib.error as _urlerr
import http.cookiejar as _cookiejar
from html.parser import HTMLParser as _HTMLParser

# A plain desktop-browser UA. Not deception — several unsubscribe endpoints
# simply 403 anything that identifies as a script, and a page you cannot fetch
# is a page you have to open in the real browser instead.
_WEB_UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
           "(KHTML, like Gecko) Chrome/124.0 Safari/537.36")
_WEB_TIMEOUT   = 20          # seconds; an unsubscribe page that is slower than
                             # this is one for the real browser
_WEB_MAX_BYTES = 2 * 1024 * 1024   # 2 MB of HTML is already absurd
_WEB_MAX_HOPS  = 6           # redirect chain length before we stop and ask


class _CappedRedirect(_urlreq.HTTPRedirectHandler):
    """Follows redirects (unsubscribe links are almost always a tracking hop
    first) but records every one, so the window can show where it actually
    ended up rather than where you thought you were going."""

    def __init__(self):
        self.chain = []

    def redirect_request(self, req, fp, code, msg, headers, newurl):
        if len(self.chain) >= _WEB_MAX_HOPS:
            return None
        if not (newurl or "").lower().startswith(("http://", "https://")):
            return None          # never follow a redirect off the web
        self.chain.append(newurl)
        return super().redirect_request(req, fp, code, msg, headers, newurl)


def _web_opener():
    """A fresh opener with its own cookie jar and redirect log.

    Returned as (opener, jar, redirect_handler) — the caller keeps all three
    for the life of ONE mini-browser window and throws them away with it."""
    jar = _cookiejar.CookieJar()
    red = _CappedRedirect()
    opener = _urlreq.build_opener(
        _urlreq.HTTPCookieProcessor(jar), red,
        _urlreq.HTTPSHandler(context=ssl.create_default_context()))
    opener.addheaders = []      # we set them per request instead
    return opener, jar, red


def _web_fetch(url, opener=None, data=None, method=None, timeout=_WEB_TIMEOUT):
    """Fetch one page. Returns a dict — never raises.

    {"ok": bool, "url": final url, "status": int, "html": str, "text": str,
     "ctype": str, "error": str, "hops": [urls]}

    `data`: bytes for a POST (form-urlencoded), or None for a GET."""
    out = {"ok": False, "url": url, "status": 0, "html": "", "text": "",
           "ctype": "", "error": "", "hops": []}
    if not (url or "").lower().startswith(("http://", "https://")):
        out["error"] = ("Only http and https addresses can be opened here "
                        f"(this one is “{(url or '')[:60]}”).")
        return out
    if opener is None:
        opener, _jar, _red = _web_opener()
    red = next((h for h in getattr(opener, "handlers", [])
                if isinstance(h, _CappedRedirect)), None)
    if red is not None:
        red.chain = []
    req = _urlreq.Request(url, data=data, method=method)
    req.add_header("User-Agent", _WEB_UA)
    req.add_header("Accept", "text/html,application/xhtml+xml,text/plain;q=0.9")
    req.add_header("Accept-Language", "sv-SE,sv;q=0.9,en;q=0.8")
    if data is not None:
        req.add_header("Content-Type", "application/x-www-form-urlencoded")
    try:
        with opener.open(req, timeout=timeout) as resp:
            out["status"] = getattr(resp, "status", 0) or resp.getcode()
            out["url"]    = resp.geturl()
            out["ctype"]  = (resp.headers.get("Content-Type") or "").lower()
            raw = resp.read(_WEB_MAX_BYTES + 1)
    except _urlerr.HTTPError as e:
        # An HTTP error still has a body, and on an unsubscribe endpoint that
        # body is usually the thing worth reading ("already unsubscribed").
        out["status"] = e.code
        out["url"]    = getattr(e, "url", url) or url
        out["ctype"]  = (e.headers.get("Content-Type") or "").lower() \
            if e.headers else ""
        try:
            raw = e.read(_WEB_MAX_BYTES + 1)
        except Exception:
            raw = b""
        out["error"] = f"The site answered {e.code} {e.reason}."
    except _urlerr.URLError as e:
        out["error"] = f"Could not reach the site: {getattr(e, 'reason', e)}"
        return out
    except Exception as e:
        out["error"] = f"Could not open the page: {e}"
        return out
    if red is not None:
        out["hops"] = list(red.chain)
    if len(raw) > _WEB_MAX_BYTES:
        raw = raw[:_WEB_MAX_BYTES]
        out["error"] = (out["error"] + "  " if out["error"] else "") + \
            "The page was very large and has been cut short."
    charset = "utf-8"
    m = _re.search(r"charset=([\w-]+)", out["ctype"] or "")
    if m:
        charset = m.group(1)
    else:
        m = _re.search(rb'(?i)charset=["\']?([\w-]+)', raw[:2048])
        if m:
            charset = m.group(1).decode("ascii", "replace")
    try:
        body = raw.decode(charset, "replace")
    except (LookupError, TypeError):
        body = raw.decode("utf-8", "replace")
    if "html" in (out["ctype"] or "") or _re.search(r"(?i)<html|<body|<div",
                                                    body[:2000]):
        out["html"] = body
        out["text"] = _html_to_text(body)
    else:
        out["text"] = body
    out["ok"] = 200 <= out["status"] < 400
    return out


# ── The form reader ───────────────────────────────────────────────────────────
# An unsubscribe page is nearly always one <form> with a hidden token, maybe a
# tick-box or two, and a submit button. That is a shape a 150-line parser can
# handle honestly; anything fancier falls through to the real browser.

_FORM_MAX        = 4     # forms rendered per page
_FORM_MAX_FIELDS = 30    # visible fields rendered per form


class _MiniFormParser(_HTMLParser):
    """Pull the <form>s and <a>s out of a page.

    Labels are a heuristic and admit it: whatever readable text appeared since
    the previous field is offered as this field's caption, falling back to the
    input's own placeholder/aria-label/name. Good enough to tell "E-mail" from
    "Reason for leaving"; not good enough to be trusted silently, which is why
    the window also shows the raw name=value of everything it will send."""

    _SKIP = {"script", "style", "head", "noscript"}

    def __init__(self):
        super().__init__(convert_charrefs=True)
        self.forms = []
        self.links = []          # [(href, text)]
        self._form = None
        self._skip = 0
        self._pending = []       # text seen since the last field
        self._select = None
        self._textarea = None
        self._a = None

    # -- helpers ---------------------------------------------------------
    @staticmethod
    def _d(attrs):
        return {(k or "").lower(): (v if v is not None else "")
                for k, v in attrs}

    def _label(self, a):
        txt = " ".join(" ".join(self._pending).split())[-70:].strip(" :*")
        self._pending = []
        return (txt or a.get("placeholder") or a.get("aria-label")
                or a.get("title") or a.get("name") or "")

    # -- tags ------------------------------------------------------------
    def handle_starttag(self, tag, attrs):
        tag = tag.lower()
        if tag in self._SKIP:
            self._skip += 1
            return
        if self._skip:
            return
        a = self._d(attrs)
        if tag == "form":
            self._form = {"action": a.get("action", ""),
                          "method": (a.get("method") or "get").lower(),
                          "name": a.get("name") or a.get("id") or "",
                          "fields": [], "submits": []}
            self.forms.append(self._form)
            self._pending = []
        elif tag == "a":
            self._a = [a.get("href", ""), []]
        elif tag == "input" and self._form is not None:
            t = (a.get("type") or "text").lower()
            if t in ("submit", "image"):
                self._form["submits"].append(
                    {"name": a.get("name", ""), "value": a.get("value", ""),
                     "label": a.get("value") or a.get("alt") or "Send"})
            elif t in ("button", "reset"):
                pass                       # does nothing without JavaScript
            else:
                self._form["fields"].append({
                    "kind": "hidden" if t == "hidden" else t,
                    "name": a.get("name", ""), "value": a.get("value", ""),
                    "checked": "checked" in a,
                    "required": "required" in a,
                    "label": "" if t == "hidden" else self._label(a)})
        elif tag == "select" and self._form is not None:
            self._select = {"kind": "select", "name": a.get("name", ""),
                            "value": "", "options": [],
                            "required": "required" in a,
                            "label": self._label(a)}
            self._form["fields"].append(self._select)
        elif tag == "option" and self._select is not None:
            self._select["options"].append(
                [a.get("value", None), "", "selected" in a])
        elif tag == "textarea" and self._form is not None:
            self._textarea = {"kind": "textarea", "name": a.get("name", ""),
                              "value": "", "required": "required" in a,
                              "label": self._label(a)}
            self._form["fields"].append(self._textarea)
        elif tag == "button" and self._form is not None:
            t = (a.get("type") or "submit").lower()
            if t == "submit":
                self._form["submits"].append(
                    {"name": a.get("name", ""), "value": a.get("value", ""),
                     "label": ""})     # filled from the button's text below
        elif tag in ("br", "p", "div", "tr", "li", "label"):
            self._pending.append(" ")

    def handle_startendtag(self, tag, attrs):
        self.handle_starttag(tag, attrs)
        if tag.lower() not in ("input", "br", "img", "hr", "meta", "link"):
            self.handle_endtag(tag)

    def handle_endtag(self, tag):
        tag = tag.lower()
        if tag in self._SKIP:
            self._skip = max(0, self._skip - 1)
            return
        if self._skip:
            return
        if tag == "form":
            self._form = None
        elif tag == "select":
            self._select = None
        elif tag == "textarea":
            self._textarea = None
        elif tag == "a" and self._a is not None:
            href, txt = self._a
            self.links.append((href, " ".join("".join(txt).split())[:80]))
            self._a = None
        elif tag == "button" and self._form is not None \
                and self._form["submits"]:
            b = self._form["submits"][-1]
            if not b["label"]:
                b["label"] = " ".join(" ".join(self._pending).split())[:40] \
                    or "Send"
                self._pending = []

    def handle_data(self, data):
        if self._skip or not data:
            return
        if self._a is not None:
            self._a[1].append(data)
        if self._textarea is not None:
            self._textarea["value"] += data
            return
        if self._select is not None and self._select["options"]:
            o = self._select["options"][-1]
            o[1] = (o[1] + data).strip()
            return
        self._pending.append(data)
        if len(self._pending) > 40:
            del self._pending[:-40]


def _page_forms(html, base_url):
    """Forms and links from a page, with every URL made absolute.

    Returns (forms, links). A form with no submit button gets a synthetic one
    — plenty of real pages submit with JavaScript and would otherwise show a
    box you cannot send."""
    p = _MiniFormParser()
    try:
        p.feed(html or "")
        p.close()
    except Exception as e:
        log.warning("mini-browser: could not parse the page: %s", e)
    forms = []
    for f in p.forms[:_FORM_MAX]:
        f["action"] = _urlparse.urljoin(base_url, f.get("action") or "") \
            or base_url
        if f["method"] not in ("get", "post"):
            f["method"] = "get"
        for fld in f["fields"]:
            if fld["kind"] == "select":
                for o in fld["options"]:
                    if o[0] is None:
                        o[0] = o[1]        # <option>Text</option> submits Text
                sel = [o for o in fld["options"] if o[2]]
                fld["value"] = (sel or fld["options"] or [["", "", False]])[0][0]
        if not f["submits"]:
            f["submits"] = [{"name": "", "value": "", "label": "Send"}]
        forms.append(f)
    links = []
    seen = set()
    for href, txt in p.links:
        u = _urlparse.urljoin(base_url, (href or "").strip())
        if not u.lower().startswith(("http://", "https://")) or u in seen:
            continue
        seen.add(u)
        links.append((u, txt))
    return forms, links


def _form_request(form, values, submit):
    """Turn a filled-in form into (url, data_bytes_or_None).

    `values` maps field index → the value the widgets currently hold; a value
    of None means "this field is unticked", which is exactly how an HTML form
    behaves: unticked boxes are simply not sent."""
    pairs = []
    for i, fld in enumerate(form["fields"]):
        name = (fld.get("name") or "").strip()
        if not name:
            continue
        v = values.get(i, fld.get("value", ""))
        if v is None:
            continue                      # unticked box / unchosen radio
        pairs.append((name, v))
    if submit and (submit.get("name") or "").strip():
        pairs.append((submit["name"], submit.get("value", "")))
    body = _urlparse.urlencode(pairs, doseq=False)
    if form["method"] == "post":
        return form["action"], body.encode("utf-8"), pairs
    url = form["action"]
    if body:
        url += ("&" if "?" in url else "?") + body
    return url, None, pairs


def _unsub_one_click(url, timeout=_WEB_TIMEOUT):
    """RFC 8058: POST "List-Unsubscribe=One-Click" and you are off the list.

    One request, no page, no browser. Returns the same dict _web_fetch does,
    so a caller can report what the server actually said."""
    opener, _jar, _red = _web_opener()
    return _web_fetch(url, opener=opener,
                      data=b"List-Unsubscribe=One-Click", method="POST",
                      timeout=timeout)


# ── What has already been unsubscribed, and what is waiting ───────────────────
# {"done":  [{"sender", "list", "route", "url", "when", "result", "account"}],
#  "queue": [{"sender", "from_name", "subject", "account", "key", "added",
#             "rule", "route", "url", "mailto", "one_click"}]}
#
# `done` is what stops the same list being unsubscribed from over and over —
# a newsletter keeps arriving for days after you leave it, and a rule that
# re-fired on every one of those would look exactly like a rule that does not
# work. `queue` is the middle setting between "ask me every time" and "just do
# it": the rule collects them, you clear them in one pass.
_UNSUB_F = os.path.join(_ACCOUNTS_DIR, "unsubscribes.json")


def _load_unsubs() -> dict:
    return _load_json_store(_UNSUB_F, {"done": list, "queue": list},
                            "unsubscribe log")


def _save_unsubs(store: dict):
    _save_json_store(_UNSUB_F, store, "unsubscribe log")


def _unsub_key(msg) -> str:
    """What counts as "the same list". The List-Unsubscribe route when there
    is one (two newsletters from the same shop are different lists and have
    different routes), otherwise the bare sender address."""
    hdr = (msg.get("_list_unsub") or "").strip().lower()
    if hdr:
        return "list:" + hdr[:200]
    return "from:" + (parseaddr(msg.get("from", ""))[1]
                      or msg.get("from", "")).strip().lower()


def _unsub_already_done(store, msg) -> dict:
    key = _unsub_key(msg)
    for d in reversed(store.get("done", [])):
        if d.get("key") == key:
            return d
    return {}


def _unsub_queued(store, msg) -> bool:
    key = _unsub_key(msg)
    return any(q.get("key") == key for q in store.get("queue", []))


# ── 2b. Attachment size ───────────────────────────────────────────────────────
#
# Gmail refuses a message over 25 MB with an SMTP error that says nothing
# useful. With "send later" that rejection would surface hours after you
# pressed the button, so the size is checked while you can still do something
# about it. Attachments are base64-encoded on the wire, which costs about
# 37 %, so the number that matters is the ENCODED size.

GMAIL_MAX_BYTES  = 25 * 1024 * 1024      # hard limit at Gmail's end
_B64_OVERHEAD    = 1.37                  # base64 + MIME headers, near enough
_ATTACH_WARN_AT  = 0.8                   # warn from 80 % of the limit


def _human_size(n: float) -> str:
    for unit in ("B", "KB", "MB", "GB"):
        if n < 1024 or unit == "GB":
            return f"{n:.0f} {unit}" if unit in ("B", "KB") else f"{n:.1f} {unit}"
        n /= 1024
    return f"{n:.1f} GB"


def _attachment_size_check(paths: list) -> dict:
    """{"raw", "encoded", "over", "warn", "missing": [...], "text"} for a set
    of attachment paths."""
    raw, missing = 0, []
    for p in (paths or []):
        try:
            raw += os.path.getsize(p)
        except OSError:
            missing.append(p)
    encoded = int(raw * _B64_OVERHEAD)
    return {
        "raw": raw, "encoded": encoded, "missing": missing,
        "over": encoded > GMAIL_MAX_BYTES,
        "warn": encoded > GMAIL_MAX_BYTES * _ATTACH_WARN_AT,
        "text": f"{_human_size(raw)} ({_human_size(encoded)} when sent)",
    }


# ── 3. Forgotten-attachment detector ──────────────────────────────────────────
#
# Two independent tests, because one word list alone is either too noisy or
# too blind:
#   • a straight word list ("attached", "bifogar", ...), and
#   • a proximity rule — a sending verb and a file noun on the SAME line,
#     which is how "jag skickar med filen" or "här kommer rapporten som fil"
#     is written in practice.

_ATTACH_WORDS = [
    "attached", "attaching", "attachment", "attachments", "i attach",
    "enclosed", "enclosing", "please find", "see attached", "find attached",
    "bifogar", "bifogat", "bifogad", "bifogade", "bilaga", "bilagor",
    "bifogas", "se bifogad", "medskickad", "medskickat",
]
_SEND_VERBS = ["skickar", "sänder", "bifoga", "sending", "send you", "here is",
               "här kommer", "här är"]
_FILE_NOUNS = ["fil", "filen", "filer", "filerna", "dokument", "dokumentet",
               "faktura", "fakturan", "rapport", "rapporten", "bild", "bilden",
               "pdf", "file", "document", "invoice", "report", "picture",
               "spreadsheet", "kalkyl"]


def _mentions_attachment(subject: str, body: str) -> str:
    """Return the phrase that suggests an attachment, or '' if none.

    The returned string is shown in the warning so the question is concrete
    ("you wrote 'bifogar'") instead of a vague nag."""
    text = f"{subject or ''}\n{body or ''}"
    low  = text.lower()
    # Ignore quoted text (lines starting with '>') and anything after the
    # signature separator — a quoted "attached" from THEIR mail is not a
    # promise that YOU are attaching something.
    lines = []
    for ln in low.splitlines():
        s = ln.strip()
        if s.startswith(">"):
            continue
        if s in ("--", "-- "):
            break
        lines.append(s)
    low_clean = "\n".join(lines)

    for w in _ATTACH_WORDS:
        if w in low_clean:
            return w
    for ln in lines:
        if any(v in ln for v in _SEND_VERBS) and any(n in ln for n in _FILE_NOUNS):
            return ln.strip()[:60]
    return ""


# ── 3b. Minimal PDF READER (no external dependency) ───────────────────────────
#
# Issu 2026-08-23: "Jag ser inte produktens namn eller mottagarens stad."
#
# A Tradera shipping mail says who bought it and what it cost, but the two
# things he actually needs when the QR code is on screen — the TOWN it is
# going to and the TITLE of the game — are not in the mail at all. They are
# inside the attached Kvitto.pdf and Fraktsedel.pdf. (Checked: the HTML body
# of every one of his shipping receipts contains "Zwickau" exactly zero times.)
#
# So the program has to read a PDF. PyMuPDF would do it in one line and is not
# an option — this file must keep working as a single .py and as a one-file
# EXE with nothing pip-installed (same rule as the PDF writer below). Three
# things make a stdlib reader enough here:
#
#   • the content streams are plain /FlateDecode, so zlib unpacks them;
#   • text is a handful of operators — Tf, Td/TD/Tm/T*, Tj/TJ — and the
#     strings are right there in the stream;
#   • the awkward part is the ENCODING. A carrier label uses subset fonts
#     where the byte in the stream is a glyph id, not a character: "SWEDEN"
#     is stored as "6:('(1" and "Dominik" as "\x00'\x00R\x00P…". Every such
#     font carries a /ToUnicode CMap that says what its codes mean, so the
#     reader resolves each font resource to its CMap and translates.
#
# Two traps found while building it, both worth keeping written down:
#
#   • the CMap must be looked up PER RESOURCE DICTIONARY. Merging all fonts
#     into one name→CMap table looked fine until "/F1" meant Helvetica on the
#     page and a subset font inside the label's Form XObject: the first F1 won
#     and the receipt text came out as mojibake.
#   • breaking a line on every Td is wrong. PostNord's receipt positions each
#     GLYPH with its own "<n> 0 Td", so "Kvitto" arrived as six one-letter
#     lines. Only a move that changes Y starts a new line.

_PDF_OBJ_RE      = _re.compile(rb'(?<![0-9])(\d+)\s+\d+\s+obj\b')
_PDF_STREAM_RE   = _re.compile(rb'stream\r?\n')
_PDF_FONTRES_RE  = _re.compile(rb'/Font\s*<<(.*?)>>', _re.S)
_PDF_FONTIND_RE  = _re.compile(rb'/Font\s+(\d+)\s+\d+\s+R')
_PDF_FREF_RE     = _re.compile(rb'/([A-Za-z0-9#+.\-_]+)\s+(\d+)\s+\d+\s+R')
_PDF_TOUNI_RE    = _re.compile(rb'/ToUnicode\s+(\d+)\s+\d+\s+R')
_PDF_HEX_RE      = _re.compile(rb'<([0-9A-Fa-f\s]*)>')
_PDF_CSR_RE      = _re.compile(rb'begincodespacerange(.*?)endcodespacerange', _re.S)
_PDF_BFCHAR_RE   = _re.compile(rb'beginbfchar(.*?)endbfchar', _re.S)
_PDF_BFRANGE_RE  = _re.compile(rb'beginbfrange(.*?)endbfrange', _re.S)
_PDF_BFR_LINE_RE = _re.compile(
    rb'<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>\s*(?:<([0-9A-Fa-f]+)>|\[(.*?)\])', _re.S)
_PDF_RESIND_RE   = _re.compile(rb'/Resources\s+(\d+)\s+\d+\s+R')
_PDF_RESDIC_RE   = _re.compile(rb'/Resources\s*<<')
_PDF_PAGE_RE     = _re.compile(rb'/Type\s*/Page[^s]')
_PDF_FORM_RE     = _re.compile(rb'/Subtype\s*/Form\b')
_PDF_CONT_RE     = _re.compile(rb'/Contents\s+(\d+)\s+\d+\s+R')
_PDF_CONTARR_RE  = _re.compile(rb'/Contents\s*\[(.*?)\]', _re.S)
_PDF_REF_RE      = _re.compile(rb'(\d+)\s+\d+\s+R')

_PDF_TOKEN_RE = _re.compile(
    rb'/([A-Za-z0-9#+.\-_]+)\s+[-+\d.]+\s+Tf'             # 1 = font switch
    rb'|((?:[-+\d.]+\s+){2})T[dD]\b'                      # 2 = Td / TD
    rb'|((?:[-+\d.]+\s+){6})Tm\b'                         # 3 = Tm
    rb'|(\((?:[^()\\]|\\.|\((?:[^()\\]|\\.)*\))*\))'      # 4 = literal string
    rb'|(<[0-9A-Fa-f\s]*>)'                               # 5 = hex string
    rb'|\bT\*|\bBT\b|\bET\b',
    _re.S)

_PDF_R_ESCAPES = {0x6e: 10, 0x72: 13, 0x74: 9, 0x62: 8, 0x66: 12,
                  0x28: 0x28, 0x29: 0x29, 0x5c: 0x5c}


def _pdf_unescape(b: bytes) -> bytes:
    """PDF literal-string escapes: \\n \\t \\( \\\\ \\ddd and a line
    continuation at the end of a line."""
    out = bytearray()
    i, n = 0, len(b)
    while i < n:
        c = b[i]
        if c == 0x5c and i + 1 < n:
            nxt = b[i + 1]
            if nxt in _PDF_R_ESCAPES:
                out.append(_PDF_R_ESCAPES[nxt]); i += 2; continue
            if 0x30 <= nxt <= 0x37:                       # octal \ddd
                j, digits = i + 1, b''
                while j < n and len(digits) < 3 and 0x30 <= b[j] <= 0x37:
                    digits += bytes([b[j]]); j += 1
                out.append(int(digits, 8) & 0xFF); i = j; continue
            if nxt in (0x0a, 0x0d):                       # continuation
                i += 2
                if nxt == 0x0d and i < n and b[i] == 0x0a:
                    i += 1
                continue
            out.append(nxt); i += 2; continue
        out.append(c); i += 1
    return bytes(out)


def _pdf_objects(data: bytes) -> dict:
    """{object number: body bytes}. The end of an object is found by walking
    PAST any stream section first, so binary stream content that happens to
    read like "12 0 obj" cannot cut the real object short."""
    objs = {}
    for m in _PDF_OBJ_RE.finditer(data):
        num, pos = int(m.group(1)), m.end()
        s = _PDF_STREAM_RE.search(data, pos, pos + 4000)
        e = data.find(b'endobj', pos)
        if s and (e < 0 or s.start() < e):
            es = data.find(b'endstream', s.end())
            e = data.find(b'endobj', es if es >= 0 else s.end())
        if e < 0:
            e = len(data)
        objs.setdefault(num, data[pos:e])
    return objs


def _pdf_stream_bytes(body: bytes):
    """The decoded stream of one object, or None when there is none (or it
    uses a filter this reader does not implement, e.g. an image codec)."""
    m = _PDF_STREAM_RE.search(body)
    if not m:
        return None
    end = body.find(b'endstream', m.end())
    raw = body[m.end():end if end >= 0 else len(body)]
    head = body[:m.start()]
    if b'/FlateDecode' in head:
        for attempt in (lambda: zlib.decompress(raw),
                        lambda: zlib.decompressobj().decompress(raw),
                        lambda: zlib.decompressobj(-15).decompress(raw)):
            try:
                return attempt()
            except Exception:
                continue
        return None
    if b'/Filter' in head:
        return None
    return raw


def _pdf_hex_to_str(h: bytes) -> str:
    h = _re.sub(rb'\s', b'', h)
    if len(h) % 2:
        h += b'0'
    try:
        return bytes.fromhex(h.decode('ascii')).decode('utf-16-be', 'replace')
    except Exception:
        return ''


def _pdf_parse_cmap(txt: bytes):
    """A /ToUnicode CMap → ({code: text}, bytes per code), or None."""
    code_len = 2
    m = _PDF_CSR_RE.search(txt)
    if m:
        first = _PDF_HEX_RE.search(m.group(1))
        if first:
            code_len = max(1, len(_re.sub(rb'\s', b'', first.group(1))) // 2)
    table = {}
    for blk in _PDF_BFCHAR_RE.findall(txt):
        pairs = _PDF_HEX_RE.findall(blk)
        for i in range(0, len(pairs) - 1, 2):
            try:
                src = int(_re.sub(rb'\s', b'', pairs[i]), 16)
            except Exception:
                continue
            table[src] = _pdf_hex_to_str(pairs[i + 1])
    for blk in _PDF_BFRANGE_RE.findall(txt):
        for lo, hi, dst, arr in _PDF_BFR_LINE_RE.findall(blk):
            try:
                lo_i, hi_i = int(lo, 16), int(hi, 16)
            except Exception:
                continue
            if hi_i < lo_i or hi_i - lo_i > 65535:
                continue
            if dst:
                base = _pdf_hex_to_str(dst)
                if not base:
                    continue
                start, head = ord(base[-1]), base[:-1]
                for k in range(hi_i - lo_i + 1):
                    table[lo_i + k] = head + chr(start + k)
            elif arr:
                for k, item in enumerate(_PDF_HEX_RE.findall(arr)):
                    if lo_i + k > hi_i:
                        break
                    table[lo_i + k] = _pdf_hex_to_str(item)
    return (table, code_len) if table else None


def _pdf_resources_of(body: bytes, objs: dict) -> bytes:
    m = _PDF_RESIND_RE.search(body)
    if m:
        return objs.get(int(m.group(1)), b'')[:8000]
    m = _PDF_RESDIC_RE.search(body)
    if m:
        return body[m.end() - 2:m.end() + 8000]
    return b''


def _pdf_fonts_in(res: bytes, objs: dict, cache: dict) -> dict:
    """{resource name: cmap} for ONE /Resources dict — see the note above on
    why this may not be merged across the document."""
    names, blocks = {}, list(_PDF_FONTRES_RE.findall(res))
    m = _PDF_FONTIND_RE.search(res)
    if m:                          # "/Font 17 0 R" — the dict is an object away
        blocks.append(objs.get(int(m.group(1)), b'')[:8000])
    for blk in blocks:
        for nm, num in _PDF_FREF_RE.findall(blk):
            names.setdefault(nm.decode('latin-1'), int(num))
    out = {}
    for nm, num in names.items():
        body = objs.get(num)
        if not body:
            continue
        m = _PDF_TOUNI_RE.search(body)
        if not m:
            continue
        tu = int(m.group(1))
        if tu not in cache:
            st = _pdf_stream_bytes(objs.get(tu, b'') or b'')
            cache[tu] = _pdf_parse_cmap(st) if st else None
        if cache[tu]:
            out[nm] = cache[tu]
    return out


def _pdf_decode_string(raw: bytes, cmap, is_hex: bool) -> str:
    if cmap:
        table, clen = cmap
        return ''.join(table.get(int.from_bytes(raw[i:i + clen], 'big'), '')
                       for i in range(0, len(raw) - clen + 1, clen))
    if is_hex:
        return raw.decode('utf-16-be', 'replace')
    return raw.decode('cp1252', 'replace')


def _pdf_nums(blob: bytes) -> list:
    out = []
    for t in blob.split():
        try:
            out.append(float(t))
        except ValueError:
            out.append(0.0)
    return out


def _pdf_stream_lines(st: bytes, fonts: dict, out: list):
    """One content stream → text lines, split on downward moves only."""
    cur, cmap, y = [], None, None

    def flush():
        if cur:
            out.append(''.join(cur))
            del cur[:]

    for m in _PDF_TOKEN_RE.finditer(st):
        font, td, tm, lit, hexs = (m.group(1), m.group(2), m.group(3),
                                   m.group(4), m.group(5))
        if font is not None:
            cmap = fonts.get(font.decode('latin-1'))
        elif lit is not None:
            cur.append(_pdf_decode_string(_pdf_unescape(lit[1:-1]), cmap, False))
        elif hexs is not None:
            hx = _re.sub(rb'\s', b'', hexs[1:-1])
            if len(hx) % 2:
                hx += b'0'
            try:
                cur.append(_pdf_decode_string(
                    bytes.fromhex(hx.decode('ascii')), cmap, True))
            except Exception:
                pass
        elif td is not None:
            n = _pdf_nums(td)
            if len(n) >= 2 and abs(n[1]) > 0.01:
                flush()
                y = (y or 0.0) + n[1]
        elif tm is not None:
            n = _pdf_nums(tm)
            if len(n) >= 6:
                if y is None or abs(n[5] - y) > 0.5:
                    flush()
                y = n[5]
        else:                                   # T* / BT / ET
            flush()
    flush()


def _pdf_text_lines(data: bytes) -> list:
    """Every text line in a PDF, in stream order. Never raises: a PDF this
    reader cannot follow simply answers with an empty list, and the caller
    falls back to what the mail body knows."""
    try:
        objs = _pdf_objects(data)
        cache, lines, done, units = {}, [], set(), []
        for num, body in objs.items():
            head = body[:3000]
            if _PDF_PAGE_RE.search(head):
                res = _pdf_resources_of(body, objs)
                for c in _PDF_CONT_RE.findall(head):
                    units.append((int(c), res))
                arr = _PDF_CONTARR_RE.search(head)
                if arr:
                    for c in _PDF_REF_RE.findall(arr.group(1)):
                        units.append((int(c), res))
            elif _PDF_FORM_RE.search(head):
                units.append((num, _pdf_resources_of(body, objs)))
        for num, res in units:
            body = objs.get(num)
            if body is None or num in done:
                continue
            done.add(num)
            st = _pdf_stream_bytes(body)
            if not st or b'BT' not in st:
                continue
            _pdf_stream_lines(st, _pdf_fonts_in(res, objs, cache), lines)
        if not lines:                       # last resort: every text stream
            for num, body in objs.items():
                if num in done:
                    continue
                st = _pdf_stream_bytes(body)
                if st and b'BT' in st and b'begincmap' not in st[:400]:
                    _pdf_stream_lines(st, {}, lines)
        return [s for s in (x.strip() for x in lines) if s]
    except Exception as e:
        log.debug("PDF text extraction failed: %s", e)
        return []


# ── 3c. What a shipping receipt actually says (DEL 09m) ───────────────────────
#
# Issu 2026-08-23, about three Tradera receipts that arrived within two
# minutes of each other: "Jag ser inte produktens namn eller mottagarens stad.
# Jag ser mottagarens namn." Three identical subjects, three identical
# senders, three QR codes named QrCode-<number>.png — nothing on screen says
# which parcel is which until you open all three and read the PDFs.
#
# This turns each receipt into a handful of facts: TITLE, CITY, COUNTRY, the
# buyer's alias and real name, the carrier, the amount and the tracking
# number. They then show up in three places: the message list row, a summary
# strip at the top of the opened message, and the filename offered when you
# save the QR code.
#
# Where each fact comes from, and why:
#   • TITLE — the label's "Titel..........." is authoritative but Tradera
#     truncates it to the width of the box ("…Revised 4th" / "E"), so the mail
#     BODY is searched for the line that starts with the truncated text and
#     the full title is used. When there is no label, the body's own layout
#     (alias / buyer / title / "Objektnr") supplies it.
#   • CITY — the Kvitto's "Mottagare:" block. Tradera writes it over three
#     lines ending in "08056 Zwickau"; PostNord writes one comma-separated
#     line ending in the country IN SWEDISH, sometimes with the buyer's
#     e-mail tacked on after it (which is why addresses are filtered for "@"
#     before the last field is read as a country).
#   • COUNTRY — only the carrier LABEL knows. The Kvitto for the German
#     parcel names Zwickau and never says Germany. Labels state it three
#     ways: a country name ("SWEDEN"), a bare code on its own line ("DE"), or
#     a code glued to the postcode ("ES-46183 LA ELIANA", "SE 726 31
#     Skultuna"). Every label also carries the SENDER's Swedish address, so
#     SE can only win when nothing else appears.
#
# "If not Sweden, then the country" is Issu's own rule for the filename, and
# it is better: a town called Zwickau tells him nothing, "Tyskland" tells him
# customs paperwork. When the country cannot be established the CITY is used —
# never a guess of "Sweden".
#
# Measured against his own cache: 74 shipping receipts back to March, 73 fully
# resolved (the 74th is a "your parcel was too heavy" notice with no
# attachments at all), including parcels to Germany, France, Spain, Lithuania,
# Hungary, Austria, Czechia, Ireland, Belgium, Switzerland, the UK and the US.

_SHIP_ISO = {
    "SE": "Sverige", "DE": "Tyskland", "DK": "Danmark", "NO": "Norge",
    "FI": "Finland", "GB": "Storbritannien", "UK": "Storbritannien",
    "NL": "Nederländerna", "BE": "Belgien", "FR": "Frankrike",
    "ES": "Spanien", "IT": "Italien", "PL": "Polen", "AT": "Österrike",
    "CH": "Schweiz", "CZ": "Tjeckien", "EE": "Estland", "LV": "Lettland",
    "LT": "Litauen", "IE": "Irland", "PT": "Portugal", "HU": "Ungern",
    "SK": "Slovakien", "SI": "Slovenien", "RO": "Rumänien", "BG": "Bulgarien",
    "GR": "Grekland", "HR": "Kroatien", "LU": "Luxemburg", "IS": "Island",
    "MT": "Malta", "CY": "Cypern", "RS": "Serbien", "UA": "Ukraina",
    "TR": "Turkiet", "US": "USA", "CA": "Kanada", "AU": "Australien",
    "NZ": "Nya Zeeland", "JP": "Japan", "SG": "Singapore",
}

_SHIP_CNAME = {
    "SVERIGE": "SE", "SWEDEN": "SE", "SCHWEDEN": "SE", "SUEDE": "SE",
    "TYSKLAND": "DE", "GERMANY": "DE", "DEUTSCHLAND": "DE",
    "DANMARK": "DK", "DENMARK": "DK", "DÄNEMARK": "DK",
    "NORGE": "NO", "NORWAY": "NO", "FINLAND": "FI", "SUOMI": "FI",
    "STORBRITANNIEN": "GB", "UNITED KINGDOM": "GB", "GREAT BRITAIN": "GB",
    "ENGLAND": "GB", "NEDERLÄNDERNA": "NL", "NETHERLANDS": "NL",
    "HOLLAND": "NL", "BELGIEN": "BE", "BELGIUM": "BE",
    "FRANKRIKE": "FR", "FRANCE": "FR", "SPANIEN": "ES", "SPAIN": "ES",
    "ESPAÑA": "ES", "ITALIEN": "IT", "ITALY": "IT", "ITALIA": "IT",
    "POLEN": "PL", "POLAND": "PL", "POLSKA": "PL",
    "ÖSTERRIKE": "AT", "AUSTRIA": "AT", "ÖSTERREICH": "AT",
    "SCHWEIZ": "CH", "SWITZERLAND": "CH", "TJECKIEN": "CZ",
    "CZECH REPUBLIC": "CZ", "CZECHIA": "CZ", "ESTLAND": "EE",
    "ESTONIA": "EE", "LETTLAND": "LV", "LATVIA": "LV", "LITAUEN": "LT",
    "LITHUANIA": "LT", "IRLAND": "IE", "IRELAND": "IE",
    "PORTUGAL": "PT", "UNGERN": "HU", "HUNGARY": "HU",
    "SLOVAKIEN": "SK", "SLOVAKIA": "SK", "SLOVENIEN": "SI",
    "SLOVENIA": "SI", "RUMÄNIEN": "RO", "ROMANIA": "RO",
    "BULGARIEN": "BG", "BULGARIA": "BG", "GREKLAND": "GR", "GREECE": "GR",
    "KROATIEN": "HR", "CROATIA": "HR", "LUXEMBURG": "LU",
    "LUXEMBOURG": "LU", "ISLAND": "IS", "ICELAND": "IS",
    "USA": "US", "UNITED STATES": "US", "KANADA": "CA", "CANADA": "CA",
    "AUSTRALIEN": "AU", "AUSTRALIA": "AU", "JAPAN": "JP",
}

# "08056 Zwickau", "SE 726 31 Skultuna", "533 96 Götene", "14131 HUDDINGE"
_SHIP_ZIPCITY_RE = _re.compile(
    r'^\s*(?:[A-Z]{2}[-\s]+)?\d{3}\s?\d{2}\s+(.{2,60})$')
_SHIP_ISOLINE_RE = _re.compile(r'^([A-Z]{2})$')
_SHIP_ISOZIP_RE  = _re.compile(r'^([A-Z]{2})[-\s]\s?\d{3,6}\s?\d{0,2}\s+\S')
_SHIP_MOTT_RE    = _re.compile(r'^Mottagare\s*:?\s*(.*)$', _re.I)
_SHIP_TITLE_RE   = _re.compile(r'^Titel\.*\s*:?\s*(.+)$')
_SHIP_BUYER_RE   = _re.compile(r'^K[öo]pare\.*\s*:?\s*(.+)$')
_SHIP_ALIAS_RE   = _re.compile(r'^K[öo]parens alias\s*:?\s*(.+)$')
_SHIP_ITEM_RE    = _re.compile(r'^Objektnr\.*\s*:?\s*([\d\s]+)$')
_SHIP_KOLLI_RE   = _re.compile(r'^Kolli-ID\s*:?\s*([\w\s]+)$')
_SHIP_CARRIER_RE = _re.compile(
    r'^(DB\s*Schenker|Schenker|DSV|DHL|PostNord[\w ]*|Budbee|Instabox|'
    r'Early\s*Bird|UPS|GLS|FedEx|Airmee)\s*,\s*(?:upp till\s*)?'
    r'([\d.,]+\s*(?:kg|g)\b.*)$', _re.I)
_SHIP_AMOUNT_RE  = _re.compile(r'^[\d\s]+[,.]\d\d\s*kr$')
_SHIP_STOP_RE    = _re.compile(
    r'^(K[öo]parens alias|Momsbelopp|Moms\b|Totalt|Avs[äa]ndare|inkl\.|'
    r'Momsgrundande|Ej momsgrundande|Kolli-ID|Tj[äa]nst)', _re.I)

# ── Who you actually hand the parcel to (Issu 2026-08-23) ────────────────────
# "Få in i qr-kod-grejen, vilken operatör som det är (Post (i stället för
#  Postnord), DSV, DHL)" — the carrier decides WHICH shop you walk to (ICA
# Kvantum for DSV, Pressbyrån for DHL), so it belongs in the filename, and it
# goes FIRST: the folder then groups itself by the errand.
#
# His spelling, not the carrier's: "Post", never "PostNord paket".
#
# DB Schenker IS DSV (Issu 2026-08-23: "Schenker har bytt namn till DSV").
# DSV bought Schenker's parcel network, so the receipts from January that say
# "DB Schenker" and the ones from August that say "DSV" are the same company
# and the same counter — one name, or the folder would sort one errand into
# two piles.
_SHIP_CARRIER_SHORT = (
    ("postnord", "Post"), ("db schenker", "DSV"), ("schenker", "DSV"),
    ("dsv", "DSV"), ("dhl", "DHL"), ("budbee", "Budbee"),
    ("instabox", "Instabox"), ("early bird", "EarlyBird"), ("ups", "UPS"),
    ("gls", "GLS"), ("fedex", "FedEx"), ("airmee", "Airmee"),
)
# The name as it appears in a PDF, for the "nobody wrote 'X, 3 kg'" fallback.
_SHIP_CARRIER_WORDS = _re.compile(
    r'\b(DB\s*Schenker|Schenker|DSV|DHL|PostNord|Budbee|Instabox|'
    r'Early\s*Bird|UPS|GLS|FedEx|Airmee)\b', _re.I)
# …and last of all, who sent the receipt.
_SHIP_SENDER_CARRIER = (("postnord.com", "Post"), ("dhl.com", "DHL"),
                        ("dbschenker.com", "DSV"), ("dsv.com", "DSV"))

# The senders whose mail is worth looking inside at all.
_SHIP_SENDERS = ("tradera.com", "postnord.com", "dhl.com", "dbschenker.com",
                 "vinted", "zhipster")


def _ship_carrier_short(name: str) -> str:
    """"PostNord paket" → "Post", "DB Schenker" → "DSV" (same company)."""
    low = (name or "").strip().lower()
    if not low:
        return ""
    for needle, short in _SHIP_CARRIER_SHORT:
        if needle in low:
            return short
    return _re.sub(r'[^\w &+-]', '', name.strip())[:14]


def _ship_city_from_block(block: list):
    """(city, country) out of the lines under "Mottagare:"."""
    city = country = ""
    for ln in block:
        # PostNord writes the whole address on ONE comma-separated line and
        # ends it with the country in Swedish ("…, Cranbrook, Storbritannien")
        # — sometimes followed by the buyer's e-mail address, which is why
        # anything with an "@" goes first. Left in, the e-mail was read as the
        # country and the country as the town.
        if ln.count(",") >= 2:
            parts = [p.strip() for p in ln.split(",") if p.strip()]
            parts = [p for p in parts if "@" not in p]
            if parts:
                last = parts[-1]
                if last.upper() in _SHIP_CNAME or (
                        len(parts) >= 3 and not _re.search(r'\d', last)):
                    country = last
                    parts = parts[:-1]
            for p in reversed(parts):
                m = _SHIP_ZIPCITY_RE.match(p)
                if m:
                    city = m.group(1).strip(); break
                if p and not _re.search(r'\d', p):
                    city = p; break
            if city:
                return city, country
    for ln in reversed(block):
        m = _SHIP_ZIPCITY_RE.match(ln)
        if m:
            return m.group(1).strip(), country
    return city, country


def _ship_read_receipt(lines: list) -> dict:
    """What a Kvitto*.pdf knows: recipient, city, country, alias, carrier,
    amount, tracking number."""
    out = {}
    for i, ln in enumerate(lines):
        m = _SHIP_MOTT_RE.match(ln)
        if not m:
            continue
        block = []
        if m.group(1).strip():
            block.append(m.group(1).strip())
        for nxt in lines[i + 1:i + 6]:
            if _SHIP_STOP_RE.match(nxt):
                break
            block.append(nxt)
        if block:
            out.setdefault("recipient", block[0].rstrip(",").strip())
            city, country = _ship_city_from_block(block)
            if city:
                out.setdefault("city", city)
            if country:
                out.setdefault("country_name", country)
        break
    for i, ln in enumerate(lines):
        m = _SHIP_ALIAS_RE.match(ln)
        if m:
            out.setdefault("alias", m.group(1).strip())
        m = _SHIP_KOLLI_RE.match(ln)
        if m:
            out.setdefault("tracking", _re.sub(r'\s', '', m.group(1)))
        m = _SHIP_CARRIER_RE.match(ln)
        if m:
            out.setdefault("carrier", m.group(1).strip())
            out.setdefault("weight", m.group(2).strip())
            nxt = lines[i + 1] if i + 1 < len(lines) else ""
            if _SHIP_AMOUNT_RE.match(nxt):
                out.setdefault("amount", nxt.strip())
    return out


def _ship_country_from_label(lines: list) -> str:
    """The destination country code off a carrier label. Every label carries
    the sender's Swedish address too, so SE only wins when nothing else is
    there — and "no country found at all" answers "" rather than guessing."""
    counts = {}
    for ln in lines:
        up = ln.strip().upper()
        code = ""
        if up in _SHIP_CNAME:
            code = _SHIP_CNAME[up]
        else:
            m = _SHIP_ISOLINE_RE.match(up)
            if m and m.group(1) in _SHIP_ISO:
                code = m.group(1)
            else:
                m = _SHIP_ISOZIP_RE.match(up)
                if m and m.group(1) in _SHIP_ISO:
                    code = m.group(1)
        if code:
            counts[code] = counts.get(code, 0) + 1
    foreign = {k: v for k, v in counts.items() if k != "SE"}
    if foreign:
        return max(foreign.items(), key=lambda kv: kv[1])[0]
    return "SE" if counts else ""


def _shipping_facts(body: str, attach: dict, sender: str = "") -> dict:
    """The facts of one shipping receipt. Empty dict when the mail is not one
    (or when its PDFs have not been downloaded yet)."""
    facts = {}
    blines = [l.strip() for l in (body or "").splitlines() if l.strip()]

    receipt_lines, label_lines = [], []
    for fn, data in (attach or {}).items():
        if not fn.lower().endswith(".pdf") or not data:
            continue
        lines = _pdf_text_lines(data)
        if not lines:
            continue
        low = fn.lower()
        if ("kvitto" in low or "receipt" in low
                or any(l.lower().startswith("kvitto") for l in lines[:3])):
            receipt_lines += lines
        else:
            label_lines += lines
    facts.update(_ship_read_receipt(receipt_lines))
    if "city" not in facts and label_lines:
        facts.update({k: v for k, v in _ship_read_receipt(label_lines).items()
                      if k not in facts})

    for ln in label_lines:
        m = _SHIP_TITLE_RE.match(ln)
        if m:
            facts["title"] = m.group(1).strip()
        m = _SHIP_BUYER_RE.match(ln)
        if m and "alias" not in facts:
            facts["alias"] = m.group(1).strip()
        m = _SHIP_ITEM_RE.match(ln)
        if m:
            facts["item_no"] = _re.sub(r'\s', '', m.group(1))
    # The label cuts the title to the width of its box; the body has it whole.
    stub = facts.get("title", "")
    if stub:
        head = stub[:18]
        for ln in blines:
            if ln.startswith(head) and len(ln) > len(stub):
                facts["title"] = ln.strip()
                break
    elif blines:
        # No label (or an unreadable one): the mail's own layout is
        # alias / buyer / title / "Objektnr".
        for i, ln in enumerate(blines):
            if ln.startswith("Objektnr") and i >= 3:
                cand = blines[i - 1]
                if 2 < len(cand) < 200 and "http" not in cand:
                    facts["title"] = cand
                    facts.setdefault("recipient", blines[i - 2])
                    facts.setdefault("alias", blines[i - 3])
                break
    # ── Who you hand it to (Issu 2026-08-23) ─────────────────────────────
    # Four sources. The MAIL BODY first, because it is the one he read; then
    # the Kvitto's own "DSV, 1 kg" line, which names the DROP-OFF network.
    # (They can disagree on the NAME — January's receipts say "DB Schenker"
    # where August's say DSV — but _ship_carrier_short answers "DSV" for both,
    # because DSV bought Schenker and it is one counter.) Deliberately NOT the
    # label's own branding: the German parcel's label is GLS from end to end,
    # but you still hand it in at DSV.
    for ln in blines:
        m = _SHIP_CARRIER_RE.match(ln)
        if m:
            facts["carrier"] = m.group(1).strip()
            facts.setdefault("weight", m.group(2).strip())
            break
    if not facts.get("carrier"):
        # Nobody wrote "X, 3 kg" — PostNord's own receipts name a service
        # ("Tracked letter") instead. Take the first carrier NAME in the
        # papers, receipt before label. Lines carrying an address or a URL
        # are skipped: every PostNord receipt ends with
        # "kundservice.digital.se@postnord.com", which is not evidence of
        # anything and would out-vote a real carrier line on someone else's
        # receipt.
        for chunk in (receipt_lines, label_lines):
            hit = ""
            for ln in chunk[:80]:
                if "@" in ln or "://" in ln or "www." in ln:
                    continue
                m = _SHIP_CARRIER_WORDS.search(ln)
                if m:
                    hit = m.group(1).strip()
                    break
            if hit:
                facts["carrier"] = hit
                break
    if not facts.get("carrier"):
        low = (sender or "").lower()
        for domain, short in _SHIP_SENDER_CARRIER:
            if domain in low:
                facts["carrier"] = short
                break
    if facts.get("carrier"):
        facts["carrier_short"] = _ship_carrier_short(facts["carrier"])
    # Knowing ONLY the carrier is still worth something: a DHL drop-off
    # receipt carries a QR code and nothing else, and "00-DHL---" in front of
    # it still says which errand it belongs to.
    if not facts:
        return {}

    code = ""
    cname = facts.get("country_name", "")
    if cname:
        code = _SHIP_CNAME.get(cname.upper(), "")
    if not code:
        code = _ship_country_from_label(label_lines)
    abroad = bool(code) and code != "SE"
    facts["country_code"] = code
    facts["country"] = _SHIP_ISO.get(code, cname)
    facts["abroad"] = abroad
    # Issu's rule: the town when it stays in Sweden, the COUNTRY when it does
    # not. Nothing known → the town, never a guessed country.
    facts["place"] = ((facts.get("country") or facts.get("city", "")) if abroad
                      else facts.get("city", ""))
    return facts


def _ship_is_shipping_mail(msg: dict) -> bool:
    """Cheap pre-check so the PDF reader is never woken for ordinary mail."""
    frm = (msg.get("from") or "").lower()
    if not any(s in frm for s in _SHIP_SENDERS):
        return False
    names = [n.lower() for n in (msg.get("attachments") or [])]
    return any(n.endswith(".pdf") for n in names) or bool(
        _re.search(r'frakt|kvitto|shipping|label|receipt',
                   (msg.get("subject") or ""), _re.I))


def _ship_clean_part(s: str, limit: int) -> str:
    """One field, safe as part of a Windows filename."""
    s = _re.sub(r'[\\/:*?"<>|]', "-", (s or "").strip())
    s = _re.sub(r'\s+', " ", s).strip(" .-")
    return s[:limit].strip(" .-")


def _ship_prefixed_name(facts: dict, fname: str) -> str:
    """"00-DSV---Tyskland---Tärning, svaga siffror---QrCode-3505190755.png".

    Issu's own format, and the "00-" is load-bearing: it sorts the parcels he
    still has to hand in to the top of the folder.

    The CARRIER comes first (2026-08-23) because it is the errand: DSV goes to
    ICA Kvantum, DHL goes to Pressbyrån, so sorting by name puts one trip's
    parcels together. Then the town (or the country when it leaves Sweden),
    then the title."""
    carrier = _ship_clean_part(facts.get("carrier_short", "")
                               or _ship_carrier_short(facts.get("carrier", "")),
                               14)
    place = _ship_clean_part(facts.get("place", ""), 40)
    # 60 characters of title: enough to tell two Kingdomino boxes apart, short
    # enough that the whole path stays inside Windows' 260-character limit
    # even in a deep folder.
    title = _ship_clean_part(facts.get("title", ""), 60)
    parts = [p for p in (carrier, place, title) if p]
    if not parts:
        return fname
    return "00-" + "---".join(parts) + "---" + fname


def _ship_row_tag(facts: dict) -> str:
    """The short "which parcel is this" tag for a message-list row."""
    if not facts:
        return ""
    place = facts.get("place") or facts.get("city") or ""
    title = facts.get("title", "")
    if place and title:
        return f"{place} · {title}"
    return place or title


# The facts are cached on disk: reading two PDFs is a few milliseconds, but
# the message LIST asks for every visible row, and after a restart the bodies
# are not in memory at all — without the cache the rows would go blank again
# until each message was opened.
_SHIP_F = os.path.join(_ACCOUNTS_DIR, "shipping.json")
# Bumped whenever a new fact is added OR an old one changes meaning, so an
# entry cached by an older build is read once more instead of serving a stale
# answer for ever. 2 = the carrier arrived; 3 = Schenker became DSV.
_SHIP_FACTS_V = 3


def _load_ship_facts() -> dict:
    return _load_json_store(_SHIP_F, {"facts": dict}, "shipping facts")


def _save_ship_facts(store: dict):
    _save_json_store(_SHIP_F, store, "shipping facts")


def _ship_prune(store: dict, keep: int = 4000):
    """Keep the store from growing for ever — oldest entries out first."""
    facts = store.get("facts") or {}
    if len(facts) <= keep:
        return
    for k in list(facts)[:len(facts) - keep]:
        facts.pop(k, None)


# ── 4. Minimal PDF writer (no external dependency) ────────────────────────────
#
# reportlab/fpdf would be nicer, but this program must keep working as a
# single .py (and as a one-file EXE) without asking anyone to pip-install
# anything. A message is text, so a text-only PDF writer is enough: A4,
# Helvetica, hard-wrapped, one font for the header and one for the body.

_PDF_PAGE_W, _PDF_PAGE_H = 595.28, 841.89      # A4 in points
_PDF_MARGIN   = 50
_PDF_FONTSIZE = 10
_PDF_LEADING  = 13.5
_PDF_WRAP     = 92          # characters per line at 10 pt Helvetica


# The fonts are declared /WinAnsiEncoding, which is Latin-1 EXCEPT for the
# 0x80–0x9F range, where Windows put the typographic punctuation that real
# e-mail is full of: curly quotes, en/em dashes, the ellipsis, the bullet.
# Encoding straight to latin-1 turns every one of those into "?", so a normal
# message came out peppered with question marks. Map them to the WinAnsi byte
# the font actually expects.
_WINANSI_EXTRA = {
    "€": 0x80,  # €
    "‚": 0x82,  # ‚
    "ƒ": 0x83,  # ƒ
    "„": 0x84,  # „
    "…": 0x85,  # …
    "†": 0x86,  # †
    "‡": 0x87,  # ‡
    "ˆ": 0x88,  # ˆ
    "‰": 0x89,  # ‰
    "Š": 0x8a,  # Š
    "‹": 0x8b,  # ‹
    "Œ": 0x8c,  # Œ
    "Ž": 0x8e,  # Ž
    "‘": 0x91,  # ‘
    "’": 0x92,  # ’   (the apostrophe most mail clients insert)
    "“": 0x93,  # “
    "”": 0x94,  # ”
    "•": 0x95,  # •
    "–": 0x96,  # –   en dash
    "—": 0x97,  # —   em dash
    "˜": 0x98,  # ˜
    "™": 0x99,  # ™
    "š": 0x9a,  # š
    "›": 0x9b,  # ›
    "œ": 0x9c,  # œ
    "ž": 0x9e,  # ž
    "Ÿ": 0x9f,  # Ÿ
}

# Anything that is in neither Latin-1 nor WinAnsi (emoji, Greek, Cyrillic…)
# still cannot be drawn by a Type1 Helvetica. A readable stand-in beats a
# question mark for the few that turn up in practice.
_PDF_FALLBACK = {
    " ": " ", "‑": "-", "‒": "-", "―": "-",
    "′": "'", "″": '"', "­": "",
    "​": "", "‎": "", "‏": "", "﻿": "",
    "→": "->", "←": "<-", "⇒": "=>",
    "≤": "<=", "≥": ">=", "≠": "!=",
}


def _pdf_escape(s: str) -> bytes:
    """Escape a string for a PDF literal and encode it as WinAnsi."""
    out = bytearray()
    for ch in (s or ""):
        ch = _PDF_FALLBACK.get(ch, ch)
        for c in ch:
            if c in "\\()":
                out += b"\\" + c.encode("ascii")
                continue
            code = _WINANSI_EXTRA.get(c)
            if code is not None:
                out.append(code)
                continue
            try:
                out += c.encode("latin-1")
            except UnicodeEncodeError:
                out += b"?"
    return bytes(out)


def _pdf_wrap(text: str, width: int = _PDF_WRAP) -> list:
    """Word-wrap to a fixed column, keeping existing blank lines."""
    lines = []
    for raw in (text or "").splitlines():
        raw = raw.replace("\t", "    ").rstrip()
        if not raw:
            lines.append("")
            continue
        while len(raw) > width:
            cut = raw.rfind(" ", 0, width)
            if cut <= 0:
                cut = width
            lines.append(raw[:cut].rstrip())
            raw = raw[cut:].lstrip()
        lines.append(raw)
    return lines


def _write_simple_pdf(path: str, blocks: list):
    """Write a text PDF. `blocks` is a list of (style, text) where style is
    "title" (14 pt bold), "head" (10 pt bold) or "body" (10 pt regular)."""
    # 1. Flow the blocks into pages of (font_key, size, text) lines.
    pages, cur = [], []
    y_room = _PDF_PAGE_H - 2 * _PDF_MARGIN

    def _push():
        nonlocal cur
        if cur:
            pages.append(cur)
            cur = []

    used = 0.0
    for style, text in blocks:
        size    = 14 if style == "title" else _PDF_FONTSIZE
        font    = "F2" if style in ("title", "head") else "F1"
        leading = _PDF_LEADING + (5 if style == "title" else 0)
        width   = int(_PDF_WRAP * (_PDF_FONTSIZE / size))
        for ln in _pdf_wrap(text, width):
            if used + leading > y_room:
                _push()
                used = 0.0
            cur.append((font, size, leading, ln))
            used += leading
    _push()
    if not pages:
        pages = [[("F1", _PDF_FONTSIZE, _PDF_LEADING, "")]]

    # 2. Build the objects. Fixed ids: 1 catalog, 2 pages, 3 F1, 4 F2,
    #    then each page takes two ids (page, content stream).
    n_pages   = len(pages)
    page_ids  = [5 + 2 * i for i in range(n_pages)]
    cont_ids  = [6 + 2 * i for i in range(n_pages)]
    objects   = {}

    objects[1] = b"<< /Type /Catalog /Pages 2 0 R >>"
    kids = " ".join(f"{pid} 0 R" for pid in page_ids).encode("ascii")
    objects[2] = (b"<< /Type /Pages /Count " + str(n_pages).encode("ascii") +
                  b" /Kids [" + kids + b"] >>")
    objects[3] = (b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica "
                  b"/Encoding /WinAnsiEncoding >>")
    objects[4] = (b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold "
                  b"/Encoding /WinAnsiEncoding >>")

    for i, page_lines in enumerate(pages):
        parts = [b"BT"]
        y = _PDF_PAGE_H - _PDF_MARGIN
        for font, size, leading, text in page_lines:
            y -= leading
            parts.append(
                b"/" + font.encode("ascii") + b" " +
                f"{size}".encode("ascii") + b" Tf")
            parts.append(
                b"1 0 0 1 " + f"{_PDF_MARGIN:.2f} {y:.2f}".encode("ascii") +
                b" Tm")
            parts.append(b"(" + _pdf_escape(text) + b") Tj")
        parts.append(b"ET")
        stream = b"\n".join(parts)
        objects[cont_ids[i]] = (
            b"<< /Length " + str(len(stream)).encode("ascii") + b" >>\n"
            b"stream\n" + stream + b"\nendstream")
        objects[page_ids[i]] = (
            b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 " +
            f"{_PDF_PAGE_W:.2f} {_PDF_PAGE_H:.2f}".encode("ascii") + b"]"
            b" /Resources << /Font << /F1 3 0 R /F2 4 0 R >> >>"
            b" /Contents " + str(cont_ids[i]).encode("ascii") + b" 0 R >>")

    # 3. Serialize with a correct xref table.
    out     = bytearray(b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n")
    offsets = {}
    for num in sorted(objects):
        offsets[num] = len(out)
        out += (str(num).encode("ascii") + b" 0 obj\n" + objects[num] +
                b"\nendobj\n")
    xref_at = len(out)
    top     = max(objects) + 1
    out += b"xref\n0 " + str(top).encode("ascii") + b"\n"
    out += b"0000000000 65535 f \n"
    for num in range(1, top):
        off = offsets.get(num, 0)
        out += f"{off:010d} 00000 n \n".encode("ascii")
    out += (b"trailer\n<< /Size " + str(top).encode("ascii") +
            b" /Root 1 0 R >>\nstartxref\n" +
            str(xref_at).encode("ascii") + b"\n%%EOF\n")

    with open(path, "wb") as f:
        f.write(bytes(out))


def _message_to_pdf_blocks(msg: dict) -> list:
    """Turn one message into the block list _write_simple_pdf expects."""
    blocks = [("title", msg.get("subject", "(no subject)"))]
    meta = [
        f"From:    {msg.get('from_name','')} <{msg.get('from','')}>",
        f"To:      {msg.get('account_email','')}",
        f"Date:    {msg.get('date','')}",
        f"Folder:  {msg.get('_folder','')}",
    ]
    if msg.get("attachments"):
        meta.append("Files:   " + ", ".join(msg["attachments"]))
    blocks.append(("head", "\n".join(meta)))
    blocks.append(("body", "-" * _PDF_WRAP))
    blocks.append(("body", msg.get("body", "")))
    return blocks


# ── 5. Backup / restore ───────────────────────────────────────────────────────
#
# Everything the program owns lives under Helpfiles/, so a backup is simply a
# zip of the interesting files there. accounts.json goes in AS IT IS — still
# DPAPI-encrypted — which means the backup is useless to anyone else but also
# that restoring it onto ANOTHER Windows user or machine will not recover the
# passwords (DPAPI is tied to the user). The restore dialog says so.

_BACKUP_MEMBERS = [
    ("Accounts", "accounts.json"),
    ("Accounts", "autosave_rules.json"),
    ("Accounts", "contacts.json"),
    ("Accounts", "addressbook.json"),
    ("Accounts", "signatures.json"),
    ("Accounts", "templates.json"),
    ("Accounts", "snippets.json"),
    ("Accounts", "filters.json"),
    ("Accounts", "blocklist.json"),
    ("Accounts", "snooze.json"),
    ("Accounts", "outbox.json"),
    ("Accounts", "calendar.json"),
    ("Accounts", "reply_progress.json"),
    ("Accounts", "activity_log.json"),
    ("Accounts", "rule_stats.json"),
    ("",         "settings.json"),
]


def _default_backup_dir() -> str:
    return os.path.join(_FM_DIR, "Backups")


def _backup_now(dest_dir: str = "") -> str:
    """Write one .zip and return its path. Raises on failure (caller reports)."""
    dest_dir = dest_dir or _default_backup_dir()
    os.makedirs(dest_dir, exist_ok=True)
    stamp = datetime.now().strftime("%Y-%m-%d_%H%M%S")
    path  = os.path.join(dest_dir, f"Freemail_backup_{stamp}.zip")
    with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as z:
        for sub, name in _BACKUP_MEMBERS:
            src = os.path.join(_FM_DIR, sub, name) if sub else \
                  os.path.join(_FM_DIR, name)
            if os.path.isfile(src):
                z.write(src, arcname=os.path.join(sub, name) if sub else name)
        # Drafts are small and are exactly what you would hate to lose.
        if os.path.isdir(_DRAFTS_DIR):
            for fn in os.listdir(_DRAFTS_DIR):
                if fn.endswith(".json"):
                    z.write(os.path.join(_DRAFTS_DIR, fn),
                            arcname=os.path.join("Drafts", fn))
        z.writestr("BACKUP_INFO.txt",
                   "F(re)email backup\n"
                   f"Created : {_now_iso()}\n"
                   f"Machine : {platform.node()}\n\n"
                   "accounts.json contains app passwords encrypted with the\n"
                   "Windows DPAPI of the user who created this backup. They\n"
                   "can ONLY be decrypted by that same Windows user on that\n"
                   "same machine. Restoring elsewhere restores every setting\n"
                   "except the passwords, which must be entered again.\n")
    log.info("Backup written: %s", path)
    return path


def _prune_backups(dest_dir: str, keep: int):
    """Keep only the newest `keep` automatic backups."""
    try:
        files = [os.path.join(dest_dir, f) for f in os.listdir(dest_dir)
                 if f.startswith("Freemail_backup_") and f.endswith(".zip")]
        files.sort(key=os.path.getmtime, reverse=True)
        for old in files[max(1, int(keep)):]:
            os.remove(old)
    except Exception as e:
        log.warning("Could not prune backups: %s", e)


def _restore_backup(zip_path: str) -> int:
    """Restore a backup over the current configuration. Returns the number of
    files written. The CURRENT configuration is backed up first — restoring
    the wrong file should never be the end of the story."""
    try:
        _backup_now()
    except Exception as e:
        log.warning("Pre-restore backup failed (continuing): %s", e)
    written = 0
    with zipfile.ZipFile(zip_path, "r") as z:
        for member in z.namelist():
            if member.endswith("/") or member == "BACKUP_INFO.txt":
                continue
            norm = member.replace("\\", "/")
            # Only ever write inside Helpfiles, and only files we recognise —
            # a zip is untrusted input and "../" in a member name is the
            # oldest trick in the book.
            if norm.startswith("Drafts/"):
                target = os.path.join(_DRAFTS_DIR, os.path.basename(norm))
            elif norm.startswith("Accounts/"):
                target = os.path.join(_ACCOUNTS_DIR, os.path.basename(norm))
            elif norm == "settings.json":
                target = _SETTINGS_F
            else:
                continue
            os.makedirs(os.path.dirname(target), exist_ok=True)
            with z.open(member) as src, open(target, "wb") as dst:
                shutil.copyfileobj(src, dst)
            written += 1
    log.info("Restored %d file(s) from %s", written, zip_path)
    return written


# ── One-time migration: Helpfiles/ (+ Accounts/) → Helpfiles/Freemail/ ─────────
# Older versions scattered this program's data across the SHARED Helpfiles root
# (a generic settings.json) and Helpfiles/Accounts/. Everything now lives in
# Helpfiles/Freemail/. This moves the old data over on first run so nothing is
# lost. It is idempotent, conservative (it only claims files it can prove are
# ours), and never fatal — any error is logged and start-up carries on.
_FM_ACCOUNT_STORES = (
    "accounts.json", "filters.json", "blocklist.json", "calendar.json",
    "outbox.json", "snooze.json", "tags.json", "followups.json",
    "searches.json", "autosave_rules.json", "hidden_parts.json",
    "contacts.json", "addressbook.json", "signatures.json", "templates.json",
    "snippets.json",
    "browser_profiles.json", "folderplans.json", "timers.json",
    "reply_progress.json", "activity_log.json", "rule_stats.json",
)
# Keys that mark a loose settings.json as THIS program's (so we never grab
# another app's file of the same generic name).
_FM_SETTINGS_KEYS = ("win_zoomed", "sash_right", "check_interval_min",
                     "allow_server_changes", "last_folder", "notify_windows")

def _mig_move_matching(legacy_dir, new_dir, predicate) -> int:
    """Move only the entries a predicate approves out of `legacy_dir`, so a
    folder SHARED with another program keeps everything that is not ours. (This
    matters: e.g. Helpfiles/Notes also holds Notes.py's files.) Returns the
    number moved; drops the old folder only if it ends up empty."""
    n = 0
    if not os.path.isdir(legacy_dir):
        return 0
    for name in os.listdir(legacy_dir):
        if not predicate(name):
            continue
        dst = os.path.join(new_dir, name)
        if os.path.exists(dst):
            continue
        try:
            os.makedirs(new_dir, exist_ok=True)
            shutil.move(os.path.join(legacy_dir, name), dst)
            n += 1
        except Exception as e:
            log.warning("migrate %s skipped: %s", name, e)
    try:
        if not os.listdir(legacy_dir):
            os.rmdir(legacy_dir)
    except Exception:
        pass
    return n

def _migrate_to_freemail_dir():
    try:
        os.makedirs(_FM_DIR, exist_ok=True)
        # Already migrated (new settings present)? Then there is nothing to do.
        if os.path.isfile(_SETTINGS_F):
            return
        moved = 0

        # 1) The loose settings.json — only if its contents look like ours.
        legacy_settings = os.path.join(_HELPFILES, "settings.json")
        if os.path.isfile(legacy_settings):
            try:
                with open(legacy_settings, encoding="utf-8") as f:
                    data = json.load(f)
                if isinstance(data, dict) and any(k in data
                                                  for k in _FM_SETTINGS_KEYS):
                    shutil.move(legacy_settings, _SETTINGS_F)
                    moved += 1
            except Exception as e:
                log.warning("settings.json migrate skipped: %s", e)

        # 2) Our known stores out of the (possibly shared) Accounts/ folder,
        #    by exact name, so anything that is not ours is left untouched.
        legacy_acc = os.path.join(_HELPFILES, "Accounts")
        if os.path.isdir(legacy_acc):
            os.makedirs(_ACCOUNTS_DIR, exist_ok=True)
            for name in _FM_ACCOUNT_STORES:
                src = os.path.join(legacy_acc, name)
                dst = os.path.join(_ACCOUNTS_DIR, name)
                if os.path.isfile(src) and not os.path.exists(dst):
                    try:
                        shutil.move(src, dst)
                        moved += 1
                    except Exception as e:
                        log.warning("account store %s migrate skipped: %s",
                                    name, e)
            try:                       # remove the old folder only if now empty
                if not os.listdir(legacy_acc):
                    os.rmdir(legacy_acc)
            except Exception:
                pass

        # 3) Working folders — PATTERN-based, never wholesale, because several
        #    of these names are shared with other programs (Helpfiles/Notes is
        #    also Notes.py's). Each predicate matches only Freemail's own files:
        #      Cache/Archive  → per-account subdirs (name has '@')
        #      Drafts         → *.json draft files
        #      Deleted        → Freemail's saved *.eml / *.json copies
        #      Notes          → *.eml notes (leaves Notes.py's .txt/.json)
        #      Backups        → Freemail_backup_*.zip
        H, F = _HELPFILES, _FM_DIR
        has_at = lambda n: "@" in n
        moved += _mig_move_matching(os.path.join(H, "Cache"),
                                    os.path.join(F, "Cache"), has_at)
        moved += _mig_move_matching(os.path.join(H, "Archive"),
                                    os.path.join(F, "Archive"), has_at)
        moved += _mig_move_matching(
            os.path.join(H, "Drafts"), os.path.join(F, "Drafts"),
            lambda n: n.endswith(".json"))
        moved += _mig_move_matching(
            os.path.join(H, "Deleted"), os.path.join(F, "Deleted"),
            lambda n: n.endswith((".eml", ".json")))
        moved += _mig_move_matching(
            os.path.join(H, "Notes"), os.path.join(F, "Notes"),
            lambda n: n.endswith(".eml"))
        moved += _mig_move_matching(
            os.path.join(H, "Outbox"), os.path.join(F, "Outbox"),
            lambda n: True)          # dedicated Freemail attachment-copy folder
        moved += _mig_move_matching(
            os.path.join(H, "Backups"), os.path.join(F, "Backups"),
            lambda n: n.startswith("Freemail_backup_") and n.endswith(".zip"))

        if moved:
            log.info("Migrated %d Freemail item(s) into %s", moved, _FM_DIR)
    except Exception as e:
        log.warning("Freemail data migration failed (continuing): %s", e)


# ── 6. Windows default mail client (mailto:) ──────────────────────────────────
#
# Windows 11 does NOT let a program make itself the default — it can only
# REGISTER itself as a candidate; the user then picks it in Settings. That is
# exactly what these two functions do, and every key is written under
# HKEY_CURRENT_USER, so nothing outside this Windows user is touched and
# "Unregister" fully removes it again.

_MAILTO_PROGID = "Freemail.Url.Mailto"
_MAILTO_APPKEY = r"Software\Clients\Mail\Freemail"


def _launch_command() -> str:
    """The command Windows should run for a mailto: link — the frozen EXE if
    this is one, otherwise pythonw.exe + this script."""
    if getattr(sys, "frozen", False):
        return f'"{sys.executable}" "%1"'
    exe = sys.executable or "python.exe"
    pyw = exe.replace("python.exe", "pythonw.exe")
    if not os.path.isfile(pyw):
        pyw = exe
    return f'"{pyw}" "{os.path.abspath(__file__)}" "%1"'


def _register_mail_client() -> str:
    """Register as a mailto: handler for the current user. Returns a message."""
    if platform.system() != "Windows":
        raise OSError("This is a Windows-only feature.")
    import winreg
    cmd = _launch_command()
    ico = _icon_path()

    def _set(root, path, value, name=None):
        with winreg.CreateKey(root, path) as k:
            winreg.SetValueEx(k, name, 0, winreg.REG_SZ, value)

    HK = winreg.HKEY_CURRENT_USER
    # (a) The ProgID that actually knows how to open a mailto: URL.
    _set(HK, rf"Software\Classes\{_MAILTO_PROGID}", "URL:MailTo Protocol")
    with winreg.CreateKey(HK, rf"Software\Classes\{_MAILTO_PROGID}") as k:
        winreg.SetValueEx(k, "URL Protocol", 0, winreg.REG_SZ, "")
    if os.path.isfile(ico):
        _set(HK, rf"Software\Classes\{_MAILTO_PROGID}\DefaultIcon", f"{ico},0")
    _set(HK, rf"Software\Classes\{_MAILTO_PROGID}\shell\open\command", cmd)

    # (b) The "this is a mail client" registration Windows' Default apps
    #     page reads to list us at all.
    _set(HK, _MAILTO_APPKEY, "F(re)email")
    _set(HK, rf"{_MAILTO_APPKEY}\shell\open\command", cmd)
    _set(HK, rf"{_MAILTO_APPKEY}\Capabilities", "F(re)email", "ApplicationName")
    _set(HK, rf"{_MAILTO_APPKEY}\Capabilities",
         "A clean Gmail frontend by Lars \"Issu\" Olsson", "ApplicationDescription")
    _set(HK, rf"{_MAILTO_APPKEY}\Capabilities\URLAssociations",
         _MAILTO_PROGID, "mailto")
    _set(HK, r"Software\RegisteredApplications",
         _MAILTO_APPKEY, "F(re)email")
    log.info("Registered as mailto handler: %s", cmd)
    return ("F(re)email is now registered as a mail client.\n\n"
            "Windows does not allow a program to make itself the default, "
            "so the final step is yours: in the Default apps page that opens "
            "next, search for F(re)email and set it for mailto links.")


def _unregister_mail_client() -> str:
    if platform.system() != "Windows":
        raise OSError("This is a Windows-only feature.")
    import winreg
    HK = winreg.HKEY_CURRENT_USER

    def _nuke(path):
        """Delete a key and everything under it, ignoring what is not there."""
        try:
            with winreg.OpenKey(HK, path) as k:
                while True:
                    try:
                        sub = winreg.EnumKey(k, 0)
                    except OSError:
                        break
                    _nuke(path + "\\" + sub)
            winreg.DeleteKey(HK, path)
        except FileNotFoundError:
            pass
        except OSError as e:
            log.warning("Could not delete %s: %s", path, e)

    _nuke(rf"Software\Classes\{_MAILTO_PROGID}")
    _nuke(_MAILTO_APPKEY)
    try:
        with winreg.OpenKey(HK, r"Software\RegisteredApplications", 0,
                            winreg.KEY_SET_VALUE) as k:
            winreg.DeleteValue(k, "F(re)email")
    except FileNotFoundError:
        pass
    except OSError as e:
        log.warning("Could not clear RegisteredApplications: %s", e)
    log.info("Unregistered mailto handler")
    return "F(re)email is no longer registered as a mail client."


def _parse_mailto(url: str) -> dict:
    """Turn a mailto: URL into {to, cc, subject, body}."""
    out = {"to": "", "cc": "", "subject": "", "body": ""}
    if not url or not url.lower().startswith("mailto:"):
        return out
    rest = url[7:]
    addr, _, query = rest.partition("?")
    out["to"] = _urlparse.unquote(addr).strip()
    for key, vals in _urlparse.parse_qs(query, keep_blank_values=True).items():
        k = key.lower()
        if k in ("cc", "subject", "body"):
            out[k] = _urlparse.unquote_plus(vals[0])
        elif k == "to" and not out["to"]:
            out["to"] = _urlparse.unquote_plus(vals[0])
    return out


# ── 7. Mail-filter engine ─────────────────────────────────────────────────────

# The fields a condition row can test (Thunderbird-style multi-row conditions,
# DEL 04z). Each uses the same operators as _op_match.
_FILTER_FIELDS = ["from", "to", "subject", "body", "folder"]
_FILTER_FIELD_LABELS = {"from": "From", "to": "Account", "subject": "Subject",
                        "body": "Body", "folder": "Folder"}

# ── Condition SECTIONS (Issu 2026-08-03, second pass) ─────────────────────────
#
# A rule used to have ONE mode for ALL of its conditions: everything ANDed, or
# everything ORed. That cannot say the thing Issu actually needed:
#
#     From MUST be dhl.se   AND   the subject is EITHER "Ditt kvitto"
#                                 OR "Inlämningskvitto"
#
# — and without it he was forced into one near-identical rule per subject line
# ("massvis av noreply@dhl.com"). So every condition now belongs to a SECTION:
#
#   group "all"  — MUST match. Every row here has to be true.        (AND)
#   group "any"  — …and at least ONE row here has to be true.        (OR)
#
# and the rule matches when BOTH hold. An empty section simply drops out, so a
# rule with only "all" rows behaves exactly like the old match-all, and one
# with only "any" rows exactly like the old match-any. That is what makes the
# migration a no-op for every rule already saved.
#
# match_mode "every" is unchanged and still means "every message, ignore the
# conditions". The little 1/2/3 box no longer switches a rule's mode — it is a
# saved DEFAULT that decides which section a suggested condition lands in.
_COND_GROUPS = ("all", "any")
_FILTER_MODE_BY_NUM = {"1": "all", "2": "any", "3": "every"}
_FILTER_NUM_BY_MODE = {v: k for k, v in _FILTER_MODE_BY_NUM.items()}
_SECTION_TITLE = {
    "all":   "1 · MUST match all of these",
    "any":   "2 · …AND at least ONE of these   (either / or)",
    "every": "3 · All messages",
}
_FILTER_MODE_WORDS = {"all": "all of the following",
                      "any": "any of the following",
                      "every": "all messages"}


def _split_conditions(flt: dict):
    """Split a rule's conditions into (MUST-match-all, at-least-ONE).

    Each item is (original index, condition). Rows with no text are dropped —
    an empty row is a row you have not filled in yet, not a condition that
    matches nothing.

    A condition with no "group" is read through the rule's OLD match_mode, so
    a filter saved before sections existed keeps its exact meaning whether or
    not it has been migrated on disk."""
    conds = flt.get("conditions")
    if conds is None:
        conds = _legacy_conditions(flt)
    legacy = "any" if flt.get("match_mode", "all") == "any" else "all"
    must, either = [], []
    for i, c in enumerate(conds or []):
        if not (c.get("value", "") or "").strip():
            continue
        (either if (c.get("group") or legacy) == "any" else must).append((i, c))
    return must, either


# ── PAIRS inside the either/or section (Issu 2026-09-07) ─────────────────────
#
# Sections gave him "From is dhl.se AND (subject A OR subject B)". What they
# still could not say is the shape his order-tracking mail actually has:
#
#       (Subject "Beställningsuppdatering"  AND  From vinted)
#    OR (Subject "är på väg!"               AND  From sellpy)
#
# — two complete alternatives, each of which is itself a PAIR of conditions.
# Sections alone force that into two rules, because the either/or section ORs
# its rows one by one: put all four rows in it and a Sellpy mail whose subject
# merely said "Beställningsuppdatering" fires the rule.
#
# So an either/or row may now carry a PAIR label. Rows sharing a label are ONE
# alternative and have to be true together; a row with no label is its own
# alternative, exactly as before. The rule fires when the MUST section holds
# AND at least one alternative holds WHOLE. Every rule already on disk has no
# labels at all, so for all of them this changes precisely nothing.
_PAIR_LABELS = ("A", "B", "C", "D", "E", "F", "G", "H")
_PAIR_NONE   = "–"        # "no pair — this row stands on its own", in the UI


def _cond_pair(c: dict) -> str:
    """One condition's pair label, cleaned. "" means: a row on its own."""
    p = (c.get("pair") or "").strip()
    if p in ("", _PAIR_NONE, "-"):
        return ""
    return p[:2].upper()


def _split_alternatives(either: list) -> list:
    """The either/or rows as ALTERNATIVES: [[(index, cond), …], …].

    One alternative is one complete way for the rule to be satisfied, and its
    rows are ANDed together. An unpaired row is an alternative of one — which
    IS the old behaviour, so a rule saved before pairs existed comes out of
    here as one alternative per row and means what it always meant.

    Order is the order of the rows, and the first row carrying a label decides
    where that pair sits in the list."""
    alts, by_pair = [], {}
    for i, c in either:
        p = _cond_pair(c)
        if not p:
            alts.append([(i, c)])
        elif p in by_pair:
            by_pair[p].append((i, c))
        else:
            by_pair[p] = [(i, c)]
            alts.append(by_pair[p])
    return alts


def _filter_describe(flt: dict) -> str:
    """The rule's logic as one plain-English sentence.

    Shown live in the editor and in the diagnosis, because "From contains
    dhl.com AND (Subject contains A OR Subject contains B)" is the one thing
    that cannot be misread — a two-section form can be."""
    if flt.get("match_mode", "all") == "every":
        return "Matches EVERY message."
    must, either = _split_conditions(flt)

    def _one(c):
        return (f"{_FILTER_FIELD_LABELS.get(c.get('field', 'from'), '?')} "
                f"{_FILTER_OP_LABELS.get(c.get('op', 'contains'), '?')} "
                f"“{c.get('value', '')}”")
    bits = []
    if must:
        bits.append(" AND ".join(_one(c) for _i, c in must))
    if either:
        # A pair is drawn as one parenthesised AND — "(Subject … AND From …)"
        # — so "OR" always separates whole alternatives and never two halves
        # of the same one.
        alts = _split_alternatives(either)
        parts = []
        for alt in alts:
            one = " AND ".join(_one(c) for _i, c in alt)
            parts.append(f"({one})" if len(alt) > 1 else one)
        inner = " OR ".join(parts)
        bits.append(f"({inner})" if len(alts) > 1 else inner)
    if not bits:
        if flt.get("has_attachment"):
            return "Matches any message WITH an attachment."
        return "Matches nothing — no condition has any text in it."
    out = "Matches when: " + " AND ".join(bits)
    if flt.get("has_attachment"):
        out += "  — and only messages WITH an attachment"
    return out

def _cond_hay(field: str, msg: dict) -> str:
    """The text a condition compares against, for one field."""
    if field == "from":
        return (msg.get("from", "") or "") + " " + (msg.get("from_name", "") or "")
    if field == "to":
        return msg.get("account_email", "") or ""
    if field == "subject":
        return msg.get("subject", "") or ""
    if field == "body":
        return msg.get("body", "") or ""
    if field == "folder":
        return msg.get("_folder", "") or ""
    return ""

def _legacy_conditions(flt: dict) -> list:
    """Build a conditions list from a pre-DEL-04z filter's flat match_* fields,
    so old saved filters keep working exactly as before."""
    conds = []
    for field, mkey, okey, default_op in (
            ("from",    "match_from",    "op_from",    "contains"),
            ("subject", "match_subject", "op_subject", "contains"),
            ("body",    "match_body",    "op_body",    "contains"),
            ("to",      "match_to",      None,         "contains"),
            ("folder",  "match_folder",  None,         "is")):
        v = (flt.get(mkey) or "").strip()
        if v:
            conds.append({"field": field,
                          "op": flt.get(okey, default_op) if okey else default_op,
                          "value": v})
    return conds

def _filter_folders(flt: dict) -> list:
    """The run-on-a-chosen-folder scope of a rule as a clean list of folder
    names (case preserved). Empty list = "every folder"."""
    raw = (flt.get("run_folders") or "").strip()
    if not raw:
        return []
    return [p.strip() for p in raw.split(",") if p.strip()]

def _filter_folder_ok(flt: dict, msg: dict) -> bool:
    """True if this rule is allowed to run on this message's folder. A rule
    with no folder scope runs everywhere; otherwise the message's folder must
    be one of the chosen ones (matched case-insensitively)."""
    scope = _filter_folders(flt)
    if not scope:
        return True
    folder = (msg.get("_folder", "") or "").strip().lower()
    return folder in {s.lower() for s in scope}

def _filter_account_ok(flt: dict, msg: dict) -> bool:
    """True if this rule is allowed to run on this message's ACCOUNT.

    Issu 2026-08-15: rules run on every account by default — that IS the
    point of a rule like "file Tradera shipping receipts", since the same
    kind of mail can land on more than one of his accounts. "For this
    account only" (match_account) is the deliberate exception: a rule
    scoped to one account is simply invisible to every other one, the same
    way _filter_folder_ok makes a folder-scoped rule invisible elsewhere.
    Empty match_account (the default) means "every account"."""
    only = (flt.get("match_account") or "").strip()
    if not only:
        return True
    return only == (msg.get("account_email", "") or "")


def _filter_needs_body(flt: dict) -> bool:
    """Does judging this rule require the message BODY (or its attachments)?

    Issu 2026-08-16, the quiet half of "filter verkar inte fungera". A folder
    listing fetches headers only — body and attachments arrive later, when you
    open the message or the prefetch reaches it. A rule testing From or
    Subject is therefore judged on complete information from the first second.
    A rule testing the BODY, or "only messages with an attachment", was judged
    against an empty string and an empty list, decided "no match", and said so
    in the diagnosis as though it had really looked. It had not: it could not
    have. Such a rule could never fire on new mail at all.

    Rules that need the body are now DEFERRED rather than wrongly decided —
    the body is fetched and they are judged on the next pass (see
    _apply_filters's "need_body" and _finish_deferred_rules)."""
    if flt.get("has_attachment"):
        return True
    must, either = _split_conditions(flt)
    return any(c.get("field") == "body" for _i, c in must + either)


def _msg_body_known(msg: dict) -> bool:
    """Has this message's real content been downloaded yet? A header-only stub
    from a folder listing says no (see _fetch_folder_cached)."""
    return bool(msg.get("_body_loaded", True))


def _filter_matches(flt: dict, msg: dict) -> bool:
    """Does one filter rule match one message?

    Two sections, ANDed together (see _split_conditions):
      • every condition in the MUST section has to be true, and
      • at least one ALTERNATIVE in the EITHER section has to be true.
    An alternative is normally one row — but rows sharing a pair label are one
    alternative together and must all be true at once (_split_alternatives).
    An empty section drops out, so a rule with only MUST rows is a plain AND
    and one with only EITHER rows is a plain OR — which is exactly how every
    rule written before sections existed keeps behaving.

    match_mode "every" matches all messages and ignores the conditions. A rule
    with no usable conditions matches nothing unless it is restricted to
    messages-with-attachments; the editor also refuses to save an empty rule.

    The run-on-a-chosen-folder scope (run_folders) and the "for this account
    only" scope (match_account) are both applied first: a rule limited to
    certain folders, or to one account, never fires outside them."""
    if not flt.get("enabled", True):
        return False
    if not _filter_folder_ok(flt, msg):
        return False
    if not _filter_account_ok(flt, msg):
        return False
    if flt.get("match_mode", "all") == "every":
        matched = True
    else:
        must, either = _split_conditions(flt)
        if not must and not either:
            matched = bool(flt.get("has_attachment"))
        else:
            matched = all(
                _op_match(c.get("op", "contains"),
                          _cond_hay(c.get("field", ""), msg),
                          c.get("value", ""))
                for _i, c in must)
            if matched and either:
                matched = any(
                    all(_op_match(c.get("op", "contains"),
                                  _cond_hay(c.get("field", ""), msg),
                                  c.get("value", ""))
                        for _i, c in alt)
                    for alt in _split_alternatives(either))
    if not matched:
        return False
    if flt.get("has_attachment") and not msg.get("attachments"):
        return False
    return True


# ── Rules that could become ONE rule (Issu 2026-08-03) ────────────────────────
#
# "Det behövs kanske något som berättar när det finns regler som skulle kunna
#  MERGEas… men 'match all' och 'match any' kan ju inte mergeas."
#
# Exactly so, and it goes further than that: only "any" rules can be merged at
# all. Two "any" rules with the same actions become one "any" rule holding both
# sets of conditions, and it means precisely what the pair meant. Two "all"
# rules cannot — ANDing their conditions together would demand that BOTH rules'
# conditions hold at once, which is a THIRD, stricter rule that matches less
# than either of them did. "All messages" rules have no conditions to merge.
#
# So a pair is only offered when every one of these is identical:
#   match mode ("any"), every action, every trigger, and the folder scope.

_MERGE_ACTION_KEYS = (
    "action_color", "action_read", "action_unread", "action_hide",
    "action_star", "action_snooze_min", "action_notify", "action_move",
    "action_move_account", "action_tag", "action_spam", "action_spam_domain",
    "action_trash", "action_seen_server", "action_flag_server",
    "action_rescue_trash", "action_unsub",
    "has_attachment",
)
_MERGE_TRIGGER_KEYS = ("run_on_fetch", "run_on_archive", "run_on_sent")


def _merge_signature(flt: dict) -> tuple:
    """Everything two rules must agree on before merging them is honest."""
    acts = tuple((k, flt.get(k, "") if not isinstance(flt.get(k), bool)
                  else bool(flt.get(k))) for k in _MERGE_ACTION_KEYS)
    trig = tuple(bool(flt.get(k, k == "run_on_fetch"))
                 for k in _MERGE_TRIGGER_KEYS)
    scope = tuple(sorted(s.lower() for s in _filter_folders(flt)))
    return (acts, trig, scope)


def _cond_signature(flt: dict) -> tuple:
    """A rule's conditions as a comparable, order-independent key.

    The SECTION is part of it: "From is X" as a MUST row and the same row in
    the either/or section are different rules, and folding one into the other
    would change what the rule means. So is the PAIR label: two rows paired
    together are one alternative, the same two rows unpaired are two — a
    different rule again."""
    must, either = _split_conditions(flt)
    return tuple(sorted(
        (g, _cond_pair(c), c.get("field", "from"), c.get("op", "contains"),
         (c.get("value", "") or "").strip().lower())
        for g, group in (("all", must), ("any", either))
        for _i, c in group))


def _merge_groups(filters: list) -> list:
    """Groups of two or more rules that could safely become one.

    Returns [{"rules": [flt, …], "why": str, "dupe": bool}, …].

    Two kinds, and the difference matters:
      • DUPLICATES — same match mode, same conditions, same actions. Whatever
        the mode, one of them is pure waste: Issu's log of 2026-08-03 has
        "Rule for hamta@dhl.com" stored twice, and uid 53846 was moved and then
        moved again. Safe to collapse even in "all" mode, because collapsing
        identical conditions changes nothing.
      • MERGEABLE — different conditions, but "any" mode with identical
        actions. Those become one "any" rule holding both lists, which means
        exactly what the pair meant. "All"-mode rules with DIFFERENT conditions
        are never offered: ANDing them makes a third, stricter rule."""
    dupe_buckets, any_buckets = {}, {}
    for flt in filters:
        csig = _cond_signature(flt)
        if not csig and flt.get("match_mode", "all") != "every":
            continue                        # nothing to contribute
        dupe_buckets.setdefault(
            (flt.get("match_mode", "all"), csig, _merge_signature(flt)),
            []).append(flt)
        # Only a pure either/or rule — nothing in the MUST section — can be
        # folded into another. Merging two rules that each have their own MUST
        # rows would AND unrelated requirements together.
        #
        # EXCEPTION (Issu 2026-08-06): a rule with exactly ONE real condition
        # total is "all of [x]" and "any of [x]" at the same time — ANDing or
        # ORing a single thing is the same thing. Issu's mailbox has six
        # separate single-sender "→ Trash" rules (support@estore.nu,
        # pm3@growatt-service.com, hemkop@medlem.hemkop.se, …) that were never
        # offered here because each was saved with its one condition in the
        # MUST section — they are exactly what this feature is for.
        must, either = _split_conditions(flt)
        if (either and not must) or (len(must) + len(either) == 1):
            any_buckets.setdefault(_merge_signature(flt), []).append(flt)

    out, claimed = [], set()
    for _sig, rules in dupe_buckets.items():
        if len(rules) < 2:
            continue
        claimed.update(id(r) for r in rules)
        out.append({"rules": rules, "dupe": True,
                    "why": f"IDENTICAL rules — same conditions, same actions, "
                           f"same match mode ({rules[0].get('match_mode','all')}). "
                           f"Every matching message is acted on "
                           f"{len(rules)} times."})
    for _sig, rules in any_buckets.items():
        rest = [r for r in rules if id(r) not in claimed]
        if len(rest) < 2:
            continue
        does = _filter_action_summary(rest[0]) or "nothing (no action set)"
        out.append({"rules": rest, "dupe": False,
                    "why": f"all either/or rules with nothing in their MUST "
                           f"section, same triggers, same folder scope, and "
                           f"all of them do: {does}"})
    # Duplicates first — those are strictly waste, so they are the easy win.
    out.sort(key=lambda g: (not g["dupe"], -len(g["rules"])))
    return out


def _merge_shared_senders(filters: list) -> list:
    """Rules that mention the SAME sender text, whatever else differs.

    Not a merge offer — a warning. Two rules matching the same sender fire in
    list order and can quietly fight each other (one moves it, the next tries
    to move what is no longer there). Returns [(sender, [names…]), …]."""
    seen = {}
    for flt in filters:
        conds = flt.get("conditions")
        if conds is None:
            conds = _legacy_conditions(flt)
        for c in conds:
            if c.get("field") != "from":
                continue
            v = (c.get("value", "") or "").strip().lower()
            if not v:
                continue
            seen.setdefault(v, []).append(flt.get("name") or "(unnamed)")
    return sorted(((v, names) for v, names in seen.items() if len(names) > 1),
                  key=lambda t: -len(t[1]))


def _rule_overlap_warnings(cand: dict, others: list) -> list:
    """Other ENABLED rules that look like the same rule as `cand`, checked
    right before a save (Issu 2026-08-06: two separate rules — "Frakt
    Tradera" and "shipping.noreply@tradera.com" — matched the exact same
    mail because one rule's subject text was a substring of the other's, and
    every Tradera receipt got cross-account-copied twice as a result). This
    is a warning, not a hard block — a person may genuinely want two rules
    to touch the same sender — so the caller always asks before saving
    rather than refusing outright. Returns short, human-readable reasons."""
    # A "from" value bound inside a PAIR (Issu 2026-09-24: e.g. rule
    # "Shit half" pairs no-reply@vinted.se WITH the subject "Bekräftelse
    # krävs") does NOT make its rule fire on that sender alone -- it needs the
    # paired condition too. So a paired sender is not a standalone match and
    # must not count as an overlap here, or a broad per-sender rule looks like
    # a duplicate of a narrow paired one it does not actually duplicate.
    # Unpaired senders (every rule without pairs) are unaffected.
    cand_from = {(c.get("value", "") or "").strip().lower()
                 for c in (cand.get("conditions") or [])
                 if c.get("field") == "from" and (c.get("value", "") or "").strip()
                 and not _cond_pair(c)}
    cand_actions = _filter_action_summary(cand)
    cand_csig = _cond_signature(cand)
    cand_msig = _merge_signature(cand)
    out = []
    for other in others:
        if other.get("id") == cand.get("id") or not other.get("enabled", True):
            continue
        oname = other.get("name") or "(unnamed)"
        if _cond_signature(other) == cand_csig and _merge_signature(other) == cand_msig:
            out.append(f"“{oname}” is IDENTICAL to this rule — same "
                       f"conditions, same actions. Saving both is pure "
                       f"duplication: every matching message gets actioned "
                       f"twice.")
            continue
        other_from = {(c.get("value", "") or "").strip().lower()
                      for c in (other.get("conditions") or [])
                      if c.get("field") == "from" and (c.get("value", "") or "").strip()
                      and not _cond_pair(c)}      # paired sender is not a standalone match
        # Not just an exact address match — a substring either way, so
        # "Frakthandlingar och kvitto" vs "📦 Frakthandlingar och kvitto"
        # (this program's own real bug) is caught, not only byte-identical
        # values.
        shared = {v for v in cand_from
                  if any(v in ov or ov in v for ov in other_from if ov)}
        if shared and cand_actions and cand_actions == _filter_action_summary(other):
            out.append(f"“{oname}” already matches "
                       f"{', '.join(sorted(shared))} and does the same "
                       f"thing ({cand_actions}) — matching mail would be "
                       f"actioned by BOTH rules, every time.")
    return out


def _merge_rules(rules: list) -> dict:
    """Fold a group of mergeable rules into one. The FIRST rule is the
    survivor: it keeps its id, name, position and every action; the others
    contribute their conditions, deduplicated on (section, field, op, value)."""
    keeper = dict(rules[0])
    conds, seen = [], set()
    # Pair labels are per-RULE: two rules folded together can both call their
    # pair "A" and mean two entirely different things. Merging them under one
    # label would AND four unrelated rows into one alternative — so every
    # incoming pair is given a fresh label here.
    pairmap, nextp = {}, iter(_PAIR_LABELS)

    def _relabel(ri, c):
        p = _cond_pair(c)
        if not p:
            return ""
        key = (ri, p)
        if key not in pairmap:
            pairmap[key] = next(nextp, "")     # out of letters: unpair it
        return pairmap[key]

    for ri, flt in enumerate(rules):
        must, either = _split_conditions(flt)
        # A rule folded in here because it had exactly ONE condition (see
        # _merge_groups) has that lone row sitting in `must` — but the merged
        # rule needs it in the "any" section (OR'd with every other rule's
        # condition), not "all" (AND'd, which would make the result match
        # nothing at all once there is more than one such row).
        if len(must) + len(either) == 1 and must and not either:
            must, either = [], must
        for group, rows in (("all", must), ("any", either)):
            for _i, c in rows:
                v = (c.get("value", "") or "").strip()
                pair = _relabel(ri, c) if group == "any" else ""
                token = (group, pair, c.get("field", "from"),
                         c.get("op", "contains"), v.lower())
                if token in seen:
                    continue
                seen.add(token)
                row = {"field": c.get("field", "from"),
                       "op": c.get("op", "contains"),
                       "value": v, "group": group}
                if pair:
                    row["pair"] = pair
                conds.append(row)
    keeper["conditions"] = conds
    keeper["match_mode"] = "groups"
    return keeper


# ── Filter DIAGNOSTICS (Issu 2026-08-03) ──────────────────────────────────────
#
# "Lägg in logg som loggar vad som sker vid Filter-körning; vilka filter som
# finns/körs… vilka filter som matchar e-mail helt… vilka som matchar delvis,
# men inte tillräckligt för att köras."
#
# A rule that does nothing gives you no evidence at all: it neither moves the
# mail nor says why. These three functions produce that evidence — every
# condition of every rule against every message, with the text it actually
# compared, so a NEAR miss ("all of: From matched, Subject did not") is as
# visible as a hit. Nothing here changes a message; it only explains.

# A rule that matched at least this share of its conditions is worth showing
# as a NEAR MISS rather than a plain "no".
_DIAG_PARTIAL_MIN = 1        # at least one condition matched


def _cond_explain(c: dict, msg: dict, group: str = "all") -> dict:
    """One condition row, evaluated with the text it looked at kept."""
    field = c.get("field", "from")
    op    = c.get("op", "contains")
    value = (c.get("value", "") or "")
    hay   = _cond_hay(field, msg)
    try:
        ok = _op_match(op, hay, value)
    except Exception as e:                    # a broken saved rule
        log.warning("filter condition crashed (%s %s %r): %s",
                    field, op, value, e)
        ok = False
    return {"field": field, "op": op, "value": value, "group": group,
            "pair": _cond_pair(c), "hay": hay, "ok": bool(ok)}


def _filter_explain(flt: dict, msg: dict, trigger: str = "manual") -> dict:
    """Why one rule did — or did not — fire on one message.

    Deliberately re-implements the decision instead of calling
    _filter_matches: the whole value is in WHICH part said no. The verdict is
    asserted against _filter_matches by the caller in debug builds, so the two
    can never drift apart silently."""
    exp = {
        "id":      flt.get("id", ""),
        "name":    flt.get("name") or (flt.get("id", "") or "")[:6] or "(unnamed)",
        "mode":    flt.get("match_mode", "all"),
        "ran":     True,
        "why":     "",          # why it did not even get to the conditions
        "conds":   [],
        "ok":      0,
        "total":   0,
        "matched": False,
        "partial": False,
        "logic":   "",          # the rule as one plain-English sentence
        "actions": "",          # what it WOULD do
    }
    if not flt.get("enabled", True):
        exp["ran"] = False
        exp["why"] = "the rule is switched off"
        return exp
    if not _filter_runs_on(flt, trigger):
        when = []
        if flt.get("run_on_fetch", True):
            when.append("new-mail checks")
        if flt.get("run_on_archive"):
            when.append("archiving")
        if flt.get("run_on_sent"):
            when.append("after sending")
        exp["ran"] = False
        exp["why"] = (f"it does not run on “{trigger}” "
                      f"(it runs on: {', '.join(when) or 'manual runs only'})")
        return exp
    scope = _filter_folders(flt)
    if scope and not _filter_folder_ok(flt, msg):
        exp["ran"] = False
        exp["why"] = (f"the rule is limited to {', '.join(scope)} and this "
                      f"message is in “{msg.get('_folder', '?')}”")
        return exp
    only = (flt.get("match_account") or "").strip()
    if only and not _filter_account_ok(flt, msg):
        exp["ran"] = False
        exp["why"] = (f"the rule is set to “for this account only: {only}” "
                      f"and this message arrived on "
                      f"{msg.get('account_email', '?')}")
        return exp
    # Deferred, not decided: the rule reads the BODY and the body has not been
    # downloaded yet. Saying "no match" here would be a lie the diagnosis has
    # been telling since header-only listing was introduced (Issu 2026-08-16).
    if _filter_needs_body(flt) and not _msg_body_known(msg):
        exp["ran"] = False
        exp["why"] = ("this rule reads the message BODY (or wants an "
                      "attachment), and only the headers of this message have "
                      "been downloaded so far — it is being fetched now and "
                      "the rule is judged on the next pass, not guessed at")
        return exp

    must, either = _split_conditions(flt)
    exp["conds"] = ([_cond_explain(c, msg, "all") for _i, c in must]
                    + [_cond_explain(c, msg, "any") for _i, c in either])
    exp["ok"]    = sum(1 for c in exp["conds"] if c["ok"])
    exp["total"] = len(exp["conds"])
    exp["logic"] = _filter_describe(flt)
    n_must_ok  = sum(1 for _i, c in must
                     if _op_match(c.get("op", "contains"),
                                  _cond_hay(c.get("field", ""), msg),
                                  c.get("value", "")))
    alts = _split_alternatives(either)
    # An ALTERNATIVE counts as satisfied only when every row of it is — a pair
    # that is half-true is not "one of the either/or rows matched", and saying
    # so was the whole confusion pairs exist to remove.
    n_either_ok = sum(
        1 for alt in alts
        if all(_op_match(c.get("op", "contains"),
                         _cond_hay(c.get("field", ""), msg),
                         c.get("value", ""))
               for _i, c in alt))

    if exp["mode"] == "every":
        matched = True
    elif not must and not either:
        matched = bool(flt.get("has_attachment"))
        if not matched:
            exp["why"] = "the rule has no conditions with any text in them"
    else:
        must_ok   = (n_must_ok == len(must))
        either_ok = (not either) or n_either_ok > 0
        matched = must_ok and either_ok
        if not matched:
            # Say WHICH section stopped it — with two sections, "it didn't
            # match" is not an answer.
            parts = []
            if not must_ok:
                missing = [c for c in exp["conds"]
                           if c["group"] == "all" and not c["ok"]]
                parts.append(
                    "the MUST section needs every row, and " +
                    ", ".join(f"“{_FILTER_FIELD_LABELS.get(c['field'], c['field'])} "
                              f"{_FILTER_OP_LABELS.get(c['op'], c['op'])} "
                              f"{c['value']}” did not match"
                              for c in missing[:3]))
            if either and not n_either_ok:
                paired = sum(1 for a in alts if len(a) > 1)
                parts.append(
                    f"none of the {len(alts)} either/or alternative(s) "
                    f"matched in full"
                    + (f" ({paired} of them a pair, where BOTH rows have to "
                       f"be true)" if paired else ""))
            exp["why"] = "; ".join(parts)

    if matched and flt.get("has_attachment") and not msg.get("attachments"):
        matched = False
        exp["why"] = ("every condition matched, but the rule wants messages "
                      "WITH an attachment and this one has none")
    # Matched, but still counting down. Kept as a MATCH with a "waiting" note
    # rather than reported as a non-match: "no condition matched" would be a
    # lie, and this is precisely the question ("why hasn't it moved yet?") the
    # diagnosis exists to answer.
    if matched:
        due, left, acts_at = _filter_delay_state(flt, msg)
        if not due:
            exp["waiting"] = True
            exp["why"] = (f"it waits {_human_minutes(flt.get('delay_min'))} "
                          f"after the mail arrives — {_human_minutes(left)} "
                          f"still to go"
                          + (f", so it acts at {acts_at:%Y-%m-%d %H:%M}"
                             if acts_at else ""))
    exp["matched"] = matched
    # A near miss: something matched but not enough. This is the line that
    # answers "why isn't my rule firing?".
    exp["partial"] = (not matched and exp["ok"] >= _DIAG_PARTIAL_MIN
                      and exp["total"] > exp["ok"])
    if not matched and not exp["why"]:
        exp["why"] = "no condition matched"
    exp["actions"] = _filter_action_summary(flt)
    return exp


def _filter_action_summary(flt: dict) -> str:
    """What a rule would DO, in plain words. "" means: nothing at all — which
    is itself the answer to "my rule matches but the mail does not move"."""
    bits = []
    wait = int(flt.get("delay_min") or 0)
    if wait > 0:
        # First, because it changes WHEN everything after it happens.
        bits.append(f"after {_human_minutes(wait)}"
                    + (" (keeps it unread)"
                       if flt.get("delay_keep_unread", True) else ""))
    if (flt.get("action_move") or "").strip():
        acct = (flt.get("action_move_account") or "").strip()
        bits.append(f"move → {acct + '/' if acct else ''}{flt['action_move'].strip()}")
    if flt.get("action_trash"):
        bits.append("→ Trash")
    if flt.get("action_spam"):
        bits.append("mark spam")
    if flt.get("action_hide"):
        bits.append("hide")
    if flt.get("action_read") or flt.get("action_seen_server"):
        bits.append("mark read")
    if flt.get("action_unread"):
        bits.append("mark unread")
    if flt.get("action_star") or flt.get("action_flag_server"):
        bits.append("star")
    if (flt.get("action_color") or "").strip():
        bits.append("colour")
    if (flt.get("action_tag") or "").strip():
        bits.append("tag")
    if int(flt.get("action_snooze_min") or 0) > 0:
        bits.append(f"snooze {flt['action_snooze_min']}m")
    if flt.get("action_notify") in ("always", "never"):
        bits.append(f"notify {flt['action_notify']}")
    if flt.get("action_rescue_trash"):
        bits.append("rescue from Trash")
    if (flt.get("action_unsub") or "") == "offer":
        bits.append("offer to unsubscribe")
    elif (flt.get("action_unsub") or "") == "auto":
        bits.append("UNSUBSCRIBE automatically")
    return ", ".join(bits)


def _diag_render(diag: dict, verbose: bool = True) -> list:
    """Turn one diagnostics record into printable lines (shared by the log and
    the on-screen window, so they can never say different things)."""
    out = []
    out.append(f"=== Filter run: trigger “{diag.get('trigger', '?')}” · "
               f"{diag.get('when', '')} · {diag.get('n_messages', 0)} message(s) "
               f"· {diag.get('n_rules', 0)} rule(s)")
    if diag.get("server_note"):
        out.append(f"    ⚠ {diag['server_note']}")
    out.append("--- Rules in this run " + "-" * 46)
    for r in diag.get("rules", []):
        state = ("ran" if r["ran"] else "DID NOT RUN")
        line = (f"  [{state}] {r['name']}"
                f" · {r['n_cond']} condition(s)"
                f" · matched {r['hits']}"
                f" · near miss {r['near']}")
        out.append(line)
        if r.get("logic"):
            out.append(f"        {r['logic']}")
        if not r["ran"] and r.get("why"):
            out.append(f"        reason: {r['why']}")
        if not r.get("actions"):
            out.append("        ⚠ this rule DOES NOTHING — no action is set "
                       "(fill in “Move to folder:” to move mail)")
        else:
            out.append(f"        does: {r['actions']}")
        if r.get("needs_server") and not diag.get("server_on"):
            out.append("        ⚠ needs “Server changes” ON, and it is OFF — "
                       "so this rule's move/trash did nothing at all")
    if not verbose:
        return out
    out.append("--- Message by message " + "-" * 45)
    for m in diag.get("messages", []):
        head = (f"  {m['folder']:<10} {m['sender'][:34]:<35} "
                f"{m['subject'][:52]}")
        out.append(head)
        for r in m["rules"]:
            if r["matched"]:
                out.append(f"        ✔ FULL MATCH  “{r['name']}”"
                           f"  ({r['ok']}/{r['total']} conditions)"
                           + (f"  → {r['actions']}" if r["actions"]
                              else "  → nothing (no action set)"))
                if r.get("waiting"):
                    out.append(f"            ⏳ WAITING — {r['why']}")
            elif r["partial"]:
                out.append(f"        ~ near miss   “{r['name']}”"
                           f"  ({r['ok']}/{r['total']} conditions) — {r['why']}")
                if r.get("logic"):
                    out.append(f"            rule: {r['logic']}")
                for c in r["conds"]:
                    mark = "✔" if c["ok"] else "✖"
                    where = ("MUST" if c.get("group", "all") == "all"
                             else "either" + (f" {c['pair']}"
                                              if c.get("pair") else ""))
                    out.append(f"            {mark} [{where}] "
                               f"{_FILTER_FIELD_LABELS.get(c['field'], c['field'])} "
                               f"{_FILTER_OP_LABELS.get(c['op'], c['op'])} "
                               f"“{c['value']}”   ·  saw: "
                               f"“{(c['hay'] or '')[:70]}”")
            elif not r["ran"]:
                out.append(f"        – skipped     “{r['name']}” — {r['why']}")
            else:
                out.append(f"        ✖ no match    “{r['name']}” — {r['why']}")
        if not m["rules"]:
            out.append("        (no rules at all)")
    return out


# The units the rule editor offers for "wait before acting", and how many
# minutes each is worth. Kept next to the engine that reads the result so the
# two can never drift.
_DELAY_UNITS  = ("minutes", "hours", "days")
_DELAY_FACTOR = {"minutes": 1, "hours": 60, "days": 1440}


def _delay_to_minutes(amount, unit) -> int:
    """Editor (number, unit) → stored minutes. Never negative."""
    try:
        n = float(str(amount).replace(",", ".").strip() or "0")
    except ValueError:
        n = 0.0
    return max(0, int(round(n * _DELAY_FACTOR.get(unit, 1))))


def _delay_from_minutes(mins) -> tuple:
    """Stored minutes → (number, unit) for the editor, picking the largest unit
    that divides exactly — 1560 comes back as (26, "hours"), the way it was
    typed, not as 1560 minutes."""
    m = int(mins or 0)
    if m <= 0:
        return 0, "hours"
    for unit in ("days", "hours"):
        f = _DELAY_FACTOR[unit]
        if m % f == 0:
            return m // f, unit
    return m, "minutes"


def _human_minutes(mins) -> str:
    """A number of minutes as something a person reads: "26 h", "3 h 12 min",
    "2 days". Used in the rule summary, the log and the diagnosis, so all three
    say the wait the same way."""
    try:
        m = int(round(float(mins)))
    except Exception:
        return "0 min"
    if m < 60:
        return f"{m} min"
    h, rest = divmod(m, 60)
    if h < 48:
        return f"{h} h" + (f" {rest} min" if rest else "")
    d, hh = divmod(h, 24)
    return f"{d} days" + (f" {hh} h" if hh else "")


def _msg_age_minutes(msg: dict):
    """How long ago this message arrived, in minutes, or None when its date
    cannot be read. Uses _parse_msg_dt — a message's date is timezone-aware and
    everything this program generates is naive, and mixing the two raises."""
    dt = _parse_msg_dt(msg.get("_dt", "") or "")
    if not dt:
        return None
    return (datetime.now() - dt).total_seconds() / 60.0


def _filter_delay_state(flt: dict, msg: dict) -> tuple:
    """Is a waiting rule due yet? Returns (due, minutes_left, acts_at).

    Pure, and the ONE place the delay is decided, so the engine, the rule
    summary and the "why didn't my rule fire?" diagnosis can never disagree
    about when a rule is going to act."""
    wait = int(flt.get("delay_min") or 0)
    if wait <= 0:
        return True, 0.0, None
    age = _msg_age_minutes(msg)
    if age is None:
        # No readable Date: header. Acting now beats never acting — and the
        # caller logs it, so it is never silent.
        return True, 0.0, None
    left = wait - age
    dt = _parse_msg_dt(msg.get("_dt", "") or "")
    return (left <= 0), max(0.0, left), (dt + timedelta(minutes=wait)) if dt else None


def _filter_holds_unread(flt: dict) -> bool:
    """Is this a delayed rule that must leave the read state alone?"""
    return (int(flt.get("delay_min") or 0) > 0
            and bool(flt.get("delay_keep_unread", True)))


def _filter_runs_on(flt: dict, trigger: str) -> bool:
    """Whether a rule fires for a given trigger (DEL 04z2).

      • "manual"  — the "Run filters now" button: every enabled rule runs.
      • "fetch"   — a new-mail check: only rules with run_on_fetch.
      • "archive" — archiving a message out of the inbox: run_on_archive rules.
      • "sent"    — a message was just sent: run_on_sent rules.
    """
    if trigger == "manual":
        return True
    if trigger == "archive":
        return bool(flt.get("run_on_archive"))
    if trigger == "sent":
        return bool(flt.get("run_on_sent"))
    return bool(flt.get("run_on_fetch", True))       # "fetch" (the default)

# ── Background rescue pass over the Trash (Issu 2026-10-12) ─────────────────
# A Tradera "Frakthandlingar och kvitto" mail went straight to Gmail's Trash
# (nothing in this program put it there) and the "Frakt" rule, which has
# "rescue from Trash" on, did nothing until he OPENED the Trash: the scheduled
# check, the account sweep and Refresh all fetch the Inbox only, so the rule
# never saw the message. Accounts that have such a rule now also look at their
# Trash on every check: the newest FETCH_LIMIT messages AND everything from the
# last RESCUE_TRASH_HOURS hours, whichever is more. Only the rescue rules run on
# those messages (no toast, nothing drawn, no other rule touched).
RESCUE_TRASH_HOURS = 36
RESCUE_TRASH_MAX_FETCH = 300      # cap when the 36-hour window is wider than 40


def _rescue_rules_for(store: dict, email: str) -> bool:
    """Does any enabled "rescue from Trash" rule apply to this account?"""
    for f in (store or {}).get("filters", []) or []:
        if not (f.get("enabled", True) and f.get("action_rescue_trash")):
            continue
        if not f.get("run_on_fetch", True):
            continue
        only = (f.get("match_account") or "").strip()
        if only and only != (email or ""):
            continue
        return True
    return False


def _rescue_trash_window(msgs: list, keep: int = FETCH_LIMIT,
                         hours: int = RESCUE_TRASH_HOURS) -> list:
    """The `keep` newest messages PLUS every message younger than `hours`.
    Messages with no readable date count as recent (acting beats never
    acting), but never more than `keep` of them."""
    dated, undated = [], []
    for m in msgs or []:
        dt = _parse_msg_dt(m.get("_dt", "") or "")
        (dated if dt else undated).append((dt, m))
    dated.sort(key=lambda p: p[0], reverse=True)
    cutoff = datetime.now() - timedelta(hours=hours)
    out = [m for i, (dt, m) in enumerate(dated) if i < keep or dt >= cutoff]
    out += [m for _dt, m in undated[:keep]]
    return out


def _apply_filters(messages: list, store: dict, tag_store=None,
                   manual: bool = False, allow_server: bool = False,
                   trigger: str = None, diagnose: bool = False,
                   diag_limit: int = 250, rescue_only: bool = False) -> dict:
    """Annotate messages in place with what the filters decided, and report
    what happened. LOCAL actions are applied here; SERVER actions (move / trash
    / mark-read / star on Gmail) are only COLLECTED into stats["server_actions"]
    for the caller to run on a background thread, and only when allow_server.

    `trigger` selects which rules run (see _filter_runs_on): "fetch" (default),
    "manual", "archive" or "sent". The older manual= flag still works and just
    means trigger="manual"; when trigger is given it wins.

    Adds to each message: _filter_color, _filter_hide, _filter_notify,
    _filter_names (which rules matched, for the tooltip/log)."""
    if trigger is None:
        trigger = "manual" if manual else "fetch"
    filters = store.get("filters", [])
    stats   = {"matched": 0, "hidden": 0, "snoozed": [], "events": [],
               "server_actions": [],
               # Unsubscribes a rule asked for (DEL 04e2). COLLECTED only —
               # this function has no business talking to the network, and the
               # log of what has already been unsubscribed lives on the app.
               "unsubs": [],
               # Rules that matched but are still counting down (delay_min) —
               # reported, never acted on. See _filter_delay_state.
               "waiting": [],
               # Messages a rule could not honestly be judged against yet,
               # because it tests the BODY and only the headers have been
               # downloaded. The caller fetches these and runs the rules again
               # — see _filter_needs_body / _finish_deferred_rules.
               "need_body": []}
    # ── Diagnostics scaffolding (see _filter_explain) ─────────────────────────
    diag = None
    if diagnose:
        diag = {
            "when": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "trigger": trigger, "n_messages": len(messages),
            "n_rules": len(filters), "server_on": bool(allow_server),
            "rules": [{"id": f.get("id", ""),
                       "name": f.get("name") or "(unnamed)",
                       "mode": f.get("match_mode", "all"),
                       "logic": _filter_describe(f),
                       "ran": _filter_runs_on(f, trigger) and f.get("enabled", True),
                       "why": "",
                       "n_cond": sum(len(g) for g in _split_conditions(f)),
                       "hits": 0, "near": 0,
                       "actions": _filter_action_summary(f),
                       "needs_server": _filter_has_server_action(f)}
                      for f in filters],
            "messages": [],
        }
        stats["diag"] = diag
    if not filters:
        if diag is not None:
            log.info("FILTER RUN [%s]: there are NO rules at all", trigger)
        return stats
    _need_body_ids = set()      # see the deferral below — identity, not ==
    for msg in messages:
        names = []
        if diag is not None and len(diag["messages"]) < diag_limit:
            m_rec = {"folder": msg.get("_folder", "") or "",
                     "sender": msg.get("from", "") or "",
                     "subject": msg.get("subject", "") or "",
                     "rules": []}
            # Indexed by POSITION, not by id: a hand-edited or legacy rule can
            # be missing an id, and two blank ids would then share a counter.
            for ri, flt in enumerate(filters):
                exp = _filter_explain(flt, msg, trigger)
                m_rec["rules"].append(exp)
                r = diag["rules"][ri]
                if exp["matched"]:
                    r["hits"] += 1
                elif exp["partial"]:
                    r["near"] += 1
                if not exp["ran"] and not r["why"]:
                    r["why"] = exp["why"]
            diag["messages"].append(m_rec)
        for flt in filters:
            if not _filter_runs_on(flt, trigger):
                continue          # this rule does not fire on this trigger
            if rescue_only and not flt.get("action_rescue_trash"):
                continue          # background Trash pass: rescue rules only
            # A rule that reads the BODY cannot be judged on a message whose
            # body has not been downloaded. Defer it — do NOT quietly call it
            # a non-match, which is what used to happen and is why a
            # body-based rule appeared never to work (Issu 2026-08-16).
            if _filter_needs_body(flt) and not _msg_body_known(msg):
                # Identity, not equality: two different messages can compare
                # equal as dicts, and a deep compare per rule per message would
                # be paid on every check for nothing.
                if id(msg) not in _need_body_ids:
                    _need_body_ids.add(id(msg))
                    stats["need_body"].append(msg)
                continue
            if not _filter_matches(flt, msg):
                continue
            # ── Wait before acting (DEL 04z3) ────────────────────────────────
            # The rule matched, but it is a delayed one and this message is not
            # old enough yet. Do nothing at all — no actions, no event, no
            # annotation — and note it so the status line and the diagnosis can
            # say WHEN it will act instead of leaving him wondering whether the
            # rule is broken. The next check re-judges it from scratch.
            due, left, acts_at = _filter_delay_state(flt, msg)
            if not due:
                stats["waiting"].append({
                    "fname":   flt.get("name") or flt.get("id", "")[:6],
                    "subject": msg.get("subject", ""),
                    "left":    left,
                    "at":      acts_at.strftime("%Y-%m-%d %H:%M") if acts_at else "",
                })
                continue
            if int(flt.get("delay_min") or 0) > 0 and acts_at is None:
                log.info("filter '%s': no readable date on “%.60s” — the "
                         "%s wait could not be measured, acting now",
                         flt.get("name", ""), msg.get("subject", ""),
                         _human_minutes(flt.get("delay_min")))
            names.append(flt.get("name") or flt.get("id", "")[:6])
            stats["matched"] += 1
            did = []              # plain-language actions, for the filter log
            # ── Rescue from Trash (Issu 2026-08-06, corrected 2026-08-15) ──
            # A same-account destination is exactly as safe to move out of
            # Trash as any other folder, so that case is not special at all
            # any more — it just falls through to the normal action block
            # below and gets filed in THIS pass, instead of parking in Inbox
            # and hoping the next check finishes the job.
            #
            # A cross-account destination is the one case that needs care:
            # its own "move" already ends by trashing the source as the last
            # step of completing the copy, and if rescue then pulled that
            # same source back out, the next pass would copy it AGAIN — an
            # endless loop, one new duplicate every cycle. So here it is
            # delivered straight to the rule's real destination in one hop
            # (queued as "rescue_copy"), and the Trash original is left
            # untouched: it is already out of the source account's normal
            # view, and _dispatch_filter_server_actions checks the target by
            # Message-ID before appending, so the same message is never
            # copied there twice even if it is still sitting in Trash (and
            # so still matching) on the next check.
            if (flt.get("action_rescue_trash")
                    and (msg.get("_folder") or "") == "Trash"):
                move_to = (flt.get("action_move") or "").strip()
                macct   = (flt.get("action_move_account") or "").strip()
                cross_acct = bool(macct) and macct != msg.get(
                    "account_email", "")
                if not cross_acct:
                    pass    # same account (or no target account at all):
                            # nothing special about Trash — fall through.
                else:
                    if not allow_server:
                        did.append("rescue from Trash — needs Server "
                                   "changes ON (skipped)")
                    elif not move_to:
                        stats["server_actions"].append(
                            {"msg": msg, "fid": flt.get("id", ""),
                             "fname": flt.get("name") or flt.get("id", "")[:6],
                             "kind": "move", "param": "Inbox", "account": ""})
                        did.append("rescued from Trash → Inbox (this rule "
                                   "has no destination folder set)")
                    else:
                        stats["server_actions"].append(
                            {"msg": msg, "fid": flt.get("id", ""),
                             "fname": flt.get("name") or flt.get("id", "")[:6],
                             "kind": "rescue_copy", "param": move_to,
                             "account": macct})
                        did.append(f"rescued straight to {macct}/{move_to} "
                                   "(original stays in Trash — skipped "
                                   "automatically if already delivered "
                                   "there)")
                    stats["events"].append({
                        "fid":     flt.get("id", ""),
                        "fname":   flt.get("name") or flt.get("id", "")[:6],
                        "key":     _msg_key(msg),
                        "subject": msg.get("subject", ""),
                        "sender":  msg.get("from", ""),
                        "folder":  msg.get("_folder", ""),
                        "account": msg.get("account_email", ""),
                        "actions": ", ".join(did) or "matched (no action)",
                    })
                    continue
            # A delayed rule that promises to leave the read state alone
            # (Issu 2026-08-17: "MEN, där så måste alla olästa kvarstå som
            # olästa"). It never makes READ mail unread — it only refuses to
            # read UNREAD mail, here and (via _keep_unread) in the auto-read
            # pass that runs after the move.
            hold_unread = _filter_holds_unread(flt)
            if hold_unread:
                msg["_keep_unread"] = True
            if flt.get("action_color"):
                msg["_filter_color"] = flt["action_color"]
                did.append("colour")
            if flt.get("action_read"):
                if hold_unread:
                    did.append("mark read SKIPPED (this rule keeps mail unread)")
                else:
                    msg["unread"] = False
                    did.append("mark read")
            if flt.get("action_unread"):
                # Mark/keep unread locally (Thunderbird's "Mark as unread").
                # Applied after action_read so an accidental both-ticked rule
                # ends up unread, and flagged _always_unread-style so the count
                # treats it as "kept" rather than genuine new mail.
                msg["unread"] = True
                msg["_manually_unread"] = True
                did.append("mark unread")
            if flt.get("action_star"):
                msg["starred"] = True
                did.append("star")
            if flt.get("action_hide"):
                msg["_filter_hide"] = True
                stats["hidden"] += 1
                did.append("hide")
            note = flt.get("action_notify", "default")
            if note in ("always", "never"):
                msg["_filter_notify"] = note
                did.append(f"notify {note}")
            mins = int(flt.get("action_snooze_min") or 0)
            if mins > 0:
                stats["snoozed"].append((msg, mins))
                did.append(f"snooze {mins}m")
            # Tagging from a rule: the same marks you apply by hand, applied
            # for you. Idempotent — a message already carrying the tag is
            # left alone rather than toggled off on the next fetch.
            tag_id = (flt.get("action_tag") or "").strip()
            if tag_id and tag_store is not None:
                have = {t["id"] for t in _tags_of(tag_store, msg)}
                if tag_id not in have:
                    _tag_toggle(tag_store, msg, tag_id)
                    did.append("tag")
            # Mark as spam (LOCAL): flag it and take it out of the list, the way
            # Gmail moves spam out of the Inbox (Issu). The "whole domain" part
            # of this request is handled at save-time in the editor by widening
            # the sender condition to the bare domain, so the rule then matches
            # everyone at that domain here — no special matcher path needed.
            if flt.get("action_spam"):
                msg["spam"] = True
                msg["_filter_hide"] = True
                stats["hidden"] += 1
                did.append("spam")

            # ── Unsubscribe (DEL 04e2) — collected, never fired from here ────
            # Same discipline as the server actions below: this function
            # decides, the caller acts. It also keeps the one thing that
            # matters out of the hot loop — whether this list has ALREADY been
            # unsubscribed from, which only the app's log knows.
            umode = (flt.get("action_unsub") or "").strip()
            if umode in ("offer", "auto"):
                stats["unsubs"].append(
                    {"msg": msg, "mode": umode,
                     "rule": flt.get("name") or flt.get("id", "")[:6]})
                did.append("unsubscribe: "
                           + ("offered" if umode == "offer" else "automatic"))

            # ── SERVER-side actions (DEL 04y) — collected, not run here ───────
            if _filter_has_server_action(flt):
                if not allow_server:
                    did.append("server actions OFF (skipped)")
                else:
                    fid   = flt.get("id", "")
                    fname = flt.get("name") or fid[:6]
                    def _sa(kind, param="", account=""):
                        stats["server_actions"].append(
                            {"msg": msg, "fid": fid, "fname": fname,
                             "kind": kind, "param": param, "account": account})
                    move_to = (flt.get("action_move") or "").strip()
                    if move_to:
                        macct = (flt.get("action_move_account") or "").strip()
                        # ── Already filed there? Leave it alone ─────────────
                        # A move to where the message already is (or to the
                        # parent of where it now sits) is not a move — it is
                        # mail hopping about for nothing, and it is what pulled
                        # Issu's month-filed receipts straight back out of
                        # their 2026-08 folder a second after they arrived
                        # (2026-08-08). Only applies within the SAME account:
                        # a cross-account rule genuinely does have somewhere
                        # else to put it.
                        same_acct = (not macct
                                     or macct == msg.get("account_email", ""))
                        if same_acct and _already_filed_there(
                                msg.get("_folder", ""), move_to):
                            did.append(f"move skipped — already filed in "
                                       f"{msg.get('_folder','')}")
                        else:
                            _sa("move", move_to, macct)
                            did.append(f"move → {macct + '/' if macct else ''}"
                                       f"{move_to}")
                    if flt.get("action_trash"):
                        # Never auto-trash a message you sent to yourself: on
                        # Gmail it is ONE message wearing Inbox+Sent, so trashing
                        # it by a rule would quietly remove it from both. That is
                        # exactly the surprise the safety rule forbids — manual
                        # delete only for those.
                        if _is_self_message(msg):
                            did.append("trash SKIPPED (self-addressed)")
                        else:
                            _sa("trash"); did.append("→ Trash")
                    if flt.get("action_seen_server"):
                        # Same promise as the local mark-read above: a waiting
                        # rule does not get to read his mail for him, on this
                        # machine or on Gmail.
                        if hold_unread:
                            did.append("read on Gmail SKIPPED (this rule keeps "
                                       "mail unread)")
                        else:
                            _sa("seen"); did.append("read on Gmail")
                    if flt.get("action_flag_server"):
                        _sa("flag"); did.append("star on Gmail")

            stats["events"].append({
                "fid":     flt.get("id", ""),
                "fname":   flt.get("name") or flt.get("id", "")[:6],
                "key":     _msg_key(msg),
                "subject": msg.get("subject", ""),
                "sender":  msg.get("from", ""),
                "folder":  msg.get("_folder", ""),
                "account": msg.get("account_email", ""),
                "actions": ", ".join(did) or "matched (no action)",
            })
        if names:
            msg["_filter_names"] = names
    if diag is not None:
        # The single most common cause of "my rules do not move anything":
        # every server action is silently dropped while Server changes is off.
        if any(r["needs_server"] for r in diag["rules"]) and not allow_server:
            diag["server_note"] = (
                "One or more rules ask to MOVE or TRASH mail on Gmail, but "
                "“Server changes” is OFF — those parts did nothing at all "
                "(a move is not a local action, so the mail neither moved "
                "nor hid). Tools → Server changes.")
        elif not any(r["actions"] for r in diag["rules"]):
            diag["server_note"] = (
                "Not one rule has an ACTION set. A rule decides WHICH mail it "
                "matches; you still have to tell it what to DO — fill in "
                "“Move to folder:” in the rule editor.")
        if len(messages) > diag_limit:
            diag["truncated"] = len(messages) - diag_limit
    return stats


# ── 7b. DUPLICATE MAIL FINDER (Issu 2026-08-06) ───────────────────────────────
#
# "idiotsäker dublettkoll" — a foolproof duplicate check. Grew out of the
# cross-account move bug: a message stuck in Trash gets re-copied to the
# target account on every single poll (see _imap_trash_message's refusal to
# re-delete an already-trashed source), so the same DHL/Tradera receipt piles
# up as several identical-looking messages with NO body (only headers were
# ever fetched for them), which made them impossible to tell apart by eye.
#
# Two passes, in order of certainty:
#   1. Same Message-ID. This is the closest thing to proof that exists: a
#      cross-account move APPENDs the ORIGINAL raw bytes unchanged (see
#      _imap_append_message), so every copy of one message carries the exact
#      same Message-ID header the sending server assigned once. Two different
#      real messages sharing a Message-ID essentially never happens.
#   2. Same sender + same normalised subject, scored down by how far apart
#      they were sent — always shown as a guess with its reasoning, never
#      stated as fact.
#
# Read-only throughout: select(readonly=True) + BODY.PEEK[HEADER.FIELDS…],
# the same guarantee every other scan in this program makes.

def _dup_scan_account(email_addr, password, folders, progress=None,
                      per_folder=2000):
    """Header-only (no body) scan of one account's folders. Returns message
    dicts with _message_id / from / subject / date / _size filled in and
    _body_loaded=False — exactly the shape _ensure_full_body already knows
    how to fill in later, so "Open" and "Compare" can fetch the real content
    on demand instead of downloading every candidate up front."""
    out = []
    imap = _imap_connect(email_addr, password)
    try:
        mapping = _discover_mailboxes(imap)
        for folder in folders:
            mailbox = _resolve_mailbox(imap, folder, mapping)
            try:
                typ, _ = imap.select(_mb_arg(mailbox), readonly=True)
                if typ != "OK":
                    continue
                if progress:
                    progress(f"Scanning {email_addr} · {folder}…")
                typ, data = imap.uid("SEARCH", None, "ALL")
                if typ != "OK" or not data or not data[0]:
                    continue
                uids = data[0].split()
                if len(uids) > per_folder:
                    uids = uids[-per_folder:]     # newest first — where
                                                   # duplicates concentrate
                for i in range(0, len(uids), 300):
                    chunk = uids[i:i + 300]
                    uid_set = ",".join(u.decode() for u in chunk)
                    typ, fetched = imap.uid(
                        "FETCH", uid_set,
                        "(UID RFC822.SIZE BODY.PEEK[HEADER.FIELDS "
                        "(MESSAGE-ID FROM SUBJECT DATE)])")
                    if typ != "OK":
                        continue
                    for item in fetched:
                        if not isinstance(item, tuple):
                            continue
                        meta = item[0] or b""
                        raw  = item[1] or b""
                        meta_s = meta.decode("utf-8", "replace")
                        uidm  = _re.search(r"UID\s+(\d+)", meta_s)
                        sizem = _re.search(r"RFC822\.SIZE\s+(\d+)", meta_s)
                        try:
                            msgobj = _email.message_from_bytes(raw)
                        except Exception as e:
                            log.warning("Duplicate scan: could not parse a "
                                       "header in %s/%s: %s",
                                       email_addr, folder, e)
                            continue
                        built = _build_msg_dict(
                            msgobj, (), None,
                            uidm.group(1) if uidm else None,
                            email_addr, folder, meta_s, body_loaded=False)
                        built["_size"] = int(sizem.group(1)) if sizem else 0
                        out.append(built)
                    if progress:
                        progress(f"Scanning {email_addr} · {folder} "
                                 f"({min(i + 300, len(uids))}/{len(uids)})…")
            except Exception as e:
                log.warning("Duplicate scan failed in %s/%s: %s",
                           email_addr, folder, e)
    finally:
        try:
            imap.logout()
        except Exception:
            pass
    return out


def _dup_normalize_subject(s: str) -> str:
    """Strip Re:/Fwd:/Vidarebefordrat: prefixes and punctuation, so
    "📦 Frakthandlingar och kvitto" and "Frakthandlingar och kvitto" compare
    equal — the exact mismatch that let two rules both match the same
    Tradera mail in this program's own filter engine."""
    s = s or ""
    s = _re.sub(r"^\s*(re|sv|fw|fwd|vidarebefordra[t]?)\s*:\s*", "", s,
               flags=_re.I)
    s = "".join(ch for ch in s if ch.isalnum() or ch.isspace())
    return _re.sub(r"\s+", " ", s).strip().lower()


def _dup_score_group(members: list) -> tuple:
    """(0-100 confidence, one-line reason) that a cluster of messages are all
    copies of the same original."""
    mids = {(m.get("_message_id") or "").strip() for m in members}
    mids.discard("")
    if len(mids) == 1 and len(members) > 1:
        return 99, "identical Message-ID — the same message, copied"
    dts = []
    for m in members:
        try:
            dts.append(datetime.fromisoformat(m.get("_dt", "")))
        except Exception:
            pass
    span_min = None
    if len(dts) >= 2:
        span_min = (max(dts) - min(dts)).total_seconds() / 60.0
    froms = {(m.get("from", "") or "").strip().lower() for m in members}
    subs  = {_dup_normalize_subject(m.get("subject", "")) for m in members}
    if len(froms) == 1 and len(subs) == 1:
        if span_min is not None and span_min <= 2:
            return 92, "same sender & subject, sent within 2 minutes"
        if span_min is not None and span_min <= 20:
            return 75, "same sender & subject, sent within 20 minutes"
        return 55, "same sender & subject, but sent far apart in time"
    if len(froms) == 1:
        return 35, "same sender, subject differs — worth a look, not certain"
    return 20, "weak match — check before trusting this one"


def _find_duplicate_groups(messages: list) -> list:
    """[{"members": [...], "score": int, "why": str}, …], most confident
    first. A message can only belong to one group — the Message-ID pass
    claims its members before the sender/subject pass ever sees them."""
    by_mid, claimed = {}, set()
    for m in messages:
        mid = (m.get("_message_id") or "").strip()
        if mid:
            by_mid.setdefault(mid, []).append(m)
    groups = []
    for members in by_mid.values():
        if len(members) < 2:
            continue
        score, why = _dup_score_group(members)
        groups.append({"members": members, "score": score, "why": why})
        claimed.update(id(m) for m in members)
    by_fs = {}
    for m in messages:
        if id(m) in claimed:
            continue
        key = ((m.get("from", "") or "").strip().lower(),
               _dup_normalize_subject(m.get("subject", "")))
        if not key[0] or not key[1]:
            continue
        by_fs.setdefault(key, []).append(m)
    for members in by_fs.values():
        if len(members) < 2:
            continue
        score, why = _dup_score_group(members)
        if score < 30:
            continue
        groups.append({"members": members, "score": score, "why": why})
    groups.sort(key=lambda g: (-g["score"], -len(g["members"])))
    return groups


# ── 8. Read-only IMAP search across folders ───────────────────────────────────

# The folders a wide search walks, in the order results are grouped. All Mail
# is skipped on purpose: on Gmail it contains a copy of nearly everything, so
# including it would just double every hit.
_SEARCH_FOLDERS = ["Inbox", "Sent", "Drafts", "Starred", "Spam", "Trash"]


# ── 7b. WHAT A WIDE SEARCH LEAVES OUT (Issu 2026-08-17) ───────────────────────
#
# "Search has three choices. It could have a fourth as well — All except…,
#  where a setting lets you pick folders (or whole accounts) to keep out of the
#  search. I am going to put 0---Frakt & kvitto in there."
#
# A search that always drags the same three thousand postage receipts along is
# a search you stop using. So: two lists in the settings, and one scope that
# honours them.
#
# The stored key is "<account>\t<folder>", the same shape hidden_folders and
# mini_hidden_folders already use. <folder> is whatever the search actually
# asks the server for — a standard name ("Inbox", "Sent"…) or the RAW mailbox
# name of one of your own labels, which is the string _imap_search_folders and
# _search_account_by_field select. Never the pretty display name: that is a
# rendering of the raw name and would stop matching the moment anything about
# the path changed.
#
# "*" in place of the account means "this folder name in EVERY account" — one
# entry for a label you keep in all of them. Nothing in the dialog writes those
# yet; the matcher understands them so a hand-edited settings.json works.

def _search_excluded_accounts(cfg) -> set:
    """Accounts a wide search must not touch at all, lower-cased."""
    return {str(a).strip().lower()
            for a in (cfg.get("search_exclude_accounts") or [])
            if str(a).strip()}


def _search_account_skipped(cfg, email_addr) -> bool:
    return (email_addr or "").strip().lower() in _search_excluded_accounts(cfg)


def _search_excluded_folders(cfg) -> set:
    """{(account-lower, folder), …} — malformed entries are ignored rather
    than crashing a search someone is waiting for."""
    out = set()
    for key in (cfg.get("search_exclude_folders") or []):
        key = str(key)
        if "\t" not in key:
            continue
        acct, folder = key.split("\t", 1)
        if folder:
            out.add((acct.strip().lower(), folder))
    return out


def _search_folder_skipped(cfg, email_addr, folder, excluded=None) -> bool:
    ex = _search_excluded_folders(cfg) if excluded is None else excluded
    acct = (email_addr or "").strip().lower()
    return (acct, folder) in ex or ("*", folder) in ex


def _search_keep_folders(cfg, email_addr, folders) -> list:
    """`folders` with the excluded ones removed, order kept."""
    ex = _search_excluded_folders(cfg)
    return [f for f in folders
            if not _search_folder_skipped(cfg, email_addr, f, ex)]


def _imap_search_folders(email_addr, password, query, folders=None,
                         per_folder=60):
    """Search several mailboxes of ONE account and return message dicts.

    READ-ONLY exactly like _fetch_folder: select(readonly=True) + BODY.PEEK[].
    The IMAP search itself is done server-side (TEXT), so it covers the whole
    mailbox and not just what has been downloaded."""
    folders = folders or _SEARCH_FOLDERS
    results = []
    imap = _imap_connect(email_addr, password)
    try:
        mapping = _discover_mailboxes(imap)
        for folder in folders:
            mailbox = mapping.get(folder, folder)
            try:
                typ, _ = imap.select(_mb_arg(mailbox), readonly=True)
                if typ != "OK":
                    continue
                # IMAP wants the search string as a literal when it is not
                # plain ASCII; imaplib handles that when we pass bytes with a
                # declared charset.
                try:
                    typ, data = imap.uid("SEARCH", "CHARSET", "UTF-8", "TEXT",
                                         f'"{query}"'.encode("utf-8"))
                except Exception:
                    # BYTES here too (Issu 2026-08-17). This fallback used to
                    # pass a str, and imaplib encodes str arguments as ASCII —
                    # so searching for "räkning" raised UnicodeEncodeError,
                    # the outer handler logged "Search failed in <acct>/Inbox"
                    # and that WHOLE FOLDER silently contributed no hits. His
                    # log has exactly that line. A Swedish search term must
                    # never be the reason a folder looks empty.
                    typ, data = imap.uid("SEARCH", None, "TEXT",
                                         f'"{query}"'.encode("utf-8"))
                if typ != "OK" or not data or not data[0]:
                    continue
                uids = data[0].split()[-per_folder:]
                if not uids:
                    continue
                uid_set = ",".join(u.decode() for u in uids)
                typ, fetched = imap.uid(
                    "FETCH", uid_set,
                    "(UID FLAGS X-GM-THRID X-GM-LABELS BODY.PEEK[])")
                if typ != "OK":
                    continue
                results.extend(_parse_fetch(fetched, email_addr, folder))
            except Exception as e:
                log.warning("Search failed in %s/%s: %s", email_addr, folder, e)
    finally:
        try:
            imap.logout()
        except Exception:
            pass
    results.sort(key=lambda m: m.get("_sortkey", 0.0), reverse=True)
    return results


# ── 8b. SEARCH BY FIELD, FOLDER BY FOLDER (Issu 2026-08-08) ───────────────────
#
# The old wide search asked IMAP for TEXT (headers + body, all in one) and gave
# back a flat list. Two things were missing:
#
#   • "instead of listing all mail in a folder, where I can't see where they
#     are" — you got hits with no sense of WHERE they live, and
#   • "to be able to choose whether to search in topic/subject, in body etc.,
#     several at once, with different colours showing what I found where".
#
# So each chosen FIELD is searched separately. That costs one extra SEARCH per
# field per folder — cheap, because a SEARCH returns only UIDs — and in return
# every hit knows exactly which fields matched it, which is what the colours in
# the search window are showing.
#
# Only HEADERS are fetched for the hits. A search across every folder of five
# accounts must not drag megabytes of bodies over the wire; the body is
# fetched if and when you open one, exactly as everywhere else.
_SEARCH_FIELDS = ["subject", "from", "to", "body"]

_SEARCH_FIELD_LABELS = {
    "subject": "Subject",
    "from":    "Sender",
    "to":      "To / Cc",
    "body":    "Message text",
}

# One colour per field. These are the chips on each hit and the key at the top
# of the search window — change them here and both follow.
_SEARCH_FIELD_COLOURS = {
    "subject": "#4a9eff",     # blue
    "from":    "#3ec98a",     # green
    "to":      "#c9a227",     # amber
    "body":    "#c07ad6",     # violet
}

# How each field becomes an IMAP SEARCH. A tuple is sent as separate atoms.
_SEARCH_FIELD_KEYS = {
    "subject": ("SUBJECT",),
    "from":    ("FROM",),
    "to":      ("OR", "TO", "%s", "CC"),    # %s marks where the term repeats
    "body":    ("BODY",),
}


def _search_one_field(imap, field: str, query: str, per_folder: int) -> set:
    """UIDs in the CURRENTLY SELECTED mailbox matching `query` in one field.

    Non-ASCII needs a declared charset; not every server accepts the CHARSET
    form, so the plain one is the fallback — the same two-step the older search
    already used."""
    q = query.strip()
    if not q:
        return set()
    if field == "to":
        # "OR TO x CC x" — the term appears twice, so it is built by hand.
        args = ("OR", "TO", f'"{q}"', "CC", f'"{q}"')
    else:
        key = _SEARCH_FIELD_KEYS.get(field, ("TEXT",))[0]
        args = (key, f'"{q}"')
    enc = tuple(a.encode("utf-8") if isinstance(a, str) else a for a in args)
    try:
        typ, data = imap.uid("SEARCH", "CHARSET", "UTF-8", *enc)
    except Exception:
        try:
            # `enc`, not `args` (Issu 2026-08-17): imaplib encodes str
            # arguments as ASCII, so a Swedish search term made this fallback
            # raise UnicodeEncodeError — which was then swallowed here and the
            # field simply reported "no hits". Silence is the worst possible
            # answer to a search; bytes cannot hit that path at all.
            typ, data = imap.uid("SEARCH", None, *enc)
        except Exception as e:
            log.debug("search %s failed: %s", field, e)
            return set()
    if typ != "OK" or not data or not data[0]:
        return set()
    return {u.decode() for u in data[0].split()[-per_folder:]}


def _search_account_by_field(email_addr, password, query, fields, folders,
                             per_folder=60, on_folder=None, stop=None,
                             interactive=True):
    """Search one account, folder by folder, one SEARCH per chosen field.

    `on_folder(folder, messages)` is called as EACH folder finishes, so the
    window fills in while the rest is still running instead of showing nothing
    for half a minute. Each message carries `_match_fields` — the set of fields
    that matched it — which is what the colour chips read.

    READ-ONLY throughout: select(readonly=True) + BODY.PEEK[HEADER].
    Returns the full list as well, for callers that just want it in one go."""
    fields = [f for f in (fields or _SEARCH_FIELDS) if f in _SEARCH_FIELD_KEYS]
    if not fields or not (query or "").strip():
        return []
    lane = "ui" if interactive else "bg"
    if interactive:
        _ui_wait_begin()
    all_msgs = []
    imap = _imap_acquire(email_addr, password, lane=lane)
    broken = False
    try:
        mapping = _discover_mailboxes(imap)
        for folder in folders:
            if stop is not None and stop():
                break
            mailbox = mapping.get(folder, folder)
            try:
                typ, _ = imap.select(_mb_arg(mailbox), readonly=True)
                if typ != "OK":
                    continue
                per_uid = {}
                for f in fields:
                    if stop is not None and stop():
                        break
                    for uid in _search_one_field(imap, f, query, per_folder):
                        per_uid.setdefault(uid, set()).add(f)
                if not per_uid:
                    if on_folder is not None:
                        on_folder(folder, [])
                    continue
                # Headers only — a search must never pull bodies.
                uid_set = ",".join(sorted(per_uid, key=lambda u: int(u)
                                          if u.isdigit() else 0)[-per_folder:])
                typ, fetched = imap.uid(
                    "FETCH", uid_set,
                    "(UID FLAGS X-GM-THRID X-GM-LABELS BODY.PEEK[HEADER])")
                if typ != "OK":
                    continue
                msgs = []
                for item in fetched or []:
                    if not isinstance(item, tuple):
                        continue
                    meta_s = (item[0] or b"").decode("utf-8", "replace")
                    um = _re.search(r"UID\s+(\d+)", meta_s)
                    if not um:
                        continue
                    uid = um.group(1)
                    thr = _re.search(r"X-GM-THRID\s+(\d+)", meta_s)
                    try:
                        hdr = _email.message_from_bytes(item[1] or b"")
                        built = _build_msg_dict(
                            hdr, _flags_from_meta(item[0] or b""),
                            thr.group(1) if thr else None, uid,
                            email_addr, folder, meta_s, body_loaded=False)
                    except Exception:
                        continue
                    built["_match_fields"] = sorted(per_uid.get(uid, set()))
                    msgs.append(built)
                msgs.sort(key=lambda m: m.get("_sortkey", 0.0), reverse=True)
                all_msgs.extend(msgs)
                if on_folder is not None:
                    on_folder(folder, msgs)
            except Exception as e:
                log.warning("Search failed in %s/%s: %s", email_addr, folder, e)
    except Exception:
        broken = True
        raise
    finally:
        _imap_release(email_addr, imap, broken, lane=lane)
        if interactive:
            _ui_wait_end()
    return all_msgs


# ── 9. WHOLE-MAILBOX FILTER SWEEP ─────────────────────────────────────────────
#
# "Run mail filters now" only ever saw the messages already downloaded (about
# forty per folder), which is useless for the job Issu actually wanted it for:
# three years of a newsletter, all of it, gone. This block asks GMAIL to find
# everything one rule matches — server-side IMAP SEARCH, whole folders, not just
# what is loaded — and then moves that set to the Trash in one batch.
#
# The safety line is exactly where it is everywhere else in this program:
#   • Finding is READ-ONLY (select(readonly=True) + BODY.PEEK[HEADER]).
#   • Trashing needs "Server changes" ON, is confirmed by hand with the real
#     count in front of you, and MOVES to the Trash — never expunges.
#   • Messages you sent to yourself are skipped (the Gmail one-message-many-
#     labels trap), exactly like the auto-trash filter action.
#
# Only headers are downloaded for the preview, so a 2 000-message sweep is a
# handful of seconds rather than a gigabyte.

# Which folders may be swept, in the order they are offered. Trash is not in the
# list: moving a message from the Trash to the Trash is a no-op, and erasing is
# never automatic here.
_SWEEP_FOLDERS = ["Inbox", "Spam", "All Mail", "Sent"]

# The condition fields IMAP can actually search for us.
_SWEEP_SEARCH_KEY = {"from": "FROM", "subject": "SUBJECT", "body": "BODY"}

# Operators that narrow to a substring the server can look for. The negative
# ones ("doesn't contain", "is not") describe what is NOT there, which no IMAP
# SEARCH can enumerate.
_SWEEP_POSITIVE_OPS = {"contains", "is", "begins", "ends"}

# Never pull more than this many messages per folder in one sweep — a runaway
# rule should be reported, not downloaded.
SWEEP_MAX_PER_FOLDER = 2000


def _sweep_plan(flt: dict) -> dict:
    """Work out whether one rule can be run over the WHOLE mailbox, and with
    what server-side searches.

    Returns {"ok", "why", "searches", "full"}. `searches` is a list of
    {"terms": [{"ci", "key", "value"}…], "cis": {condition indexes}} — run each
    one and take the UNION, which is how an either/or section is expressed in
    IMAP (there is no OR we can rely on across servers, but N searches ORed by
    us is the same answer). `cis` records exactly which conditions a search
    enforced, so _sweep_keep knows which BODY tests it may take on trust.

    With sections that becomes: the MUST rows are ANDed into every search, and
    the EITHER rows contribute one search each.

    A rule is refused rather than half-run whenever the server search could
    quietly MISS matches — being told "this rule can't be swept" is fine, a
    sweep that silently skips half your junk is not."""
    out = {"ok": False, "why": "", "searches": [],
           "full": bool(flt.get("has_attachment"))}
    if flt.get("match_mode", "all") == "every":
        out["why"] = ("this rule matches EVERY message — sweeping it would "
                      "mean the whole mailbox")
        return out
    must, either = _split_conditions(flt)
    if not must and not either:
        out["why"] = "it has no conditions"
        return out

    base, base_cis = [], set()
    for ci, c in must:
        field = c.get("field", "")
        op    = c.get("op", "contains")
        value = (c.get("value", "") or "").strip()
        key   = _SWEEP_SEARCH_KEY.get(field)
        if key and op in _SWEEP_POSITIVE_OPS:
            base.append({"ci": ci, "key": key, "value": value})
            base_cis.add(ci)
        elif field == "body":
            # A MUST row testing what the body does NOT contain: the server can
            # narrow on the others, but checking this one needs every message
            # downloaded. Refuse rather than download the mailbox.
            out["why"] = ("it tests what the message body does NOT contain, "
                          "which needs every message downloaded")
            return out
        # Any other unsearchable MUST row is fine: it only ever REMOVES
        # messages from the result, and _sweep_keep re-checks it locally.

    if either:
        # One search per ALTERNATIVE. A pair's rows are ANDed into the same
        # search, which is what makes "(subject A AND from X) OR (subject B
        # AND from Y)" two searches rather than four.
        for alt in _split_alternatives(either):
            terms, cis, unsearchable = [], set(), None
            for ci, c in alt:
                field = c.get("field", "")
                op    = c.get("op", "contains")
                value = (c.get("value", "") or "").strip()
                key   = _SWEEP_SEARCH_KEY.get(field)
                if key and op in _SWEEP_POSITIVE_OPS:
                    terms.append({"ci": ci, "key": key, "value": value})
                    cis.add(ci)
                elif field == "body":
                    # The one row _sweep_keep cannot re-check afterwards: only
                    # headers are downloaded, so a body row that was not part
                    # of the search has no answer at all.
                    out["why"] = ("an either/or row tests what the message "
                                  "BODY does NOT contain, which needs every "
                                  "message downloaded")
                    return out
                elif unsearchable is None:
                    unsearchable = (field, op)
            # A row the server cannot search only ever NARROWS its own
            # alternative, and _sweep_keep re-checks it locally — so a PAIR
            # survives one. An alternative with nothing searchable in it at
            # all is a different matter: it pulls messages in on its own, so
            # not searching it means an incomplete result.
            if not terms:
                field, op = unsearchable or ("", "")
                out["why"] = (
                    f"an either/or row "
                    f"({_FILTER_FIELD_LABELS.get(field, field)} "
                    f"{_FILTER_OP_LABELS.get(op, op)}) cannot be searched on "
                    f"the server")
                return out
            out["searches"].append({"terms": base + terms,
                                    "cis": base_cis | cis})
    elif base:
        out["searches"].append({"terms": list(base), "cis": set(base_cis)})

    if not out["searches"]:
        out["why"] = ("it has nothing the server can search for "
                      "(needs a From, Subject or Body condition)")
        return out
    out["ok"] = True
    return _soften_searches(out)


def _sweep_keep(flt: dict, msg: dict) -> bool:
    """Re-check one swept message locally, so the sweep is never wider than the
    rule itself.

    IMAP SEARCH is always a substring match, so "is" / "begins with" / "ends
    with" come back too generous — those are enforced here.

    A condition on the BODY is the one thing that cannot be re-checked: only
    the headers were downloaded. It is therefore true exactly when the search
    that enforced it returned this message, which `_sweep_hits` records per
    condition index — no guessing, and it works the same for a MUST row and an
    either/or row."""
    if not _filter_folder_ok(flt, msg):
        return False
    must, either = _split_conditions(flt)
    hits = msg.get("_sweep_hits") or set()

    def _ev(ci, c):
        if c.get("field") == "body":
            return ci in hits
        return _op_match(c.get("op", "contains"),
                         _cond_hay(c.get("field", ""), msg),
                         (c.get("value", "") or "").strip())

    if not must and not either:
        return False
    ok = all(_ev(ci, c) for ci, c in must)
    if ok and either:
        ok = any(all(_ev(ci, c) for ci, c in alt)
                 for alt in _split_alternatives(either))
    if ok and flt.get("has_attachment") and not msg.get("attachments"):
        return False
    return ok


def _imap_quote(value: str) -> str:
    """One IMAP quoted-string, with everything that would break the command
    escaped: a quote or a backslash inside the text, and any line break (which
    would otherwise end the command halfway through a search term)."""
    v = (value or "").replace("\\", "\\\\").replace('"', '\\"')
    v = v.replace("\r", " ").replace("\n", " ")
    return f'"{v}"'


# ── Gmail's index has no apostrophes in it (Issu 2026-08-23) ─────────────────
#
# His "Potentiella köpare" rule found nothing, ever, and his own guess was
# right: "apostrof-problem?". The log settles it — same folder, same minute:
#
#   SUBJECT "Sålt objekt"      → 3 uid(s)      SUBJECT "Beställt:"      → ok
#   SUBJECT "Skickade: \""     → 1 uid(s)      SUBJECT "Du har fått…"   → ok
#   SUBJECT "I'm interested in" → 0 uids       SUBJECT "[BGG] I'm"      → 0 uids
#
# Colons, quotes, brackets and å/ä/ö are all fine. Only the apostrophe fails,
# and it fails in every folder of every account — while sixteen matching
# geekmails sit in the Inbox with "[BGG] I'm interested in …" in plain sight.
# Gmail's IMAP SEARCH is served by Gmail's own word index, which folds the
# apostrophe away ("I'm" → "im"), so a phrase containing one matches nothing.
# There is no quoting that fixes it: it is not a syntax problem, the server
# simply has no such word.
#
# So ask for less and check it here. A CONTIGUOUS piece of the phrase with no
# apostrophe in it is matched by every message the whole phrase matches, so
# the search stays a superset and _sweep_keep narrows it to exactly the rule
# again. Whole words only — "I'm interested in" asks for "interested in", not
# "m interested in", because Gmail has no token "m" either.
#
#   "I'm interested in"  →  "interested in"
#   "[BGG] I'm"          →  "[BGG]"        (every BGG mail, then filtered here)
#
# BODY terms are left alone on purpose. The body is never downloaded, so a
# widened body search could not be re-checked and would file mail the rule
# does not really match; better it keeps failing loudly than passes quietly.

_APOSTROPHES = "'’‘ʼ´`"
_APOS_RUN_RE = _re.compile("[^" + _re.escape(_APOSTROPHES) + "]+")


def _search_soften(value: str) -> str:
    """The longest whole-word stretch of `value` with no apostrophe in it, or
    `value` unchanged when there is none (or nothing usable left)."""
    if not value or not any(ch in value for ch in _APOSTROPHES):
        return value
    best, n = "", len(value)
    for m in _APOS_RUN_RE.finditer(value):
        s, e = m.start(), m.end()
        if s > 0:                       # an apostrophe on the left: the first
            while s < e and not value[s].isspace():   # word is a fragment
                s += 1
        if e < n:                       # …and on the right, the last one is
            while e > s and not value[e - 1].isspace():
                e -= 1
        piece = value[s:e].strip()
        if len(piece) > len(best):
            best = piece
    return best if len(best) >= 2 else value


def _soften_searches(plan: dict) -> dict:
    """Rewrite a plan so no search carries an apostrophe to the server.

    Done here, on the PLAN, rather than down in the IMAP call: the plan is
    what both rule kinds are built from and what a test can look at, and
    dropping the condition index out of `cis` in the same breath is what
    tells _sweep_keep to test the whole phrase locally instead of taking the
    server's word for it."""
    for s in plan.get("searches", []):
        out = []
        for t in s.get("terms", []):
            v = t.get("value") or ""
            # BODY is left alone: the body is never downloaded, so a widened
            # body search could not be re-checked here.
            if t.get("raw") or t.get("key") == "BODY" or not v:
                out.append(t)
                continue
            sv = _search_soften(v)
            if sv == v:
                out.append(t)
                continue
            out.append(dict(t, value=sv, softened=v))
            s["cis"] = set(s.get("cis") or ()) - {t.get("ci")}
            log.info("SEARCH: %s %r holds an apostrophe, which Gmail's index "
                     "does not — asking for %r instead and checking the whole "
                     "phrase locally", t.get("key"), v, sv)
        s["terms"] = out
    return plan


def _term_show(t: dict) -> str:
    """One SEARCH term as it will go over the wire, for the log. A bare key
    (ALL, UNSEEN, SEEN) shows on its own — it carries no argument."""
    if t.get("raw"):
        v = t.get("value") or ""
        return f'{t["key"]} {v}'.strip()
    return f'{t["key"]} {_imap_quote(t.get("value", ""))}'


def _sweep_age_terms(newer_days=0, older_days=0) -> list:
    """Extra IMAP SEARCH terms that limit a sweep BY AGE (Issu 2026-08-03:
    "checkboxar för all / only inbox / only last 7 days").

    Returns terms in the same {"key", "value"} shape as _sweep_plan, but with
    `raw=True` so the value is sent as a bare atom — SINCE and BEFORE take a
    date like 03-Aug-2026, NOT a quoted string, and quoting it makes Gmail
    return nothing at all rather than complain.

    Dates are what the SERVER stored (INTERNALDATE), which is what you want
    here: "everything older than a year" should mean when it arrived."""
    out = []
    today = datetime.now().date()
    if newer_days and newer_days > 0:
        since = today - timedelta(days=int(newer_days))
        out.append({"ci": -1, "key": "SINCE", "raw": True,
                    "value": since.strftime("%d-%b-%Y")})
    if older_days and older_days > 0:
        before = today - timedelta(days=int(older_days))
        out.append({"ci": -1, "key": "BEFORE", "raw": True,
                    "value": before.strftime("%d-%b-%Y")})
    return out


def _imap_sweep_search(email_addr, password, plan, folders,
                       per_folder=SWEEP_MAX_PER_FOLDER, progress=None,
                       extra_terms=None):
    """Ask ONE account's server which messages a rule matches, in each folder.

    Returns (messages, notes). Every message dict carries _folder, uid and
    _sweep_hits (the condition indexes whose search returned it). READ-ONLY:
    select(readonly=True) and BODY.PEEK — the same guarantee as a normal fetch.

    `progress` is called with a short status line from the worker thread; the
    caller is responsible for marshalling it back to the GUI thread."""
    out, notes = [], []
    fetch_what = ("(UID FLAGS X-GM-THRID X-GM-LABELS BODY.PEEK[])"
                  if plan.get("full") else
                  "(UID FLAGS X-GM-THRID X-GM-LABELS BODY.PEEK[HEADER])")
    imap = _imap_connect(email_addr, password)
    try:
        mapping = _discover_mailboxes(imap)
        log.info("SWEEP %s: %d search(es) %s full=%s folders=%s",
                 email_addr, len(plan.get("searches", [])),
                 [[(t["key"], t["value"]) for t in s["terms"]]
                  for s in plan.get("searches", [])],
                 plan.get("full"), folders)
        for folder in folders:
            mailbox = _resolve_mailbox(imap, folder, mapping)
            try:
                typ, _ = imap.select(_mb_arg(mailbox), readonly=True)
                if typ != "OK":
                    log.warning("SWEEP %s: could not open %s (raw %r) — %s",
                                email_addr, folder, mailbox, typ)
                    notes.append(f"{folder}: could not be opened on the server")
                    continue
                if progress:
                    progress(f"Searching {email_addr} · {folder}…")

                def _search(terms):
                    """One UID SEARCH with the given terms ANDed together.

                    Every step is logged. "The sweep finds nothing" was
                    impossible to answer before, because a refused search, a
                    search that legitimately returned zero, and a search that
                    raised on the way out all looked identical from the
                    outside (Issu 2026-08-03)."""
                    # The age limits (SINCE / BEFORE) are ANDed onto EVERY
                    # search, including each separate one in "any" mode — a
                    # date range narrows the whole sweep, it is not one more
                    # thing a message may match on.
                    # ── A Swedish search word is not a quoted string ──────────
                    #
                    # Issu 2026-08-18: every sweep whose subject held an "ä"
                    # came back BAD "Could not parse command", so "Ditt
                    # inlämningskvitto" and "Inlämningskvitto" found NOTHING —
                    # which quietly meant no DHL, PostNord or DSV receipt was
                    # ever swept, while Tradera and Vinted (plain ASCII) worked
                    # and made it look as though the sweep was fine.
                    #
                    # RFC 3501 is the reason: a quoted string is 7-bit only.
                    # Non-ASCII has to go as a LITERAL — {18}\r\n then the raw
                    # bytes — and imaplib will only do that for ONE argument,
                    # the last one. SEARCH keys are ANDed, so their order is
                    # ours to choose: the non-ASCII term is moved to the end
                    # and sent as the literal.
                    #
                    # If a search needs more than one such term, the extra ones
                    # are left OUT of the query and enforced locally instead:
                    # the server then returns a SUPERSET and _sweep_keep
                    # narrows it down exactly. `enforced` says which conditions
                    # the server really proved, so nothing is taken on trust
                    # that was not actually asked.
                    terms = list(terms) + list(extra_terms or [])
                    enforced = {t["ci"] for t in terms}

                    def _is_ascii(t):
                        return bool(t.get("raw")) or (t["value"] or "").isascii()

                    ascii_terms = [t for t in terms if _is_ascii(t)]
                    wide_terms  = [t for t in terms if not _is_ascii(t)]
                    literal_t   = wide_terms[0] if wide_terms else None
                    for t in wide_terms[1:]:
                        enforced.discard(t["ci"])
                        log.info("SWEEP %s/%s: %s %r cannot share a command "
                                 "with another non-ASCII term — left out of "
                                 "the search and checked here instead",
                                 email_addr, folder, t["key"], t["value"])
                    if not ascii_terms and literal_t is None:
                        return [], enforced           # nothing to ask

                    ordered = ascii_terms + ([literal_t] if literal_t else [])
                    shown = " ".join(_term_show(t) for t in ordered)

                    def _args_for(send):
                        """Positional args for everything except the literal."""
                        out_ = []
                        for t in send:
                            out_.append(t["key"])
                            # A bare SEARCH key — ALL, UNSEEN, SEEN — takes no
                            # argument at all (DEL 51). Sending an empty one
                            # makes the server answer BAD.
                            if t.get("raw") and not (t.get("value") or ""):
                                continue
                            out_.append(
                                t["value"].encode("ascii") if t.get("raw")
                                else _imap_quote(t["value"]).encode("utf-8"))
                        return out_

                    def _run():
                        """One SEARCH. The literal, when there is one, is armed
                        immediately before the command — imaplib consumes and
                        clears it, so it must never be set early or left set."""
                        args = _args_for(ascii_terms)
                        if literal_t is not None:
                            args.append(literal_t["key"])
                            imap.literal = (literal_t["value"]
                                            .encode("utf-8"))
                        return imap.uid("SEARCH", "CHARSET", "UTF-8", *args)

                    try:
                        typ_, data_ = _run()
                    except Exception as e1:
                        imap.literal = None       # never leave one armed
                        log.warning("SWEEP %s/%s: SEARCH CHARSET UTF-8 %s "
                                    "failed (%s) — dropping the non-ASCII "
                                    "term(s) and checking them here instead",
                                    email_addr, folder, shown, e1)
                        # Last resort: ask only what is plainly askable and let
                        # _sweep_keep do the rest. A wider search costs a few
                        # more headers; a refused one costs Issu his receipts.
                        if not ascii_terms:
                            notes.append(f"{folder}: the server refused the "
                                         f"search ({e1})")
                            return [], enforced
                        if literal_t is not None:
                            enforced.discard(literal_t["ci"])
                        shown = " ".join(_term_show(t) for t in ascii_terms)
                        try:
                            typ_, data_ = imap.uid("SEARCH", "CHARSET",
                                                   "UTF-8",
                                                   *_args_for(ascii_terms))
                        except Exception as e:
                            log.warning("SWEEP %s/%s: search %s failed: %s",
                                        email_addr, folder, shown, e)
                            notes.append(f"{folder}: the server refused the "
                                         f"search ({e})")
                            return [], enforced
                    if typ_ != "OK":
                        log.warning("SWEEP %s/%s: %s → %s %r",
                                    email_addr, folder, shown, typ_, data_)
                        notes.append(f"{folder}: the server answered {typ_} "
                                     f"to the search")
                        return [], enforced
                    if not data_ or not data_[0]:
                        log.info("SWEEP %s/%s: %s → 0 uids",
                                 email_addr, folder, shown)
                        return [], enforced
                    hit = data_[0].split()
                    log.info("SWEEP %s/%s: %s → %d uid(s)%s",
                             email_addr, folder, shown, len(hit),
                             "" if enforced == {t["ci"] for t in terms}
                             else "  (some conditions checked here, not on "
                                  "the server)")
                    return hit, enforced

                # One search per either/or row, ANDed with the MUST rows, and
                # the results UNIONed — that is how a two-section rule is asked
                # of a server with no reliable OR. A rule with no either/or
                # section is simply one search (see _sweep_plan).
                hits = {}       # uid(str) -> set of condition indexes proven
                for s in plan.get("searches", []):
                    found_uids, enforced = _search(s["terms"])
                    # Only what the SERVER actually proved may be taken on
                    # trust — a term left out of the query proves nothing.
                    proven = s["cis"] & enforced
                    for u in found_uids:
                        hits.setdefault(u.decode(), set()).update(proven)
                if not hits:
                    continue

                uids = sorted(hits, key=lambda s: int(s) if s.isdigit() else 0)
                if len(uids) > per_folder:
                    notes.append(f"{folder}: {len(uids)} matches, only the "
                                 f"newest {per_folder} were listed")
                    uids = uids[-per_folder:]

                # Fetch in chunks — one enormous FETCH line upsets some servers
                # and gives no feedback at all while it runs.
                for i in range(0, len(uids), 200):
                    chunk = uids[i:i + 200]
                    if progress:
                        progress(f"Reading {email_addr} · {folder} "
                                 f"({i + len(chunk)}/{len(uids)})…")
                    typ, fetched = imap.uid("FETCH", ",".join(chunk),
                                            fetch_what)
                    if typ != "OK":
                        continue
                    for m in _parse_fetch(fetched, email_addr, folder):
                        m["_sweep_hits"] = hits.get(str(m.get("uid")), set())
                        out.append(m)
            except Exception as e:
                log.warning("Sweep failed in %s/%s: %s", email_addr, folder, e)
                notes.append(f"{folder}: {e}")
    finally:
        try:
            imap.logout()
        except Exception:
            pass
    out.sort(key=lambda m: m.get("_sortkey", 0.0), reverse=True)
    return out, notes


# ==============================================================================
# DEL 51 — THE MAIL RELOCATOR  (Issu 2026-08-23)
# ==============================================================================
#
# "Jag vill ha in en relocator-funktion … som skiljer sig från filter. Jag
#  matar in, som i de andra programmen … och de som jag väljer (som i file
#  manager … ett eller alla) körs och flyttar mail från olika/samma konton
#  till bestämda ställen. Filter kör vanligtvis vid hämtning … eller manuell
#  filter. Detta ska vara separat sak … körs enbart manuellt."
#
# So: the same thing File_manager's ⤴ Relocator does for files, for mail.
# Type the rules in, tick the ones you want, press ▶ on one or ▶▶ on the lot,
# and the mail moves. The differences from the filter engine are the whole
# point and are deliberate:
#
#   FILTERS                            THE RELOCATOR
#   run on every fetch (and on         runs ONLY when you press the button —
#     "run filters now")                 never on a fetch, never on a timer
#   see the ~40 messages that were     asks GMAIL ITSELF, so it reaches years
#     downloaded                         of mail the program never downloaded
#   one rule set, all-or-nothing       tick one, tick five, tick none
#   many actions (read, tag, hide,     ONE action: move it there
#     trash, cross-account…)
#   conditions with sections,          a plain form: from / to / subject /
#     operators, either-or               body / age / read state
#
# It is built on the whole-mailbox sweep (DEL 04v) rather than beside it:
# _imap_sweep_search does the searching, _imap_move_uids the moving, and
# _split_protected keeps the promise that nothing automatic takes mail out of
# a protected folder. A Relocator rule simply builds the same `plan` the
# sweep already understands.
#
# Safety, all of it borrowed from code that already had to earn it:
#   • the search is READ-ONLY (select readonly, BODY.PEEK) — pressing ▶ shows
#     you the count and the destination BEFORE anything moves;
#   • "Server changes" must be on, offered inline like everywhere else;
#   • protected folders are never emptied;
#   • a message already in the destination is skipped, not moved onto itself;
#   • cross-account rules go through _deliver_cross_account, which will not
#     upload a header-only copy and will not deliver the same message twice.

_RELOC_F = os.path.join(_ACCOUNTS_DIR, "relocator.json")

_RELOC_KEYS = {
    "name": "", "enabled": True,
    "accounts": [],            # [] = every real account
    "folders": ["Inbox"],      # where to look (from _SWEEP_FOLDERS + labels)
    # Conditions in the FILTER engine's own shape (Issu 2026-08-23: "gör som
    # med filter att jag kan lägga till flera saker, t.ex. 3 olika subjects
    # och 2 olika From, och att jag väljer om det räcker med en, eller om
    # någon ska ha kriteriet att det ska vara X OCH Y"):
    #   {"field": from|to|subject|body|folder, "op": contains|is|…,
    #    "value": "...", "group": "all" | "any"}
    # group "all" = MUST be true; group "any" = at least ONE of them must be.
    # Sharing the shape is not laziness — it means _split_conditions,
    # _sweep_plan, _sweep_keep and _filter_describe all work on a Relocator
    # rule unchanged, so the two rule kinds can never drift apart on what
    # "AND" means.
    "conditions": [],
    "newer_h": 0, "older_h": 0,   # age limits, in HOURS (0 = no limit)
    "state": "any",               # any | unread | read
    "has_attachment": False,
    "action": "move",             # move | trash
    "dest_account": "",           # "" = the account the message is already in
    "dest_folder": "",
    "mark_read": False,
    "per_folder": 500,
}

_RELOC_ACTIONS = ("move", "trash")


def _reloc_norm(rule: dict) -> dict:
    """One rule with every key present and of the right type — and the older
    shapes of it quietly brought up to date, so a rule saved this morning
    still runs tonight."""
    r = dict(_RELOC_KEYS)
    r["conditions"] = []
    for k, v in (rule or {}).items():
        if k in r:
            r[k] = v
    r["accounts"] = [a for a in (r["accounts"] or []) if a]
    r["folders"] = [f for f in (r["folders"] or []) if f] or ["Inbox"]

    # ── The first shape: one box per field, all ANDed ────────────────────
    conds = []
    for c in (r["conditions"] or []):
        if not isinstance(c, dict):
            continue
        value = (c.get("value", "") or "").strip()
        if not value:
            continue                       # an empty row is not a condition
        row = {
            "field": c.get("field", "from"),
            "op":    c.get("op", "contains"),
            "value": value,
            "group": "any" if c.get("group") == "any" else "all",
        }
        # A pair only means anything among alternatives, so it is dropped off
        # a MUST row rather than kept as a label nothing reads.
        pair = _cond_pair(c) if row["group"] == "any" else ""
        if pair:
            row["pair"] = pair
        conds.append(row)
    for field in ("from", "to", "subject", "body"):
        old = ((rule or {}).get(field) or "").strip()
        if old and not any(c["field"] == field and c["value"] == old
                           for c in conds):
            conds.append({"field": field, "op": "contains", "value": old,
                          "group": "all"})
    r["conditions"] = conds

    # ── Age: days became hours (Issu: "efter X timmar/dagar") ────────────
    for new_key, old_key in (("newer_h", "newer_days"), ("older_h", "older_days")):
        try:
            r[new_key] = max(0, int(r[new_key] or 0))
        except (TypeError, ValueError):
            r[new_key] = 0
        if not r[new_key]:
            try:
                r[new_key] = max(0, int((rule or {}).get(old_key) or 0)) * 24
            except (TypeError, ValueError):
                pass
    try:
        r["per_folder"] = max(0, int(r["per_folder"] or 0)) or 500
    except (TypeError, ValueError):
        r["per_folder"] = 500

    if r["state"] not in ("any", "unread", "read"):
        r["state"] = "any"
    if r["action"] not in _RELOC_ACTIONS:
        r["action"] = "move"
    if not r["has_attachment"]:
        r["has_attachment"] = bool((rule or {}).get("attach_only"))
    r["has_attachment"] = bool(r["has_attachment"])
    r["mark_read"] = bool(r["mark_read"])
    r["enabled"] = bool(r["enabled"])
    for k in ("name", "dest_account", "dest_folder"):
        r[k] = (r[k] or "").strip()
    return r


def _load_reloc() -> dict:
    store = _load_json_store(_RELOC_F, {"rules": list}, "relocator rules")
    store["rules"] = [_reloc_norm(r) for r in (store.get("rules") or [])]
    return store


def _save_reloc(store: dict):
    _save_json_store(_RELOC_F, store, "relocator rules")


def _reloc_state_term(state: str):
    """The read state as a bare SEARCH key, or None."""
    if state == "unread":
        return {"ci": -10, "key": "UNSEEN", "raw": True, "value": ""}
    if state == "read":
        return {"ci": -11, "key": "SEEN", "raw": True, "value": ""}
    return None


def _reloc_plan(rule: dict) -> dict:
    """The rule as something _imap_sweep_search can run.

    Conditions are handed straight to _sweep_plan — it already knows how to
    turn MUST rows and either/or rows into one search per OR row, and how to
    refuse a rule the server could only half-answer. What is added here is
    the Relocator's own three: the read state (a bare UNSEEN/SEEN, ANDed onto
    every search), the destination check, and the case _sweep_plan rightly
    refuses but this does not — a rule with NO text conditions at all, which
    for "everything in here older than two days" is the whole point."""
    r = _reloc_norm(rule)
    out = {"ok": False, "why": "", "searches": [], "full": False}
    if r["action"] == "move" and not r["dest_folder"]:
        out["why"] = "it has no destination folder"
        return out
    must, either = _split_conditions(r)
    has_age = bool(r["newer_h"] or r["older_h"])
    state_term = _reloc_state_term(r["state"])

    if must or either:
        plan = _sweep_plan(r)
        if not plan["ok"]:
            return plan                    # its own "why" is the better one
        out = plan
    elif has_age or state_term or r["has_attachment"]:
        base = state_term or {"ci": -1, "key": "ALL", "raw": True, "value": ""}
        out = {"ok": True, "why": "",
               "searches": [{"terms": [base], "cis": set()}],
               "full": bool(r["has_attachment"])}
        state_term = None                  # already in there
    else:
        out["why"] = ("it says nothing about WHICH mail to take — add a "
                      "condition, an age or a read state, or it would take "
                      "the whole folder")
        return out

    if state_term:
        for s in out["searches"]:
            s["terms"] = list(s["terms"]) + [state_term]
    # Whole messages are only needed when the mail has to be UPLOADED to
    # another account; a move inside one account, and a trash, are UID work
    # and headers are plenty.
    out["full"] = bool(out.get("full")) or bool(
        r["dest_account"] and r["action"] == "move")
    out["ok"] = True
    return out


def _reloc_extra_terms(rule: dict) -> list:
    """SINCE / BEFORE for the age limits.

    IMAP can only search whole DAYS, and he asked for hours ("efter X
    timmar/dagar"), so these are deliberately a little too generous: the day
    the cut-off falls on is included whole, and _reloc_keep then does the
    exact comparison. A superset costs a few more headers; a too-narrow
    search would silently miss mail."""
    r = _reloc_norm(rule)
    out = []
    now = datetime.now()
    if r["newer_h"]:
        cut = now - timedelta(hours=r["newer_h"])
        out.append({"ci": -2, "key": "SINCE", "raw": True,
                    "value": cut.strftime("%d-%b-%Y")})
    if r["older_h"]:
        cut = now - timedelta(hours=r["older_h"])
        out.append({"ci": -3, "key": "BEFORE", "raw": True,
                    "value": (cut + timedelta(days=1)).strftime("%d-%b-%Y")})
    return out


def _reloc_keep(rule: dict, msg: dict) -> bool:
    """Re-check one found message locally, so a run is never wider than the
    rule. _sweep_keep does the conditions (it re-tests "is" / "begins with",
    which IMAP can only answer as "contains"); the rest is the Relocator's
    own — and the age in real HOURS, which no IMAP search can express."""
    r = _reloc_norm(rule)
    must, either = _split_conditions(r)
    if must or either:
        if not _sweep_keep(r, msg):
            return False
    elif r["has_attachment"] and not msg.get("attachments"):
        return False
    if r["state"] == "unread" and not msg.get("unread"):
        return False
    if r["state"] == "read" and msg.get("unread"):
        return False
    age_h = _reloc_age_hours(msg)
    if age_h is not None:
        if r["older_h"] and age_h < r["older_h"]:
            return False
        if r["newer_h"] and age_h > r["newer_h"]:
            return False
    # Never move a message onto itself.
    if (r["action"] == "move" and not r["dest_account"]
            and _folder_norm(msg.get("_folder", ""))
            == _folder_norm(r["dest_folder"])):
        return False
    return True


def _reloc_age_hours(msg: dict):
    """How many hours old this message is, or None when it has no date."""
    ts = msg.get("_sortkey") or 0.0
    if not ts:
        return None
    try:
        return max(0.0, (time.time() - float(ts)) / 3600.0)
    except (TypeError, ValueError):
        return None


def _reloc_age_words(hours: int) -> str:
    """"36" → "1 d 12 h". Hours are what he types; days are what he means
    once there are enough of them."""
    h = int(hours or 0)
    if not h:
        return ""
    if h < 24:
        return f"{h} h"
    d, rest = divmod(h, 24)
    return f"{d} d" + (f" {rest} h" if rest else "")


def _reloc_describe(rule: dict) -> str:
    """The one-line "what this rule does" under its name."""
    r = _reloc_norm(rule)
    bits = []
    must, either = _split_conditions(r)
    if must or either:
        sentence = _filter_describe(r)
        bits.append(sentence[len("Matches when: "):]
                    if sentence.startswith("Matches when: ") else sentence)
    if r["state"] == "unread":
        bits.append("unread only")
    elif r["state"] == "read":
        bits.append("read only")
    if r["has_attachment"] and not (must or either):
        bits.append("with an attachment")
    if r["newer_h"]:
        bits.append("newer than " + _reloc_age_words(r["newer_h"]))
    if r["older_h"]:
        bits.append("older than " + _reloc_age_words(r["older_h"]))
    what = "   ·   ".join(bits) or "everything"
    where = ", ".join(r["folders"])
    who = ", ".join(a.split("@")[0] for a in r["accounts"]) or "every account"
    return f"{what}\n     in {where} ({who})   →   {_reloc_dest_label(r)}"


def _reloc_dest_label(rule: dict) -> str:
    r = _reloc_norm(rule)
    if r["action"] == "trash":
        return "🗑 the Trash"
    if r["dest_account"]:
        return f"{r['dest_folder']}  on {r['dest_account']}"
    return r["dest_folder"] or "(no destination)"


def _imap_trash_uids(email_addr, password, folder, uids, chunk=100):
    """Move MANY messages of one folder to the Trash over ONE connection.

    Returns (moved, problems). Same careful path as _imap_trash_message (UID
    MOVE, else COPY + \\Deleted + UID EXPUNGE, never a bare EXPUNGE) — but a
    batch at a time, because logging in once per message would take an hour for
    a real junk clean-out and hammer Gmail's connection limit."""
    uids = [str(u) for u in uids if u]
    if not uids:
        return 0, []
    problems, moved = [], 0
    imap = _imap_connect(email_addr, password)
    try:
        mapping = _discover_mailboxes(imap)
        source  = mapping.get(folder, folder)
        trash   = mapping.get("Trash", "[Gmail]/Trash")
        if source == trash:
            return 0, ["Those messages are already in the Trash."]
        typ, _ = imap.select(f'"{source}"', readonly=False)
        if typ != "OK":
            return 0, [f"Could not open {source} for writing."]
        caps = _imap_capabilities(imap)
        for i in range(0, len(uids), chunk):
            part  = uids[i:i + chunk]
            uid_s = ",".join(part)
            if "MOVE" in caps:
                typ, resp = imap.uid("MOVE", uid_s, f'"{trash}"')
                if typ == "OK":
                    moved += len(part)
                    log.info("Sweep trashed %d message(s) %s/%s → %s",
                             len(part), email_addr, source, trash)
                    continue
                log.warning("Sweep UID MOVE failed (%s), falling back: %s",
                            typ, resp)
            typ, resp = imap.uid("COPY", uid_s, f'"{trash}"')
            if typ != "OK":
                problems.append(f"{folder}: could not copy to the Trash: {resp}")
                continue
            typ, resp = imap.uid("STORE", uid_s, "+FLAGS", "(\\Deleted)")
            if typ != "OK":
                problems.append(f"{folder}: copied to the Trash but the "
                                f"originals could not be flagged — you may "
                                f"now have two copies.")
                continue
            if "UIDPLUS" in caps:
                typ, resp = imap.uid("EXPUNGE", uid_s)
                if typ != "OK":
                    problems.append(f"{folder}: copied to the Trash, but "
                                    f"removing the originals failed: {resp}")
                    continue
                moved += len(part)
                log.info("Sweep trashed %d message(s) (COPY+UID EXPUNGE) %s/%s",
                         len(part), email_addr, source)
            else:
                moved += len(part)
                problems.append(
                    f"{folder}: the messages are in the Trash, but your server "
                    f"cannot remove single messages, so the originals are only "
                    f"marked as deleted. Nothing was erased.")
    finally:
        try:
            imap.logout()
        except Exception:
            pass
    return moved, problems


# ******************************************************************************
# DEL 04f — CALENDAR: store, recurrence, .ics import/export, reminders
# ******************************************************************************
#
# A local calendar in the Thunderbird spirit: your events live in one JSON
# file next to every other setting, meeting invitations that arrive by mail
# can be imported with one click, and reminders pop up while the program is
# running.
#
# What this deliberately is NOT: a CalDAV/Google Calendar client. Syncing
# would mean writing to a server, and this program's whole Phase-1 contract is
# that it never changes anything out there. Import and export of .ics files
# covers the practical cases (an invitation arrives, or you hand an event to
# another program) without breaking that promise.
#
# EVENT SHAPE
# {"id", "title", "location", "description",
#  "start": iso, "end": iso, "all_day": bool,
#  "rrule": {"freq": "DAILY"|"WEEKLY"|"MONTHLY"|"YEARLY",
#            "interval": int, "count": int|0, "until": iso|"",
#            "byday": ["MO","WE"]},          # byday only used by WEEKLY
#  "reminders": [minutes_before, ...],       # [] = no reminder
#  "color": "#rrggbb", "uid": <ics UID>, "source": "manual"|"ics",
#  "created": iso}

import calendar as _calmod

_CALENDAR_F = os.path.join(_ACCOUNTS_DIR, "calendar.json")

# Minutes-before options that USED to be offered as one flat checkbox list.
# Superseded 2026-08-13 by the adaptive Days/Hours/Minutes builder + smart-%
# buttons further down (see REMINDER_HOUR_CHOICES etc.) — kept here only as a
# reference for the offsets people are used to; the editor no longer reads it.
REMINDER_CHOICES = [
    (0,     "At the time of the event"),
    (5,     "5 minutes before"),
    (15,    "15 minutes before"),
    (30,    "30 minutes before"),
    (60,    "1 hour before"),
    (120,   "2 hours before"),
    (1440,  "1 day before"),
    (2880,  "2 days before"),
    (10080, "1 week before"),
]

# ── Adaptive "days / hours / minutes" reminder builder (Issu 2026-08-13) ──────
# The old idea was one flat list of fixed offsets (5 min … 1 week). Problem:
# with a day left, "15/30/60 min before" are all nearly worthless and there is
# nothing between 1 hour and 1 day; with a week left, hour-level ticks are
# noise. So instead the editor now builds ONE offset at a time from three
# dropdowns and adds it to the event's reminder list — the day range is
# capped to how much lead time the event actually has (see
# EventEditor._max_reminder_days), so you cannot build an offset that is
# already overdue the moment you save. On top of that, 5 "smart" buttons
# fire a reminder at a given PERCENTAGE of the remaining time, so the offer
# always scales with however far out the event is.
REMINDER_HOUR_CHOICES   = [0, 1, 2, 3, 4, 5, 6, 12, 24]
REMINDER_MINUTE_CHOICES = [0, 5, 10, 15, 30, 60]
REMINDER_SMART_PERCENTS = [10, 25, 50, 75, 90]

def _format_reminder_label(mins) -> str:
    """Human-readable label for an arbitrary minutes-before offset, e.g.
    "2 days 3 hours before" for values that don't land on a round unit."""
    mins = max(0, int(mins))
    if mins == 0:
        return "At the time of the event"
    if mins % 10080 == 0:
        w = mins // 10080
        return f"{w} week{'s' if w != 1 else ''} before"
    if mins % 1440 == 0:
        d = mins // 1440
        return f"{d} day{'s' if d != 1 else ''} before"
    if mins < 60:
        return f"{mins} minutes before"
    if mins % 60 == 0:
        h = mins // 60
        return f"{h} hour{'s' if h != 1 else ''} before"
    d, rem = divmod(mins, 1440)
    h, m = divmod(rem, 60)
    parts = ([f"{d} day{'s' if d != 1 else ''}"] if d else []) + \
            ([f"{h} h"] if h else []) + ([f"{m} min"] if m else [])
    return " ".join(parts) + " before"


# ── DEL 04f3 — SNOOZE OFFERS THAT SCALE WITH THE TIME LEFT (Issu 2026-08-22) ──
#
# "Reminder ger mig fortfarande bara 5, 15, 60 minuter… som alternativ. Det är
#  24 timmar kvar… 1 vecka kvar, då blir det löjligt med 1 timme. 3 timmar
#  kvar, då fungerar det inte att påminna igen om 1 dygn."
#
# The event EDITOR was made adaptive in 2026-08-13 (the smart-% buttons above);
# the reminder POP-UP was not, and it is the pop-up he actually meets. Its
# three buttons were the literal constants 5 / 15 / 60, which are right for an
# event twenty minutes away and useless for anything else — in both directions.
#
# The offers are now a share of what is actually LEFT (roughly 15 % / 35 % /
# 60 %), snapped down to a round interval so the button says "3 h" and not
# "3 h 36 min". Two properties matter more than the exact fractions:
#   • nothing is ever offered that would fire AFTER the event (the 90 % cap) —
#     a snooze that outlives the thing it is reminding you about is not a
#     reminder, it is a way of missing it;
#   • and the smallest offer is never below 5 minutes, so the list stays
#     usable when the event is nearly on top of you.
#
# Worked through, which is the quickest way to see it is right:
#   24 h left → 3 h  ·  8 h  ·  12 h        (was 5 / 15 / 60 min)
#    1 week   → 1 day · 2 days · 3 days
#    3 h left → 15 min · 1 h · 1 h 30 min   (and never "tomorrow")
#   20 min    → 5 min · 10 min
_SNOOZE_LADDER = [5, 10, 15, 30, 45, 60, 90, 120, 180, 240, 360, 480, 720,
                  1440, 2880, 4320, 10080]


def _snooze_choices(left_min) -> list:
    """Minute values to offer on a reminder with `left_min` minutes to go.

    `left_min` None or ≤ 0 means the event is already here or is an all-day
    entry with no meaningful countdown — then the old short ladder is exactly
    right, because the only sensible question left is "nudge me again soon"."""
    try:
        left = int(left_min)
    except (TypeError, ValueError):
        left = 0
    if left <= 0:
        return [5, 15, 60]
    cap   = max(5, int(left * 0.9))     # must still land before the event
    picks = []
    for frac in (0.15, 0.35, 0.60):
        want    = min(left * frac, cap)
        smaller = [v for v in _SNOOZE_LADDER if v <= want]
        v = smaller[-1] if smaller else 5
        # Two fractions can snap onto the same rung (0.35 and 0.60 of three
        # days both land on "1 day"). Step up rather than drop the offer —
        # three buttons that differ beat two that are further apart.
        if v in picks:
            bigger = [x for x in _SNOOZE_LADDER if x > v and x <= cap]
            if not bigger:
                continue
            v = bigger[0]
        if v <= cap and v not in picks:
            picks.append(v)
    return sorted(picks) or [5]


def _snooze_label(mins) -> str:
    """Short button text for a snooze interval: "15 min", "3 h", "2 days"."""
    m = max(1, int(mins or 0))
    if m < 60:
        return f"{m} min"
    if m < 1440:
        h, r = divmod(m, 60)
        return f"{h} h" if not r else f"{h} h {r} min"
    if m % 10080 == 0:
        w = m // 10080
        return f"{w} week{'s' if w != 1 else ''}"
    d, r = divmod(m, 1440)
    if not r:
        return f"{d} day{'s' if d != 1 else ''}"
    return f"{d} d {r // 60} h"


# ── Repeating / accelerating reminders (DEL 04f2) ─────────────────────────────
# Beyond the fixed "X before" ticks, an event can carry a repeating SERIES:
# start reminding `lead_min` before it, then keep reminding until it starts.
# Even spacing = the same `interval_min` gap the whole way; accelerating = small
# gaps near the event that grow the further out you go (Issu's snowball idea:
# 3 h at the end, then 6 h, 12 h, a day at the start).
REMINDER_LEAD_CHOICES = [
    (60, "1 hour before"), (120, "2 hours before"), (360, "6 hours before"),
    (720, "12 hours before"), (1440, "1 day before"), (2880, "2 days before"),
    (10080, "1 week before"),
]
REMINDER_EVERY_CHOICES = [
    (30, "30 minutes"), (60, "1 hour"), (120, "2 hours"), (180, "3 hours"),
    (360, "6 hours"), (720, "12 hours"), (1440, "1 day"),
]

def _reminder_series_offsets(lead_min, interval_min, accelerate) -> list:
    """Minute offsets before an event at which a repeating reminder fires, from
    `lead_min` down to 0 (the event time).

    Even spacing = every `interval_min`. Accelerating = the gap starts at
    `interval_min` near the event and DOUBLES every two reminders as you move
    away, so you get frequent nudges just before and only the occasional early
    heads-up. Capped so a silly setting cannot schedule hundreds of popups."""
    lead_min     = max(0, int(lead_min or 0))
    interval_min = max(5, int(interval_min or 60))
    offsets = [0]
    if not accelerate:
        cur = interval_min
        while cur <= lead_min and len(offsets) < 60:
            offsets.append(cur)
            cur += interval_min
    else:
        cur, gap, n = interval_min, interval_min, 0
        while cur <= lead_min and len(offsets) < 60:
            offsets.append(cur)
            cur += gap
            n += 1
            if n >= 2:          # two reminders at each gap, then it doubles
                gap *= 2
                n = 0
    if lead_min and lead_min not in offsets:
        offsets.append(lead_min)     # always give the earliest heads-up
    return sorted(set(int(o) for o in offsets))[:40]

# How loud a reminder is (Issu: gentle for away-from-desk things, insistent for
# a Skype meeting; and "more intense the closer you get"). Stored per event as
# `alert`: "silent" (popup only) | "sound" (a beep) | "insistent" (beeps that
# escalate the nearer the event is, plus a taskbar flash).
ALERT_CHOICES = [("silent", "Silent (popup only)"),
                 ("sound", "A sound"),
                 ("insistent", "Insistent (louder as it nears)")]

def _alert_beeps(alert: str, mins) -> int:
    """How many beeps a reminder should make. 0 = silent. Insistent scales with
    closeness: one far out, a whole burst at the event time itself."""
    if alert == "silent":
        return 0
    if alert != "insistent":
        return 1
    try:
        m = int(mins or 0)
    except (TypeError, ValueError):
        m = 0
    if m == 0:
        return 8
    if m <= 5:
        return 4
    if m <= 15:
        return 2
    return 1

def _event_reminder_minutes(ev: dict) -> list:
    """Every minute-offset an event should fire a reminder at: the fixed ticked
    ones PLUS any repeating/accelerating series, de-duplicated."""
    mins = set(int(m) for m in (ev.get("reminders") or []))
    ser = ev.get("reminder_series") or {}
    if ser.get("enabled"):
        for o in _reminder_series_offsets(ser.get("lead_min", 1440),
                                          ser.get("interval_min", 180),
                                          bool(ser.get("accelerate"))):
            mins.add(int(o))
    return sorted(mins)

# Full names for the "put the date & time in the title" helper. Hard-coded (not
# locale-dependent strftime) so they are always English, per the English-only
# rule — these become part of the user's event title.
_FULL_WEEKDAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
                  "Saturday", "Sunday"]
_FULL_MONTHS = ["January", "February", "March", "April", "May", "June", "July",
                "August", "September", "October", "November", "December"]

def _event_title_suffix(start_dt, all_day, fmt="name") -> str:
    """The ", <when>" tail auto-added to an event title (Issu: type just
    'Doctor', get 'Doctor, Friday 10.00 (14 August)'). Two shapes: "name"
    (Friday 10.00 (14 August)) or "numeric" (14/08 (Friday) 10.00)."""
    wd  = _FULL_WEEKDAYS[start_dt.weekday()]
    mon = _FULL_MONTHS[start_dt.month - 1]
    if all_day:
        if fmt == "numeric":
            return f", {start_dt.strftime('%d/%m')} ({wd})"
        return f", {wd} ({start_dt.day} {mon})"
    hm = start_dt.strftime("%H.%M")
    if fmt == "numeric":
        return f", {start_dt.strftime('%d/%m')} ({wd}) {hm}"
    return f", {wd} {hm} ({start_dt.day} {mon})"

# A palette for event colours — same idea as the contact colours.
EVENT_PALETTE = ["#4dabf7", "#69db7c", "#ffd43b", "#ff6b6b", "#b197fc",
                 "#38d9a9", "#ffa94d", "#f783ac"]

_WEEKDAY_CODES = ["MO", "TU", "WE", "TH", "FR", "SA", "SU"]


def _load_calendar() -> dict:
    """{"events": [...], "fired": [...]}.

    "fired" remembers which reminders have already been shown, as
    "<event id>|<occurrence iso>|<minutes>" strings, so a repeating event does
    not nag again for the same occurrence after a restart."""
    store = _load_json_store(_CALENDAR_F,
                            {"events": list, "fired": list}, "calendar")
    for ev in store.get("events", []):
        ev.setdefault("id", _new_id())
        ev.setdefault("rrule", {})
        ev.setdefault("reminders", [])
        ev.setdefault("all_day", False)
        ev.setdefault("color", EVENT_PALETTE[0])
    return store


def _save_calendar(store: dict):
    _save_json_store(_CALENDAR_F, store, "calendar")


# ── Recurrence ────────────────────────────────────────────────────────────────

def _rrule_of(ev: dict) -> dict:
    r = ev.get("rrule") or {}
    freq = (r.get("freq") or "").upper()
    if freq not in ("DAILY", "WEEKLY", "MONTHLY", "YEARLY"):
        return {}
    return {
        "freq":     freq,
        "interval": max(1, int(r.get("interval") or 1)),
        "count":    max(0, int(r.get("count") or 0)),
        "until":    r.get("until") or "",
        "byday":    [d for d in (r.get("byday") or []) if d in _WEEKDAY_CODES],
    }


def _add_months(dt, months):
    """Shift a datetime by whole months, clamping the day (31 Jan + 1 month
    is 28/29 Feb, which is what every calendar program does)."""
    y = dt.year + (dt.month - 1 + months) // 12
    m = (dt.month - 1 + months) % 12 + 1
    d = min(dt.day, _calmod.monthrange(y, m)[1])
    return dt.replace(year=y, month=m, day=d)


def _event_occurrences(ev: dict, win_start, win_end, limit=500) -> list:
    """Every start-datetime of `ev` that falls inside [win_start, win_end).

    A non-repeating event yields at most one. The limit is a guard: a badly
    formed rule must never spin forever."""
    start = _parse_iso(ev.get("start", ""))
    if start is None:
        return []
    rule = _rrule_of(ev)
    if not rule:
        return [start] if win_start <= start < win_end else []

    until = _parse_iso(rule["until"]) if rule["until"] else None
    count = rule["count"]
    interval = rule["interval"]
    freq = rule["freq"]
    out, produced, guard = [], 0, 0

    def _emit(dt):
        """Record one occurrence; return False when we are done for good."""
        nonlocal produced
        if until is not None and dt > until:
            return False
        if count and produced >= count:
            return False
        produced += 1
        if win_start <= dt < win_end:
            out.append(dt)
        return dt < win_end

    if freq == "WEEKLY" and rule["byday"]:
        # Week-by-week: the event's own week is the anchor, and inside every
        # Nth week each selected weekday produces an occurrence.
        week_anchor = start - timedelta(days=start.weekday())
        cur = week_anchor
        while guard < limit * 7:
            guard += 1
            keep_going = False
            for code in sorted(rule["byday"], key=_WEEKDAY_CODES.index):
                dt = cur + timedelta(days=_WEEKDAY_CODES.index(code))
                dt = dt.replace(hour=start.hour, minute=start.minute,
                                second=0, microsecond=0)
                if dt < start:
                    continue
                keep_going = _emit(dt)
                if not keep_going and (count and produced >= count):
                    return out
            if until is not None and cur > until:
                break
            if cur > win_end:
                break
            if cur - week_anchor > timedelta(days=366 * 6):
                break
            cur += timedelta(weeks=interval)
        return out

    cur = start
    while guard < limit:
        guard += 1
        if not _emit(cur) and cur >= win_end:
            break
        if count and produced >= count:
            break
        if until is not None and cur > until:
            break
        if freq == "DAILY":
            cur = cur + timedelta(days=interval)
        elif freq == "WEEKLY":
            cur = cur + timedelta(weeks=interval)
        elif freq == "MONTHLY":
            cur = _add_months(cur, interval)
        else:                                    # YEARLY
            cur = _add_months(cur, 12 * interval)
    return out


def _events_between(store: dict, win_start, win_end) -> list:
    """All (occurrence_start, event) pairs in a window, chronologically."""
    rows = []
    for ev in store.get("events", []):
        for dt in _event_occurrences(ev, win_start, win_end):
            rows.append((dt, ev))
    rows.sort(key=lambda r: (r[0], r[1].get("title", "")))
    return rows


def _events_by_day(store: dict, win_start, win_end) -> dict:
    """{date: [(occurrence_start, event), ...]} for a grid view.

    Unlike _events_between this SPREADS an event over every day it covers, so
    a holiday from the 1st to the 14th shows up on all fourteen days instead
    of only on the first — which is what a month grid is for. The occurrence
    start is kept unchanged on every day, so clicking any of them edits the
    same event and the time shown is still the real start time.

    A guard caps how many days one event may occupy: a mistyped end date
    (year 2226) must not paint the entire grid."""
    by_day = {}
    # Widen the search backwards so an event that STARTED before the window
    # but still runs into it is not missed. Only as far back as the LONGEST
    # event actually needs — a fixed year of lookback made every month view
    # expand a year of daily recurrences for nothing.
    longest = timedelta(days=1)
    for ev in store.get("events", []):
        d = _event_duration(ev)
        if d > longest:
            longest = d
    lookback = win_start - min(longest, timedelta(days=370))
    for occ, ev in _events_between(store, lookback, win_end):
        end = occ + _event_duration(ev)
        # An all-day event's end is exclusive (see EventEditor._collect), and
        # a timed event that stops at 00:00 should not claim the next day.
        last = end - timedelta(seconds=1)
        day = occ
        guard = 0
        while day.date() <= last.date() and guard < 400:
            guard += 1
            if win_start.date() <= day.date() < win_end.date():
                by_day.setdefault(day.date(), []).append((occ, ev))
            day += timedelta(days=1)
    for items in by_day.values():
        items.sort(key=lambda r: (not r[1].get("all_day"), r[0],
                                  r[1].get("title", "")))
    return by_day


def _event_duration(ev: dict) -> timedelta:
    start = _parse_iso(ev.get("start", ""))
    end   = _parse_iso(ev.get("end", ""))
    if start and end and end > start:
        return end - start
    return timedelta(days=1) if ev.get("all_day") else timedelta(hours=1)


def _fmt_event_time(dt, ev) -> str:
    if ev.get("all_day"):
        return "all day"
    # No end set (the common "I just need the start" case) → show only the
    # start time, not a 10:00–11:00 range (DEL 04f2).
    if not ev.get("has_end", True):
        return dt.strftime("%H:%M")
    end = dt + _event_duration(ev)
    return f"{dt.strftime('%H:%M')}–{end.strftime('%H:%M')}"


# ── Reminders ─────────────────────────────────────────────────────────────────

def _due_reminders(store: dict, now=None, look_back_min=60) -> list:
    """Return [(event, occurrence_dt, minutes_before, key), ...] for reminders
    that should be showing right now and have not been shown yet.

    `look_back_min` catches the case where the program was closed when the
    reminder was due: a meeting you were supposed to be told about ten minutes
    ago is still worth a popup. Anything older than that is skipped, so
    starting the program after a holiday does not bury you in alarms."""
    now = now or datetime.now()
    fired = set(store.get("fired", []))
    out = []
    # Widest reminder we support is one week, so a week-wide window is enough.
    win_start = now - timedelta(minutes=look_back_min)
    win_end   = now + timedelta(days=8)
    for ev in store.get("events", []):
        mins_list = _event_reminder_minutes(ev)
        if not mins_list:
            continue
        for occ in _event_occurrences(ev, win_start, win_end):
            for mins in mins_list:
                fire_at = occ - timedelta(minutes=mins)
                if not (win_start <= fire_at <= now):
                    continue
                key = f"{ev.get('id','')}|{occ.isoformat(timespec='minutes')}|{mins}"
                if key in fired:
                    continue
                out.append((ev, occ, mins, key))
    out.sort(key=lambda r: r[1])
    return out


def _mark_reminder_fired(store: dict, key: str):
    fired = store.setdefault("fired", [])
    if key not in fired:
        fired.append(key)
    # Keep the list from growing without bound — only recent keys matter.
    if len(fired) > 400:
        store["fired"] = fired[-200:]
    _save_calendar(store)


# NOTE: there is intentionally no _unfire_reminder(). Snoozing a reminder
# keeps its "fired" flag set and re-arms the popup in memory instead
# (_snooze_reminder, DEL 09d). Clearing the flag would let the engine ALSO
# rediscover the same reminder on its next tick, so you would get the popup
# back immediately instead of in five minutes.


# ── .ics (iCalendar) import ───────────────────────────────────────────────────

def _ics_unfold(text: str) -> list:
    """RFC 5545 line folding: a line starting with a space or tab continues
    the previous one."""
    lines = []
    for raw in (text or "").replace("\r\n", "\n").replace("\r", "\n").split("\n"):
        if raw[:1] in (" ", "\t") and lines:
            lines[-1] += raw[1:]
        else:
            lines.append(raw)
    return lines


def _ics_unescape(value: str) -> str:
    return (value.replace("\\n", "\n").replace("\\N", "\n")
                 .replace("\\,", ",").replace("\\;", ";")
                 .replace("\\\\", "\\"))


def _ics_parse_dt(value: str, params: dict):
    """Parse DTSTART/DTEND. Returns (datetime, is_all_day).

    A trailing Z means UTC and is converted to local time. A TZID is taken at
    face value (treated as local) — without a timezone database that is the
    honest approximation, and it is right whenever the invitation comes from
    someone in your own timezone, which is the common case."""
    v = (value or "").strip()
    if not v:
        return None, False
    if params.get("VALUE", "").upper() == "DATE" or len(v) == 8:
        try:
            return datetime.strptime(v, "%Y%m%d"), True
        except ValueError:
            return None, False
    utc = v.endswith("Z")
    if utc:
        v = v[:-1]
    for fmt in ("%Y%m%dT%H%M%S", "%Y%m%dT%H%M"):
        try:
            dt = datetime.strptime(v, fmt)
        except ValueError:
            continue
        if utc:
            # Convert UTC → local using the offset in force at that moment.
            try:
                from datetime import timezone
                dt = (dt.replace(tzinfo=timezone.utc)
                        .astimezone().replace(tzinfo=None))
            except Exception:
                pass
        return dt, False
    return None, False


def _ics_parse_trigger(value: str) -> int:
    """VALARM TRIGGER like "-PT15M" / "-P1D" → minutes before. Positive
    triggers (after the event) are not supported and return 0."""
    v = (value or "").strip().upper()
    m = _re.match(r'^-?P(?:(\d+)W)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?)?$', v)
    if not m:
        return 0
    weeks, days, hours, mins = (int(g or 0) for g in m.groups())
    total = weeks * 10080 + days * 1440 + hours * 60 + mins
    return total if v.startswith("-") else 0


def _ics_parse(text: str) -> list:
    """Turn an .ics file into a list of our event dicts. Unknown properties
    are ignored rather than rejected — invitations in the wild carry all kinds
    of vendor extensions."""
    events, cur, alarm = [], None, None
    for line in _ics_unfold(text):
        line = line.strip()
        if not line:
            continue
        upper = line.upper()
        if upper.startswith("BEGIN:VEVENT"):
            cur = {"id": _new_id(), "title": "", "location": "",
                   "description": "", "start": "", "end": "", "all_day": False,
                   "rrule": {}, "reminders": [], "color": EVENT_PALETTE[0],
                   "uid": "", "source": "ics", "created": _now_iso()}
            continue
        if upper.startswith("END:VEVENT"):
            if cur is not None and cur.get("start"):
                if not cur.get("title"):
                    cur["title"] = "(no title)"
                events.append(cur)
            cur, alarm = None, None
            continue
        if cur is None:
            continue
        if upper.startswith("BEGIN:VALARM"):
            alarm = True
            continue
        if upper.startswith("END:VALARM"):
            alarm = False
            continue

        name, _, value = line.partition(":")
        parts  = name.split(";")
        prop   = parts[0].upper()
        params = {}
        for p in parts[1:]:
            k, _, v = p.partition("=")
            params[k.upper()] = v
        value = _ics_unescape(value)

        if alarm:
            if prop == "TRIGGER":
                mins = _ics_parse_trigger(value)
                if mins and mins not in cur["reminders"]:
                    cur["reminders"].append(mins)
            continue

        if prop == "SUMMARY":
            cur["title"] = value.strip()
        elif prop == "LOCATION":
            cur["location"] = value.strip()
        elif prop == "DESCRIPTION":
            cur["description"] = value.strip()
        elif prop == "UID":
            cur["uid"] = value.strip()
        elif prop == "DTSTART":
            dt, allday = _ics_parse_dt(value, params)
            if dt:
                cur["start"] = dt.isoformat(timespec="seconds")
                cur["all_day"] = allday
        elif prop == "DTEND":
            dt, _allday = _ics_parse_dt(value, params)
            if dt:
                cur["end"] = dt.isoformat(timespec="seconds")
        elif prop == "DURATION" and not cur.get("end"):
            mins = _ics_parse_trigger("-" + value.lstrip("-"))
            st = _parse_iso(cur.get("start", ""))
            if st and mins:
                cur["end"] = (st + timedelta(minutes=mins)
                              ).isoformat(timespec="seconds")
        elif prop == "RRULE":
            rule = {}
            for chunk in value.split(";"):
                k, _, v = chunk.partition("=")
                k = k.upper()
                if k == "FREQ":
                    rule["freq"] = v.upper()
                elif k == "INTERVAL":
                    try:
                        rule["interval"] = int(v)
                    except ValueError:
                        pass
                elif k == "COUNT":
                    try:
                        rule["count"] = int(v)
                    except ValueError:
                        pass
                elif k == "UNTIL":
                    dt, _a = _ics_parse_dt(v, {})
                    if dt:
                        rule["until"] = dt.isoformat(timespec="seconds")
                elif k == "BYDAY":
                    # Strip any ordinal prefix ("2MO" → "MO"); we do not model
                    # "second Monday of the month".
                    rule["byday"] = [_re.sub(r'^[-+]?\d+', '', d).upper()
                                     for d in v.split(",")]
            cur["rrule"] = rule
    # An event with no end gets a sane one so the views have something to draw.
    for ev in events:
        if not ev.get("end"):
            st = _parse_iso(ev["start"])
            if st:
                dur = timedelta(days=1) if ev["all_day"] else timedelta(hours=1)
                ev["end"] = (st + dur).isoformat(timespec="seconds")
    return events


def _find_ics_in_message(msg: dict) -> str:
    """Return the raw .ics text carried by a message, or ''.

    Invitations arrive either as a text/calendar part (captured into
    msg["_ics"] when the message was parsed) or as a plain .ics attachment."""
    ics = (msg.get("_ics") or "").strip()
    if ics:
        return ics
    for fname, data in (msg.get("_attachment_data") or {}).items():
        if fname.lower().endswith(".ics") and data:
            try:
                return data.decode("utf-8", "replace")
            except Exception:
                continue
    return ""


# ── .ics export ───────────────────────────────────────────────────────────────

def _ics_escape(value: str) -> str:
    return ((value or "").replace("\\", "\\\\").replace("\n", "\\n")
            .replace(",", "\\,").replace(";", "\\;"))


def _ics_fmt_dt(dt, all_day=False) -> str:
    return dt.strftime("%Y%m%d") if all_day else dt.strftime("%Y%m%dT%H%M%S")


def _ics_export(events: list) -> str:
    """Serialize events to an .ics document other calendar programs accept."""
    out = ["BEGIN:VCALENDAR", "VERSION:2.0",
           "PRODID:-//Lars Issu Olsson//F(re)email//EN", "CALSCALE:GREGORIAN"]
    for ev in events:
        start = _parse_iso(ev.get("start", ""))
        if start is None:
            continue
        end = _parse_iso(ev.get("end", "")) or (start + _event_duration(ev))
        all_day = bool(ev.get("all_day"))
        out.append("BEGIN:VEVENT")
        out.append(f"UID:{ev.get('uid') or (ev.get('id','') + '@freemail')}")
        out.append(f"DTSTAMP:{datetime.now().strftime('%Y%m%dT%H%M%S')}")
        if all_day:
            out.append(f"DTSTART;VALUE=DATE:{_ics_fmt_dt(start, True)}")
            out.append(f"DTEND;VALUE=DATE:{_ics_fmt_dt(end, True)}")
        else:
            out.append(f"DTSTART:{_ics_fmt_dt(start)}")
            out.append(f"DTEND:{_ics_fmt_dt(end)}")
        out.append(f"SUMMARY:{_ics_escape(ev.get('title',''))}")
        if ev.get("location"):
            out.append(f"LOCATION:{_ics_escape(ev['location'])}")
        if ev.get("description"):
            out.append(f"DESCRIPTION:{_ics_escape(ev['description'])}")
        rule = _rrule_of(ev)
        if rule:
            bits = [f"FREQ={rule['freq']}"]
            if rule["interval"] > 1:
                bits.append(f"INTERVAL={rule['interval']}")
            if rule["count"]:
                bits.append(f"COUNT={rule['count']}")
            if rule["until"]:
                u = _parse_iso(rule["until"])
                if u:
                    bits.append(f"UNTIL={_ics_fmt_dt(u)}")
            if rule["byday"]:
                bits.append("BYDAY=" + ",".join(rule["byday"]))
            out.append("RRULE:" + ";".join(bits))
        for mins in (ev.get("reminders") or []):
            out.append("BEGIN:VALARM")
            out.append("ACTION:DISPLAY")
            out.append(f"DESCRIPTION:{_ics_escape(ev.get('title',''))}")
            out.append(f"TRIGGER:-PT{int(mins)}M")
            out.append("END:VALARM")
        out.append("END:VEVENT")
    out.append("END:VCALENDAR")
    return "\r\n".join(out) + "\r\n"


# ******************************************************************************
# DEL 04g — NOTES: local "mail to myself" that never touches a server
# ******************************************************************************
#
# WHY THIS EXISTS
# ---------------
# Writing a mail to yourself is the classic way to park a thought, a link or a
# receipt. On Gmail that has a nasty edge: a message you send to yourself is
# ONE message carrying both the Inbox and the Sent label — not two copies. Bin
# it from Sent and it disappears from the Inbox too, because it is the same
# message. That is Gmail's data model, not a bug in any mail program, and it
# is exactly the thing you should never have to keep in your head.
#
# A note never goes near a server, so none of that can happen to it: no
# labels, no sync, no other program deleting it. It is a file on your own
# disk that only this program (and you) can touch.
#
# FORMAT
# ------
# One .eml file per note, in a folder you choose (default Helpfiles/Notes).
# .eml because it is the actual e-mail format: notes survive this program
# entirely — you can open them in Thunderbird or Outlook, copy them to a
# backup, or read them in Notepad. There is no database to corrupt and no
# index that can drift out of step with reality: the folder IS the truth,
# and the list is rebuilt by reading it.

_NOTES_DIRNAME = "Notes"


def _notes_dir(cfg: dict) -> str:
    """Where notes are kept. Configurable, because "a specific folder" is
    half the point — you may well want them in your documents, in a synced
    folder, or on another drive."""
    custom = (cfg or {}).get("notes_dir", "") or ""
    return custom.strip() or os.path.join(_FM_DIR, _NOTES_DIRNAME)


def _note_filename(subject: str, when: datetime) -> str:
    stem = _safe_name((subject or "note").strip())[:60] or "note"
    return f"{when.strftime('%Y-%m-%d_%H%M%S')}_{stem}.eml"


def _note_write(cfg: dict, subject: str, body: str, from_addr="",
                to_addr="", attachments=None, attach_data=None,
                origin=None) -> str:
    """Write one note as an .eml file and return its path.

    `attachments` are file paths to copy in; `attach_data` is {name: bytes}
    for attachments that came from a received message (they are already in
    memory, no need to go back to the server). `origin` is the message a note
    was made from, recorded in headers so you can see where it came from."""
    folder = _notes_dir(cfg)
    os.makedirs(folder, exist_ok=True)
    now = datetime.now()

    em = EmailMessage()
    em["Subject"] = subject or "(no subject)"
    em["From"]    = from_addr or "me"
    em["To"]      = to_addr or "me"
    em["Date"]    = format_datetime(now)
    # Marks this as ours, and keeps the trail back to the original message.
    em["X-Freemail-Note"] = "yes"
    if origin:
        em["X-Freemail-Note-Source"] = "message"
        if origin.get("from"):
            em["X-Freemail-Origin-From"] = origin.get("from", "")
        if origin.get("date"):
            em["X-Freemail-Origin-Date"] = str(origin.get("date", ""))
        if origin.get("_message_id"):
            em["X-Freemail-Origin-Id"] = origin.get("_message_id", "")
    else:
        em["X-Freemail-Note-Source"] = "written"
    em.set_content(body or "")

    for path in (attachments or []):
        try:
            with open(path, "rb") as f:
                data = f.read()
            ctype, _ = mimetypes.guess_type(path)
            maintype, subtype = (ctype.split("/", 1) if ctype
                                 else ("application", "octet-stream"))
            em.add_attachment(data, maintype=maintype, subtype=subtype,
                              filename=os.path.basename(path))
        except Exception as e:
            log.warning("Note: could not attach %s: %s", path, e)

    for name, data in (attach_data or {}).items():
        if not data:
            continue
        try:
            ctype, _ = mimetypes.guess_type(name)
            maintype, subtype = (ctype.split("/", 1) if ctype
                                 else ("application", "octet-stream"))
            em.add_attachment(data, maintype=maintype, subtype=subtype,
                              filename=name)
        except Exception as e:
            log.warning("Note: could not attach %s: %s", name, e)

    path = os.path.join(folder, _note_filename(subject, now))
    n = 1
    while os.path.exists(path):          # same subject in the same second
        root_, ext_ = os.path.splitext(path)
        path = f"{root_}({n}){ext_}"
        n += 1
    with open(path, "wb") as f:
        f.write(em.as_bytes())
    log.info("Note written: %s", path)
    return path


def _notes_search(cfg: dict, query: str) -> list:
    """Notes matching a query, for the wide search.

    Notes live on disk, not on the server, so an IMAP SEARCH can never find
    them — they have to be searched separately or "All folders" would quietly
    skip the one folder you are surest about."""
    q = (query or "").strip().lower()
    if not q:
        return []
    hits = []
    for note in _notes_list(cfg):
        if (q in (note.get("subject", "") or "").lower()
                or q in (note.get("body", "") or "").lower()
                or q in (note.get("from", "") or "").lower()
                or any(q in a.lower() for a in note.get("attachments", []))):
            hits.append(note)
    return hits


def _notes_list(cfg: dict) -> list:
    """Every note, newest first, as message dicts the normal list can render.

    Rebuilt by reading the folder, so notes you copy in from elsewhere (or
    delete in Explorer) simply appear or disappear — there is no index to
    keep in step."""
    folder = _notes_dir(cfg)
    out = []
    try:
        if not os.path.isdir(folder):
            return []
        names = [n for n in os.listdir(folder) if n.lower().endswith(".eml")]
    except Exception as e:
        log.warning("Could not list notes: %s", e)
        return []

    for name in names:
        path = os.path.join(folder, name)
        try:
            with open(path, "rb") as f:
                em = _email.message_from_bytes(f.read())
        except Exception as e:
            log.warning("Skipping unreadable note %s: %s", name, e)
            continue
        msg = _build_msg_dict(em, [b"\\Seen"], None, None, "", "Notes", "")
        msg["unread"]     = False        # a note you wrote is not "unread"
        msg["_note_path"] = path
        msg["id"]         = path         # stable, unique, and human-readable
        msg["thread_id"]  = path
        if not msg.get("_sortkey"):
            # No parsable Date header — fall back to the file's own time so
            # sorting still works.
            try:
                msg["_sortkey"] = os.path.getmtime(path)
            except OSError:
                msg["_sortkey"] = 0.0
        out.append(msg)
    out.sort(key=lambda m: m.get("_sortkey", 0.0), reverse=True)
    return out


def _note_delete(path: str) -> bool:
    """Delete one note file. This IS a real delete — but of a local file you
    made, never of anything on a server."""
    try:
        if path and os.path.isfile(path):
            os.remove(path)
            log.info("Note deleted: %s", path)
            return True
    except Exception as e:
        log.error("Could not delete note %s: %s", path, e)
    return False


# ==============================================================================
# DEL 04g3 — THE POST-IT BOARD (Issu 2026-08-22)
# ==============================================================================
#
# "Notes-systemet känns lite överkomplicerat. Bättre om det bara är något som
#  mitt Notes-program (som jag kör genom Tower-programmet). Ha något liknande i
#  Freemail; en Post-it-/notes-funktion."
#
# He is right, and the reason is worth writing down rather than just fixing.
# The notes above are .eml files: a note is written in a full compose window,
# gets a From/To/Date/Subject, is saved as a mail message and read back as a
# fake mailbox. That machinery earns its keep for ONE job — "save this message,
# attachments and all, to my own disk" — because there the thing being kept
# really is a mail. For "milk, eggs, ring the dentist" it is all cost: four
# header fields to fill in before you can write a word, and a mailbox to browse
# afterwards.
#
# So this is the other kind of note, sitting beside it rather than replacing
# it. One plain-text file, one screen, no fields you must fill in, a colour so
# the eye finds the right one. Deliberately built like his own Notes.py:
#   • ONE readable text file, sections marked by a header line, so the file is
#     the truth and Notepad can edit it. No database, no index to drift.
#   • The title is just the first thing you type; nothing is mandatory.
#   • It saves itself — leaving a note is not an act that needs a button.
# "Save this MESSAGE to Notes" is untouched and still writes .eml, because for
# that job the .eml is the right answer.

_POSTIT_MARK = "#=== "          # a section header line starts with this

# (name, card/paper colour, accent) — dark-theme post-it tints, chosen so
# C_FG text keeps its contrast on every one of them.
_POSTIT_COLORS = [
    ("Yellow", "#6b6320", "#e0cf6a"),
    ("Pink",   "#6b2a3a", "#eda0b4"),
    ("Blue",   "#1f4d6b", "#8ecbf0"),
    ("Green",  "#265c33", "#8edaa0"),
    ("Purple", "#4a3a70", "#bdaef0"),
]


def _postit_path() -> str:
    """The one file the board lives in. Kept inside this program's own folder
    (never in a Notes folder that may be shared with Notes.py) so nothing else
    can be surprised by it."""
    return os.path.join(_FM_DIR, _NOTES_DIRNAME, "postit.txt")


def _postit_parse(text: str) -> list:
    """Read the file format back into note dicts.

    Anything before the first header line is kept as an untitled note rather
    than thrown away — if a person edits this file by hand, losing what they
    typed because they forgot a marker would be unforgivable."""
    notes, cur = [], None

    def _flush():
        if cur is not None:
            cur["body"] = "\n".join(cur["body"]).strip("\n")
            notes.append(cur)

    for line in (text or "").splitlines():
        if line.startswith(_POSTIT_MARK):
            _flush()
            head = line[len(_POSTIT_MARK):]
            title, color, pinned, updated = head, 0, False, ""
            # Metadata is appended as " | k=v" pairs, so it is parsed off the
            # RIGHT and a title may contain anything that is not one of them.
            while " | " in title:
                left, _sep, tail = title.rpartition(" | ")
                key, _eq, val = tail.partition("=")
                key = key.strip().lower()
                if key == "c":
                    try:
                        color = max(0, min(len(_POSTIT_COLORS) - 1, int(val)))
                    except ValueError:
                        color = 0
                elif key == "p":
                    pinned = val.strip() in ("1", "true", "yes")
                elif key == "u":
                    updated = val.strip()
                else:
                    break                    # not metadata — part of the title
                title = left
            cur = {"title": title.strip(), "color": color, "pinned": pinned,
                   "updated": updated, "body": []}
        else:
            if cur is None:
                cur = {"title": "", "color": 0, "pinned": False,
                       "updated": "", "body": []}
            cur["body"].append(line)
    _flush()
    return notes


def _postit_load() -> list:
    path = _postit_path()
    try:
        if not os.path.isfile(path):
            return []
        with open(path, "r", encoding="utf-8", errors="replace") as f:
            return _postit_parse(f.read())
    except Exception as e:
        log.error("Could not read the post-it file %s: %s", path, e)
        return []


def _postit_render(notes: list) -> str:
    out = []
    for n in notes:
        title = (n.get("title") or "").replace("\n", " ").strip()
        out.append(f"{_POSTIT_MARK}{title} | c={int(n.get('color', 0))} "
                   f"| p={1 if n.get('pinned') else 0} "
                   f"| u={n.get('updated') or _now_iso()}")
        body = (n.get("body") or "")
        if body:
            out.append(body.rstrip("\n"))
        out.append("")
    return "\n".join(out).rstrip("\n") + "\n"


def _postit_save(notes: list) -> bool:
    """Write the whole board. Via a temp file and os.replace, so a crash
    half-way through cannot leave him with half a board."""
    path = _postit_path()
    try:
        os.makedirs(os.path.dirname(path), exist_ok=True)
        tmp = path + ".tmp"
        with open(tmp, "w", encoding="utf-8") as f:
            f.write(_postit_render(notes))
        os.replace(tmp, path)
        return True
    except Exception as e:
        log.error("Could not write the post-it file %s: %s", path, e)
        return False


def _postit_order(notes: list) -> list:
    """Pinned first, then most recently changed. Stable, so two notes edited
    in the same minute do not swap places while you look at them."""
    idx = {id(n): i for i, n in enumerate(notes)}
    return sorted(notes,
                  key=lambda n: (0 if n.get("pinned") else 1,
                                 _neg_iso(n.get("updated", "")),
                                 idx.get(id(n), 0)))


def _neg_iso(value: str):
    """Sort key that puts the NEWEST iso timestamp first. Strings cannot be
    negated, so the ordering is inverted by mapping each character."""
    return tuple(-ord(c) for c in (value or ""))


def _is_self_message(msg: dict) -> bool:
    """Did this message go from one of my own addresses to the same address?

    Used for the Gmail single-copy warning: those are precisely the messages
    that live in Inbox AND Sent as one object."""
    sender  = (parseaddr(msg.get("from", ""))[1] or "").lower()
    account = (msg.get("account_email", "") or "").lower()
    if not sender or not account:
        return False
    if sender != account:
        return False
    to_hdr = (msg.get("_to_hdr", "") or "").lower()
    return (not to_hdr) or (account in to_hdr)


# ******************************************************************************
# DEL 04h — LOCAL ARCHIVE: your own copy of everything, on your own disk
# ******************************************************************************
#
# WHAT THIS IS, AND WHAT IT IS NOT
# --------------------------------
# People coming from POP3 expect a setting like "leave a copy on the server /
# remove it after 14 days". That setting belongs to POP3, where the mail is
# DOWNLOADED to your computer and the server copy is a leftover you decide
# what to do with. This program speaks IMAP, where it is the other way round:
# the mailbox on the server IS the mail, and what you see here is a view of
# it. There is no local copy to keep or discard — so there is nothing for a
# "keep on server?" question to mean.
#
# The real want behind that question is ownership: I would like MY copy, so I
# am not left with nothing if an account is closed, hijacked or emptied. That
# is what this section does, and it only ever ADDS:
#
#   • Faithful .eml copies of every message the program fetches, written to a
#     folder you choose and organised account / folder / year-month.
#   • Optionally automatic, so every message you ever look at is quietly kept.
#   • Idempotent: the same message is written once, no matter how many times
#     it is fetched (matched on Message-ID, falling back to a content hash).
#
# It never deletes anything, here or at Google. Removing mail from the server
# is Phase 2 and needs an explicit decision that has not been made — and see
# the note at the end of this section for why "delete from the server after N
# days" is a bad idea to automate at all.

import hashlib


def _archive_dir(cfg: dict) -> str:
    custom = (cfg or {}).get("archive_dir", "") or ""
    return custom.strip() or os.path.join(_FM_DIR, "Archive")


def _archive_key(msg: dict) -> str:
    """A stable identity for "have I already archived this?".

    Message-ID is the right answer when there is one — it is assigned by the
    sending server and survives re-fetching, moving and relabelling. When a
    message has none (rare, but it happens), a hash of the raw bytes is used
    instead, which is just as stable for our purpose."""
    mid = (msg.get("_message_id") or "").strip()
    if mid:
        return hashlib.sha1(mid.encode("utf-8", "replace")).hexdigest()[:16]
    raw = msg.get("_raw") or b""
    if raw:
        return hashlib.sha1(raw).hexdigest()[:16]
    seed = f"{msg.get('account_email','')}|{msg.get('from','')}|" \
           f"{msg.get('subject','')}|{msg.get('_dt','')}"
    return hashlib.sha1(seed.encode("utf-8", "replace")).hexdigest()[:16]


def _archive_path_for(cfg: dict, msg: dict) -> str:
    """account / folder / YYYY-MM / YYYY-MM-DD_subject_key.eml

    Dated folders because an archive is something you go looking through
    years later, in Explorer, without this program running."""
    base    = _archive_dir(cfg)
    account = _safe_name(msg.get("account_email") or "unknown")
    folder  = _safe_name(msg.get("_folder") or "Inbox")
    dt_iso  = msg.get("_dt", "") or ""
    ym      = dt_iso[:7] or "undated"
    day     = dt_iso[:10] or "undated"
    subject = _safe_name((msg.get("subject") or "no subject").strip())[:50]
    name    = f"{day}_{subject}_{_archive_key(msg)}.eml"
    return os.path.join(base, account, folder, ym, name)


def _archive_message(cfg: dict, msg: dict) -> str:
    """Write one message to the archive. Returns the path, or "" if it was
    already there (or could not be written — the log says which)."""
    path = _archive_path_for(cfg, msg)
    if os.path.exists(path):
        return ""                     # already archived — idempotent
    raw = msg.get("_raw")
    if not raw:
        # No original bytes (a note, demo data, or a message from before the
        # raw source was kept). Rebuild something faithful enough to be worth
        # having rather than skipping it silently.
        em = EmailMessage()
        em["Subject"] = msg.get("subject", "") or "(no subject)"
        em["From"]    = msg.get("from", "")
        em["To"]      = msg.get("_to_hdr", "") or msg.get("account_email", "")
        if msg.get("_dt"):
            dt = _parse_msg_dt(msg["_dt"])
            if dt:
                em["Date"] = format_datetime(dt)
        em["X-Freemail-Archive"] = "rebuilt-without-original-source"
        em.set_content(msg.get("body", "") or "")
        for fname, data in (msg.get("_attachment_data") or {}).items():
            if not data:
                continue
            try:
                ctype, _ = mimetypes.guess_type(fname)
                maintype, subtype = (ctype.split("/", 1) if ctype
                                     else ("application", "octet-stream"))
                em.add_attachment(data, maintype=maintype, subtype=subtype,
                                  filename=fname)
            except Exception as e:
                log.warning("Archive: could not attach %s: %s", fname, e)
        raw = em.as_bytes()
    try:
        os.makedirs(os.path.dirname(path), exist_ok=True)
        # Write to a temporary name and rename, so a crash mid-write cannot
        # leave a half-message that later looks "already archived".
        tmp = path + ".part"
        with open(tmp, "wb") as f:
            f.write(raw)
        os.replace(tmp, path)
        return path
    except Exception as e:
        log.warning("Archive: could not write %s: %s", path, e)
        return ""


def _archive_run(cfg: dict, messages: list) -> int:
    """Archive a batch. Returns how many were NEW. Safe to call on every
    fetch: already-archived messages cost one os.path.exists() each."""
    if not messages:
        return 0
    written = 0
    for msg in messages:
        if msg.get("_note_path"):
            continue                  # notes are already files you own
        if _archive_message(cfg, msg):
            written += 1
    if written:
        log.info("Archive: wrote %d new message(s)", written)
    return written


def _archive_stats(cfg: dict) -> dict:
    """{"files": n, "bytes": n, "path": ...} for the dialog."""
    base = _archive_dir(cfg)
    files, total = 0, 0
    try:
        for root_, _dirs, names in os.walk(base):
            for n in names:
                if n.lower().endswith(".eml"):
                    files += 1
                    try:
                        total += os.path.getsize(os.path.join(root_, n))
                    except OSError:
                        pass
    except Exception as e:
        log.warning("Could not measure the archive: %s", e)
    return {"files": files, "bytes": total, "path": base}


# WHY THERE IS NO "DELETE FROM THE SERVER AFTER N DAYS"
# ----------------------------------------------------
# Because automating deletion is how mail gets lost for good, and because on
# Gmail specifically it is sharper than it looks:
#
#   • Gmail stores ONE message with labels (see DEL 04g). A rule that trashes
#     "everything in Sent older than a year" would also strip those messages
#     out of the Inbox, out of All Mail and out of every label they carry —
#     including the mail you sent yourself.
#   • A scheduled deletion runs when you are not watching. By the time you
#     notice it did the wrong thing, the 30-day Trash window may have passed.
#   • Retention rules are written once, when you are confident, and then keep
#     running for years across mail you never imagined when you wrote them.
#
# So: keep your own copies (that is what this section is for), and delete on
# the server deliberately, by hand, seeing exactly what goes. If Phase 2 is
# ever unlocked, deletion stays a manual act with a confirmation that names
# what disappears — never a timer.


# ******************************************************************************
# DEL 04i — PHASE 2: SERVER-SIDE DELETE  (opt-in, move to Trash, never erase)
# ******************************************************************************
#
# This is the ONLY code in the program that changes anything on Gmail. It
# exists because deleting mail from your own mail client is ordinary, expected
# behaviour — "delete here, delete at Google too", the way Thunderbird does
# it. Everything else in F(re)email remains read-only.
#
# THE FOUR RULES IT FOLLOWS
# -------------------------
# 1. OFF BY DEFAULT. Nothing here runs unless "allow server changes" has been
#    switched on by hand (Tools → Server changes). A fresh install, or a
#    restored backup, cannot delete anything.
# 2. TRASH FIRST. A message deleted from a normal folder is MOVED to
#    [Gmail]/Trash, where Gmail keeps it for 30 days and you can put it back
#    from any client. The ONE exception (DEL 04s, added at Issu's request) is
#    deleting a message that is ALREADY in the Trash: that is a real permanent
#    expunge — but only of that single UID, and only after a hidden local copy
#    is saved so it can still be read, forwarded, or restored. Never a bare
#    EXPUNGE; the Trash is never blanket-emptied.
# 3. IT SAYS WHAT IT WILL DO FIRST. Gmail stores ONE message with labels, so
#    a message can sit in Inbox and Sent and three labels at once — and
#    trashing it removes it from ALL of them. The confirmation lists them by
#    name, and a message you sent to yourself gets a louder warning still.
# 4. NEVER AUTOMATIC. There is no rule, timer or filter action anywhere in
#    this program that can reach this code. A human clicks Delete, reads what
#    it says, and confirms. Every time.
#
# WHY MOVE AND NOT "STORE \Deleted + EXPUNGE"
# -------------------------------------------
# A plain EXPUNGE removes every message in the mailbox that carries the
# \Deleted flag — including ones flagged by another client, days ago, that
# you never meant to touch. UID MOVE (RFC 6851, which Gmail supports) affects
# exactly the message named and nothing else. The fallback path below uses
# UID EXPUNGE (RFC 4315), which is likewise limited to the UIDs given; if
# neither extension is available the message is left copied-and-flagged and
# that is reported honestly rather than reaching for the blunt instrument.


def _imap_capabilities(imap) -> set:
    try:
        typ, data = imap.capability()
        if typ != "OK" or not data:
            return set()
        return set(data[0].decode("ascii", "replace").upper().split())
    except Exception as e:
        log.warning("Could not read IMAP capabilities: %s", e)
        return set()


def _imap_trash_message(email_addr, password, folder, uid) -> str:
    """Move ONE message to the account's Trash. Returns "" on success, or a
    human-readable reason on failure. Raises only on connection/login errors.

    The mailbox is opened WRITABLE here — the single place in this program
    where that happens."""
    if not uid:
        return "This message has no server id (it may be demo or local data)."
    imap = _imap_connect(email_addr, password)
    try:
        mapping = _discover_mailboxes(imap)
        source  = mapping.get(folder, folder)
        trash   = mapping.get("Trash", "[Gmail]/Trash")

        if source == trash:
            # Already in the Trash. Deleting it again would mean erasing it
            # for good, which this code does not do.
            return ("That message is already in the Trash. Emptying the "
                    "Trash is done in Gmail itself — F(re)email never "
                    "erases mail permanently.")

        typ, _ = imap.select(f'"{source}"', readonly=False)
        if typ != "OK":
            return f"Could not open {source} for writing."

        caps = _imap_capabilities(imap)
        uid_s = str(uid)

        # Preferred: UID MOVE — atomic, and touches only this message.
        if "MOVE" in caps:
            typ, resp = imap.uid("MOVE", uid_s, f'"{trash}"')
            if typ == "OK":
                log.info("Trashed (MOVE) uid=%s %s/%s → %s",
                         uid_s, email_addr, source, trash)
                return ""
            log.warning("UID MOVE failed (%s), falling back: %s", typ, resp)

        # Fallback: COPY, flag, then expunge JUST this uid.
        typ, resp = imap.uid("COPY", uid_s, f'"{trash}"')
        if typ != "OK":
            return f"Could not copy the message to the Trash: {resp}"
        typ, resp = imap.uid("STORE", uid_s, "+FLAGS", "(\\Deleted)")
        if typ != "OK":
            return ("The message was copied to the Trash but the original "
                    "could not be flagged — you may now have two copies.")
        if "UIDPLUS" in caps:
            typ, resp = imap.uid("EXPUNGE", uid_s)
            if typ != "OK":
                return ("Copied to the Trash, but removing the original "
                        f"failed: {resp}")
            log.info("Trashed (COPY+UID EXPUNGE) uid=%s %s/%s",
                     uid_s, email_addr, source)
            return ""
        # No UIDPLUS: refuse to run a blanket EXPUNGE.
        log.info("Trashed by COPY only (no UIDPLUS) uid=%s %s/%s",
                 uid_s, email_addr, source)
        return ("The message is now in the Trash, but your server does not "
                "support removing single messages, so the original is only "
                "marked as deleted. It will disappear when the mailbox is "
                "next compacted. Nothing was erased.")
    finally:
        try:
            imap.logout()
        except Exception:
            pass


def _imap_move_message(email_addr, password, folder, uid,
                       target_mailbox) -> str:
    """Move ONE message to a named mailbox. Returns "" on success or a reason.

    The same careful path as trashing (UID MOVE, falling back to COPY +
    \\Deleted + UID EXPUNGE, never a bare EXPUNGE) — but to a folder you
    chose, which is what "archive this out of my inbox" means. Creates the
    mailbox if it does not exist yet, so a first use of "Minbox" works."""
    if not uid:
        return "This message has no server id."
    if not target_mailbox:
        return "No destination folder is set."
    imap = _imap_connect(email_addr, password)
    try:
        mapping = _discover_mailboxes(imap)
        # BOTH ends go through the resolver: the name in a filter rule or in
        # the folder picker is the DECODED one a human reads, and IMAP only
        # answers to the raw modified-UTF-7 name (see _imap_utf7_encode for
        # what this was breaking). create=True so a first move into a label
        # that does not exist yet still works.
        source = _resolve_mailbox(imap, folder, mapping)
        target = _resolve_mailbox(imap, target_mailbox, mapping, create=True)
        log.info("move: %s uid=%s  %r→%r  (raw %r→%r)",
                 email_addr, uid, folder, target_mailbox, source, target)
        if not target:
            return "No destination folder is set."
        if source == target:
            return ""                      # already where it should be
        typ, _ = imap.select(_mb_arg(source), readonly=False)
        if typ != "OK":
            return f"Could not open {folder} for writing."
        caps = _imap_capabilities(imap)
        uid_s = str(uid)
        if "MOVE" in caps:
            typ, resp = imap.uid("MOVE", uid_s, _mb_arg(target))
            if typ == "OK":
                log.info("Moved uid=%s %s → %s", uid_s, source, target)
                return ""
            log.warning("UID MOVE failed (%s): %s", typ, resp)
        typ, resp = imap.uid("COPY", uid_s, _mb_arg(target))
        if typ != "OK":
            return f"Could not copy to {target_mailbox}: {resp}"
        imap.uid("STORE", uid_s, "+FLAGS", "(\\Deleted)")
        if "UIDPLUS" in caps:
            imap.uid("EXPUNGE", uid_s)
            log.info("Moved uid=%s %s → %s (copy+expunge)", uid_s, source, target)
            return ""
        return (f"Copied to {target_mailbox}, but the original could only be "
                f"marked as deleted — your server cannot remove single "
                f"messages.")
    finally:
        try:
            imap.logout()
        except Exception:
            pass


def _imap_move_uids(email_addr, password, folder, uids, target_mailbox,
                    chunk=100) -> tuple:
    """Move MANY messages of one folder to one target over ONE connection.

    Returns (moved, problems). The batched twin of _imap_move_message, and for
    the same reason _imap_trash_uids exists: the filter engine used to call the
    single-message version per message, so every message meant a fresh TLS
    handshake, a fresh LOGIN, a LIST and a SELECT. Issu's log of 2026-08-03
    shows 1–5 seconds PER MESSAGE and about ninety seconds to file twenty of
    them, most of it spent logging in over and over — and Gmail starts refusing
    connections long before a real junk clean-out finishes."""
    uids = [str(u) for u in uids if u]
    if not uids:
        return 0, []
    if not target_mailbox:
        return 0, ["No destination folder is set."]
    problems, moved = [], 0
    imap = _imap_connect(email_addr, password)
    try:
        mapping = _discover_mailboxes(imap)
        source = _resolve_mailbox(imap, folder, mapping)
        target = _resolve_mailbox(imap, target_mailbox, mapping, create=True)
        log.info("move x%d: %s  %r→%r  (raw %r→%r)",
                 len(uids), email_addr, folder, target_mailbox, source, target)
        if not target:
            return 0, ["No destination folder is set."]
        if source == target:
            return len(uids), []               # already where they should be
        typ, _ = imap.select(_mb_arg(source), readonly=False)
        if typ != "OK":
            return 0, [f"Could not open {folder} for writing."]
        caps = _imap_capabilities(imap)
        for i in range(0, len(uids), chunk):
            part  = uids[i:i + chunk]
            uid_s = ",".join(part)
            if "MOVE" in caps:
                typ, resp = imap.uid("MOVE", uid_s, _mb_arg(target))
                if typ == "OK":
                    moved += len(part)
                    log.info("Moved %d message(s) %s/%s → %s",
                             len(part), email_addr, source, target)
                    continue
                log.warning("UID MOVE failed (%s), falling back: %s", typ, resp)
            typ, resp = imap.uid("COPY", uid_s, _mb_arg(target))
            if typ != "OK":
                problems.append(f"{folder}: could not copy to "
                                f"{target_mailbox}: {resp}")
                continue
            typ, resp = imap.uid("STORE", uid_s, "+FLAGS", "(\\Deleted)")
            if typ != "OK":
                problems.append(f"{folder}: copied to {target_mailbox} but the "
                                f"originals could not be flagged — you may now "
                                f"have two copies.")
                continue
            if "UIDPLUS" in caps:
                typ, resp = imap.uid("EXPUNGE", uid_s)
                if typ != "OK":
                    problems.append(f"{folder}: copied to {target_mailbox}, but "
                                    f"removing the originals failed: {resp}")
                    continue
                moved += len(part)
                log.info("Moved %d message(s) (COPY+UID EXPUNGE) %s/%s → %s",
                         len(part), email_addr, source, target)
            else:
                moved += len(part)
                problems.append(
                    f"{folder}: copied to {target_mailbox}, but the originals "
                    f"could only be marked as deleted — your server cannot "
                    f"remove single messages.")
    finally:
        try:
            imap.logout()
        except Exception:
            pass
    return moved, problems


def _imap_folder_stats(email_addr, password, folder) -> dict:
    """How many messages (and unread) a folder holds, plus whether it has
    sub-folders. Read-only: STATUS + LIST, nothing is opened for writing.

    Returns {"exists": bool, "messages": int, "unseen": int,
             "children": int, "raw": <raw mailbox name>}."""
    out = {"exists": False, "messages": 0, "unseen": 0, "children": 0,
           "raw": ""}
    imap = _imap_connect(email_addr, password)
    try:
        mapping = _discover_mailboxes(imap)
        raw = _resolve_mailbox(imap, folder, mapping)
        out["raw"] = raw
        if not raw:
            return out
        typ, data = imap.status(_mb_arg(raw).decode("ascii"),
                                "(MESSAGES UNSEEN)")
        if typ == "OK" and data and data[0]:
            out["exists"] = True
            m = _re.search(rb"MESSAGES\s+(\d+)", data[0])
            u = _re.search(rb"UNSEEN\s+(\d+)", data[0])
            out["messages"] = int(m.group(1)) if m else 0
            out["unseen"] = int(u.group(1)) if u else 0
        # Sub-folders: IMAP will not DELETE a parent that still has children,
        # so it is worth knowing BEFORE offering to.
        try:
            typ, kids = imap.list(f'"{raw}"', '"*"')
            if typ == "OK":
                out["children"] = len([k for k in (kids or []) if k])
        except Exception:
            pass
        return out
    except Exception as e:
        log.warning("Folder stats failed for %s/%s: %s", email_addr, folder, e)
        return out
    finally:
        try:
            imap.logout()
        except Exception:
            pass


def _imap_delete_folder(email_addr, password, folder) -> str:
    """Delete a folder / label. Returns "" on success or a reason.

    On Gmail a folder IS a label, so DELETE removes the label — the messages
    that carried it are NOT deleted, they stay in All Mail. That is why this is
    far less dangerous than the word "delete" suggests, and why an EMPTY label
    can be removed without asking at all (Issu 2026-08-03).

    Never touches INBOX or any of the standard mailboxes."""
    imap = _imap_connect(email_addr, password)
    try:
        mapping = _discover_mailboxes(imap)
        raw = _resolve_mailbox(imap, folder, mapping)
        if not raw:
            return "That folder no longer exists on the server."
        if raw.upper() == "INBOX" or raw in mapping.values():
            return ("That is one of Gmail's own folders (Inbox, Sent, Trash…) "
                    "and cannot be deleted.")
        typ, resp = imap.delete(_mb_arg(raw))
        if typ != "OK":
            return f"The server refused to delete it: {resp}"
        log.info("Deleted folder %r on %s", raw, email_addr)
        return ""
    finally:
        try:
            imap.logout()
        except Exception:
            pass


def _imap_create_folders(email_addr, password, paths) -> tuple:
    """Create folders/labels. Returns (made, skipped, problems).

    Each entry of `paths` is a DECODED path such as
    "INBOX/Temporär/0---Frakt & Kvitto/2026-01"; it is encoded to modified
    UTF-7 and created. A name that already exists is SKIPPED, never touched —
    Issu's explicit requirement, "att inte skriva över om redan existerar".
    Creating a label cannot affect any message: on Gmail a folder is a label,
    and a brand-new label has nothing in it.

    One connection for the whole list, so building a year of month folders is
    one login rather than twelve."""
    made, skipped, problems = [], [], []
    imap = _imap_connect(email_addr, password)
    try:
        mapping = _discover_mailboxes(imap)
        # Ask once what already exists, then test against that.
        existing = set()
        try:
            typ, data = imap.list()
            if typ == "OK":
                for raw in data or []:
                    if not raw:
                        continue
                    if isinstance(raw, tuple):
                        raw = raw[0]
                    if isinstance(raw, str):
                        raw = raw.encode("utf-8", "replace")
                    m = _LIST_RE.match(raw)
                    if m:
                        existing.add(m.group("name").decode("utf-8", "replace")
                                     .strip('"').lower())
        except Exception as e:
            log.warning("Create folders: LIST failed: %s", e)
        for path in paths:
            path = (path or "").strip().strip("/")
            if not path:
                continue
            try:
                raw = _imap_utf7_encode(path)
                if raw.lower() in existing:
                    skipped.append(path)
                    continue
                typ, resp = imap.create(_mb_arg(raw))
                if typ == "OK":
                    made.append(path)
                    existing.add(raw.lower())
                    log.info("Created folder %r on %s", raw, email_addr)
                else:
                    # Gmail answers NO for "already exists" too, which is not
                    # a failure worth showing anyone.
                    txt = str(resp).lower()
                    if "exist" in txt:
                        skipped.append(path)
                    else:
                        problems.append(f"{path}: {resp}")
            except Exception as e:
                problems.append(f"{path}: {e}")
    finally:
        try:
            imap.logout()
        except Exception:
            pass
    return made, skipped, problems


# ── Date folders: names, and which one a message belongs in ───────────────────
#
# Issu 2026-08-08, about his 0---Frakt & Kvitto folder: he already keeps 01,
# 02 … under it by month, and wants the program to make them — with the option
# of "2026-01" style names instead, because a bare "01" stops making sense the
# moment a second year's worth arrives.
_DATE_FOLDER_STYLES = {
    "month":      ("01, 02, 03 …",
                   "Just the month number. Short, and what you have now — but "
                   "next January's 01 sits in the same place as this one."),
    "year_month": ("2026-01, 2026-02 …",
                   "Year first, so folders sort correctly for ever and two "
                   "Januaries never collide. Recommended."),
    "year/month": ("2026 / 01, 02 …",
                   "A folder per year, with the months inside it."),
}


def _date_folder_name(style: str, year: int, month: int) -> str:
    """The sub-path (under the parent) for one month, in the chosen style."""
    if style == "month":
        return f"{month:02d}"
    if style == "year/month":
        return f"{year:04d}/{month:02d}"
    return f"{year:04d}-{month:02d}"


def _date_folders_for(style: str, start_year: int, start_month: int,
                      count: int) -> list:
    """`count` consecutive month names starting at the given month."""
    out, y, m = [], start_year, start_month
    for _ in range(max(0, count)):
        out.append(_date_folder_name(style, y, m))
        m += 1
        if m > 12:
            m, y = 1, y + 1
    return out


def _month_folder_for_message(msg: dict, style: str) -> str:
    """Which month folder does this message belong in, judged by ITS OWN date?

    The email's Date: header, not today — a receipt that arrives on the 1st for
    something bought on the 31st belongs in the month it happened."""
    iso = (msg or {}).get("_dt", "") or ""
    if len(iso) < 7:
        return ""
    try:
        y, m = int(iso[:4]), int(iso[5:7])
    except ValueError:
        return ""
    if not (1 <= m <= 12):
        return ""
    return _date_folder_name(style, y, m)


def _imap_mark_folder_read(email_addr, password, folder, chunk=500) -> tuple:
    """Mark EVERY unread message in one folder as read on the server.

    Returns (how many, problems). Additive only — this adds \\Seen and never
    removes it, the same one-directional rule as _imap_mark_seen."""
    imap = _imap_connect(email_addr, password)
    try:
        mapping = _discover_mailboxes(imap)
        raw = _resolve_mailbox(imap, folder, mapping)
        typ, _ = imap.select(_mb_arg(raw), readonly=False)
        if typ != "OK":
            return 0, [f"Could not open {folder} for writing."]
        typ, data = imap.uid("SEARCH", None, "UNSEEN")
        if typ != "OK":
            return 0, [f"Could not list the unread mail in {folder}."]
        uids = [u.decode() for u in (data[0].split() if data and data[0] else [])]
        if not uids:
            return 0, []
        done, problems = 0, []
        for i in range(0, len(uids), chunk):
            part = uids[i:i + chunk]
            typ, resp = imap.uid("STORE", ",".join(part), "+FLAGS", "(\\Seen)")
            if typ != "OK":
                problems.append(f"{folder}: server refused to mark read: {resp}")
                continue
            done += len(part)
        log.info("Marked %d message(s) read in %s/%s", done, email_addr, raw)
        return done, problems
    finally:
        try:
            imap.logout()
        except Exception:
            pass


def _imap_trash_count(email_addr, password) -> int:
    """How many messages are in this account's Trash. Read-only (STATUS)."""
    imap = _imap_connect(email_addr, password)
    try:
        mapping = _discover_mailboxes(imap)
        trash   = _resolve_mailbox(imap, "Trash", mapping)
        typ, data = imap.status(_mb_arg(trash).decode("ascii"), "(MESSAGES)")
        if typ != "OK" or not data or not data[0]:
            return 0
        m = _re.search(rb"MESSAGES\s+(\d+)", data[0])
        return int(m.group(1)) if m else 0
    except Exception as e:
        log.warning("Trash count failed for %s: %s", email_addr, e)
        return 0
    finally:
        try:
            imap.logout()
        except Exception:
            pass


def _imap_empty_trash(email_addr, password, chunk=200) -> tuple:
    """EMPTY THE TRASH: erase every message in it, for good.

    Returns (erased, problems). This is the most destructive thing in the
    program and the only place a whole mailbox is cleared, so read the rules it
    keeps to:

      • It only ever opens the TRASH. Nothing else can be reached from here.
      • It flags exactly the uids it found and expunges THOSE uids (UID
        EXPUNGE, UIDPLUS) — never a bare EXPUNGE, which would also erase
        messages another client happened to flag while we were working.
      • A server without UIDPLUS is REFUSED rather than served with a bare
        EXPUNGE. Being told "your server cannot do this safely" is fine;
        quietly erasing someone else's flagged mail is not.
      • Gmail does not put this back. The caller must have asked twice.
    """
    erased, problems = 0, []
    imap = _imap_connect(email_addr, password)
    try:
        mapping = _discover_mailboxes(imap)
        trash   = _resolve_mailbox(imap, "Trash", mapping)
        typ, _ = imap.select(_mb_arg(trash), readonly=False)
        if typ != "OK":
            return 0, [f"Could not open the Trash of {email_addr}."]
        caps = _imap_capabilities(imap)
        if "UIDPLUS" not in caps:
            return 0, [f"{email_addr}: this server cannot erase single "
                       f"messages safely (no UIDPLUS), so the Trash was left "
                       f"alone. Empty it in Gmail itself."]
        typ, data = imap.uid("SEARCH", None, "ALL")
        if typ != "OK":
            return 0, [f"{email_addr}: could not list the Trash."]
        uids = [u.decode() for u in (data[0].split() if data and data[0] else [])]
        if not uids:
            return 0, []
        log.info("EMPTY TRASH %s: %d message(s) to erase", email_addr, len(uids))
        for i in range(0, len(uids), chunk):
            part  = uids[i:i + chunk]
            uid_s = ",".join(part)
            typ, resp = imap.uid("STORE", uid_s, "+FLAGS", "(\\Deleted)")
            if typ != "OK":
                problems.append(f"{email_addr}: could not flag part of the "
                                f"Trash: {resp}")
                continue
            typ, resp = imap.uid("EXPUNGE", uid_s)
            if typ != "OK":
                problems.append(f"{email_addr}: could not erase part of the "
                                f"Trash: {resp}")
                continue
            erased += len(part)
            log.info("EMPTY TRASH %s: erased %d (%d/%d)",
                     email_addr, len(part), i + len(part), len(uids))
    finally:
        try:
            imap.logout()
        except Exception:
            pass
    return erased, problems


def _imap_mark_seen(email_addr, password, folder, uids) -> str:
    """ADD the \\Seen flag to messages on the server. Returns "" on success or
    a reason string.

    Deliberately one-directional: this program only ever ADDS \\Seen (marks
    read), it NEVER removes it. That is the whole point — a message you read in
    Freemail stops being "new" on your phone/Thunderbird too, but "mark unread"
    in Freemail is a LOCAL view and can never make the Gmail app ping again.
    This is the least destructive server write there is (no message moves, none
    is deleted); it still only runs when Server changes is switched on."""
    uids = [str(u) for u in uids if u]
    if not uids:
        return ""
    imap = _imap_connect(email_addr, password)
    try:
        mapping = _discover_mailboxes(imap)
        mailbox = mapping.get(folder, folder)
        typ, _ = imap.select(f'"{mailbox}"', readonly=False)
        if typ != "OK":
            return f"Could not open {mailbox} for writing."
        typ, resp = imap.uid("STORE", ",".join(uids), "+FLAGS", "(\\Seen)")
        if typ != "OK":
            return f"Server refused to mark read: {resp}"
        return ""
    finally:
        try:
            imap.logout()
        except Exception:
            pass


def _imap_star_message(email_addr, password, folder, uids) -> str:
    """ADD the \\Flagged flag (Gmail's star) to messages on the server. Returns
    "" on success or a reason string. Additive only — never removes the star,
    so a local un-star can't reach back to Gmail. Runs only when Server changes
    is on."""
    uids = [str(u) for u in uids if u]
    if not uids:
        return ""
    imap = _imap_connect(email_addr, password)
    try:
        mapping = _discover_mailboxes(imap)
        mailbox = mapping.get(folder, folder)
        typ, _ = imap.select(f'"{mailbox}"', readonly=False)
        if typ != "OK":
            return f"Could not open {mailbox} for writing."
        typ, resp = imap.uid("STORE", ",".join(uids), "+FLAGS", "(\\Flagged)")
        if typ != "OK":
            return f"Server refused to star: {resp}"
        return ""
    finally:
        try:
            imap.logout()
        except Exception:
            pass


# ******************************************************************************
# DEL 04s — DELETED ARCHIVE  (permanent Trash delete + hidden 30-day copy)
# ******************************************************************************
#
# Deleting a normal message moves it to the Gmail Trash (recoverable 30 days).
# Deleting one that is ALREADY in the Trash means "get rid of it for good" — a
# real server EXPUNGE. To make that safe, we first write a hidden local copy
# (Helpfiles/Deleted) that survives for a configurable number of days, so a
# permanent delete you regret can still be read, forwarded, or uploaded back
# to Gmail (IMAP APPEND). The "Deleted" virtual folder shows this archive.

def _imap_expunge_message(email_addr, password, folder, uid) -> str:
    """Permanently remove ONE message from a mailbox. STORE \\Deleted then
    UID EXPUNGE (RFC 4315), limited to that single UID — NEVER a bare EXPUNGE,
    which would also erase messages another client flagged. Returns "" on
    success or a reason string."""
    if not uid:
        return "This message has no server id."
    imap = _imap_connect(email_addr, password)
    try:
        mapping = _discover_mailboxes(imap)
        mailbox = mapping.get(folder, folder)
        typ, _ = imap.select(f'"{mailbox}"', readonly=False)
        if typ != "OK":
            return f"Could not open {mailbox} for writing."
        caps  = _imap_capabilities(imap)
        uid_s = str(uid)
        imap.uid("STORE", uid_s, "+FLAGS", "(\\Deleted)")
        if "UIDPLUS" in caps:
            typ, resp = imap.uid("EXPUNGE", uid_s)
            if typ == "OK":
                log.info("Expunged uid=%s from %s", uid_s, mailbox)
                return ""
            return f"Server refused to expunge: {resp}"
        return ("Marked as deleted, but your server cannot remove a single "
                "message safely (no UIDPLUS), so it was left in place.")
    finally:
        try:
            imap.logout()
        except Exception:
            pass


def _imap_purge_hollow_copy(email_addr, password, logical_folder,
                            message_id) -> tuple:
    """Remove the EMPTY copies of one Message-ID from the Trash or Spam of an
    account, so the real message can be delivered.

    Returns (removed, certain). `certain` is False when the account could not
    be asked at all — a timeout, a refused EXPUNGE. It matters because "I
    removed nothing" and "I could not look" must not read the same: only the
    first one is safe to deliver on top of (Issu 2026-08-18, after a timed-out
    purge logged "had 0 empty copies — removed" and delivered anyway).

    Why this exists (Issu 2026-08-18). Gmail's IMAP APPEND does not always
    create a new message: hand it a Message-ID the account already knows and
    it may simply add the label to the copy that is already there. When that
    copy is one of the body-less shells the old cross-account move left
    behind, "delivering" the real receipt would have relabelled the empty one
    and the contents would still be missing. So the shell goes first.

    Three separate refusals keep this safe, because this is the one place in
    the program that erases mail without being asked:

      • only Trash and Spam — never a folder you file things in;
      • only after re-reading the body on THIS connection and finding it
        genuinely empty, so an intact message can never be caught;
      • only STORE \\Deleted + UID EXPUNGE of those exact UIDs (RFC 4315),
        never a bare EXPUNGE.

    Nothing of value can be lost here: an empty envelope holds nothing, and
    the message it was supposed to carry is about to be delivered from the
    account that still has it whole."""
    mid = _hdr_safe(message_id or "")
    if not mid or not _is_discard_folder(logical_folder):
        return 0, True
    gone = 0
    imap = _imap_connect(email_addr, password)
    try:
        mapping = _discover_mailboxes(imap)
        mailbox = mapping.get(logical_folder, logical_folder)
        typ, _ = imap.select(_mb_arg(mailbox), readonly=False)
        if typ != "OK":
            log.warning("Hollow-copy purge: could not open %s/%s for writing",
                        email_addr, mailbox)
            return 0, False
        try:
            typ, data = imap.uid("SEARCH", "X-GM-RAW",
                                 f'rfc822msgid:{mid.strip("<>")}')
        except Exception:
            typ, data = imap.uid("SEARCH", None, "HEADER", "Message-ID",
                                 f'"{mid}"')
        if typ != "OK" or not data or not data[0]:
            return 0, True          # asked, and there is nothing there
        caps  = _imap_capabilities(imap)
        empty = []
        for u in data[0].split():
            uid_s = u.decode()
            t2, f2 = imap.uid("FETCH", uid_s, "(BODY.PEEK[TEXT]<0.256>)")
            if t2 != "OK":
                continue                      # unsure → leave it alone
            it = next((x for x in f2 if isinstance(x, tuple)), None)
            if it and len((it[1] or b"").strip()) >= 8:
                continue                      # it has a body — not ours to touch
            empty.append(uid_s)
        if not empty:
            return 0, True          # asked, and none of them is hollow
        if "UIDPLUS" not in caps:
            log.warning("Hollow-copy purge: %s cannot expunge single messages "
                        "safely (no UIDPLUS) — %d empty copy/copies left in %s",
                        email_addr, len(empty), mailbox)
            return 0, False
        uid_set = ",".join(empty)
        imap.uid("STORE", uid_set, "+FLAGS", "(\\Deleted)")
        typ, resp = imap.uid("EXPUNGE", uid_set)
        if typ != "OK":
            log.warning("Hollow-copy purge: server refused to expunge %s "
                        "from %s: %s", uid_set, mailbox, resp)
            return 0, False
        gone = len(empty)
        log.info("Hollow-copy purge: removed %d body-less copy/copies of %s "
                 "from %s/%s so the real message can be delivered",
                 gone, mid[:60], email_addr, mailbox)
        return gone, True
    except Exception as e:
        log.warning("Hollow-copy purge failed for %s: %s", email_addr, e)
        return gone, False
    finally:
        try:
            imap.logout()
        except Exception:
            pass


def _imap_append_message(email_addr, password, target_folder, raw_bytes,
                         mark_seen=False) -> str:
    """Upload a raw .eml back onto the server (RESTORE). Additive only — nothing
    is moved or removed. Returns "" on success or a reason string."""
    if not raw_bytes:
        return "No message content to restore."
    imap = _imap_connect(email_addr, password)
    try:
        mapping = _discover_mailboxes(imap)
        # Same raw-name resolution as the move path — a cross-account move
        # lands here, and its target is a label the user picked by its decoded
        # name (see _imap_utf7_encode).
        mailbox = _resolve_mailbox(imap, target_folder, mapping, create=True)
        flags = r"(\Seen)" if mark_seen else ""
        typ, resp = imap.append(_mb_arg(mailbox).decode("ascii"), flags, None,
                                raw_bytes)
        if typ != "OK":
            return f"Server refused the upload: {resp}"
        log.info("Appended a restored message to %s", mailbox)
        return ""
    finally:
        try:
            imap.logout()
        except Exception:
            pass


def _imap_append_full(email_addr, password, target_folder, raw_bytes,
                      flags=None, internaldate=None, imap=None) -> str:
    """Upload a raw .eml back onto the server, KEEPING its flags and date.

    The plain _imap_append_message above is enough for restoring one deleted
    message. A backup restore needs two more things or the result is subtly
    wrong in a way you only notice later:

      • INTERNALDATE — without it every restored message is dated "now", so a
        year of mail all lands on today and every sort, every "oldest first",
        every date search is ruined.
      • FLAGS — \\Seen above all. Restore 4 000 messages without it and the
        whole lot comes back unread, on your phone too.

    `imap` lets a caller reuse ONE connection for a whole restore instead of
    logging in per message. Returns "" on success, else a reason."""
    if not raw_bytes:
        return "No message content."
    own = imap is None
    if own:
        imap = _imap_connect(email_addr, password)
    try:
        mapping = _discover_mailboxes(imap)
        mailbox = _resolve_mailbox(imap, target_folder, mapping, create=True)
        keep = [f for f in (flags or [])
                if f.lower() in ("\\seen", "\\flagged", "\\answered",
                                 "\\draft")]
        flag_s = f"({' '.join(keep)})" if keep else ""
        date_s = None
        if internaldate:
            try:
                dt = _parse_iso(internaldate) if isinstance(internaldate, str) \
                    else internaldate
                if dt is not None:
                    date_s = imaplib.Time2Internaldate(dt.timestamp())
            except Exception:
                date_s = None
        typ, resp = imap.append(_mb_arg(mailbox).decode("ascii"), flag_s,
                                date_s, raw_bytes)
        if typ != "OK":
            return f"Server refused the upload: {resp}"
        return ""
    except Exception as e:
        return str(e)
    finally:
        if own:
            try:
                imap.logout()
            except Exception:
                pass


# ── Export / restore a mailbox to ONE file (Issu 2026-08-08) ──────────────────
#
# His question, and it is the right one to ask: "kan jag spara mail så att jag
# kan exportera en fil… sedan importera och oavsett vad jag gjort i Gmail under
# tiden, återställa, och Gmail krånglar inte?"
#
# What is genuinely possible, and what is not, decided the design:
#
#   ✔ The message itself restores EXACTLY. An .eml is the original bytes; put
#     them back and it is the same message, headers, attachments and all.
#   ✔ Its date and its read/starred state survive — but only because they are
#     saved beside it and handed to APPEND (see _imap_append_full). Nothing in
#     the .eml itself carries them.
#   ✔ Labels survive, because the manifest records them and the restore puts
#     the message back into each one.
#   ⚠ A message that is STILL on Gmail must not be uploaded again. Gmail's own
#     de-duplication is not something to rely on, so the restore LOOKS FIRST
#     (by Message-ID) and skips what is already there. That is the whole of
#     "Gmail krånglar inte": nothing is ever duplicated, and a restore you run
#     twice by mistake changes nothing the second time.
#   ✗ What CANNOT be restored is Gmail's own idea of a conversation: thread
#     ids are assigned by Gmail, so a restored message may sit in a thread of
#     its own. The mail is all there; the grouping may differ. Said out loud
#     in the dialog rather than discovered later.
#
# The file is a plain .zip: manifest.json plus one .eml per message. Openable
# by anything, restorable by this program, and readable by hand in fifty years.
_EXPORT_FORMAT = 1


def _export_messages_zip(path, entries, on_progress=None, stop=None) -> dict:
    """Write messages to one .zip. `entries` are message dicts that carry
    `_raw` (or whose raw bytes can be read from the cache).

    Returns {"written", "skipped", "path", "bytes"}."""
    written = skipped = 0
    manifest = {"format": _EXPORT_FORMAT,
                "created": _now_iso(),
                "program": "F(re)email",
                "messages": []}
    with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as z:
        for i, m in enumerate(entries):
            if stop is not None and stop():
                break
            raw = m.get("_raw")
            if not raw:
                raw = _cached_raw_for(m)
            if not raw:
                skipped += 1
                continue
            name = f"msgs/{i:06d}.eml"
            try:
                z.writestr(name, raw)
            except Exception as e:
                log.warning("export: could not write %s: %s", name, e)
                skipped += 1
                continue
            manifest["messages"].append({
                "file":       name,
                "message_id": (m.get("_message_id") or "").strip(),
                "account":    m.get("account_email", ""),
                "folder":     m.get("_folder", ""),
                "labels":     list(m.get("_labels") or []),
                "flags":      ([r"\Seen"] if not m.get("unread") else [])
                              + ([r"\Flagged"] if m.get("starred") else []),
                "date":       m.get("_dt", ""),
                "subject":    m.get("subject", ""),
                "from":       m.get("from", ""),
            })
            written += 1
            if on_progress is not None and (written % 25 == 0):
                on_progress(written, len(entries))
        z.writestr("manifest.json",
                   json.dumps(manifest, ensure_ascii=False, indent=1))
    size = os.path.getsize(path) if os.path.isfile(path) else 0
    log.info("Export: %d message(s) written, %d skipped, %.1f MB → %s",
             written, skipped, size / 1024 / 1024, path)
    return {"written": written, "skipped": skipped, "path": path,
            "bytes": size}


def _cached_raw_for(msg) -> bytes:
    """The raw bytes of a message from the on-disk cache, or b''."""
    try:
        d = _cache_folder_dir(msg.get("account_email", ""),
                              msg.get("_folder", ""))
        p = os.path.join(d, f"{msg.get('uid','')}.eml")
        if _cached_body_ok(p):
            with open(p, "rb") as f:
                return f.read()
    except Exception:
        pass
    return b""


def _restore_messages_zip(path, target_account, password, only_missing=True,
                          folder_override=None, on_progress=None, stop=None,
                          dry_run=False) -> dict:
    """Put an export back onto the server.

    `only_missing=True` (the default, and the point of the whole thing) asks
    the server whether each Message-ID is already there and skips it if so. A
    restore is then SAFE TO REPEAT: run it twice, or restore a year-old backup
    over a mailbox you have been using since, and the only thing that happens
    is that what is genuinely missing comes back. Nothing is duplicated and
    nothing already on Gmail is touched.

    `dry_run=True` does the looking and none of the uploading, so the dialog
    can say exactly what WOULD happen before anything does.

    Returns {"restored", "already_there", "failed", "problems", "total"}."""
    man = _read_export_manifest(path)
    msgs = man.get("messages") or []
    out = {"restored": 0, "already_there": 0, "failed": 0,
           "problems": [], "total": len(msgs)}
    if not msgs:
        out["problems"].append("That file has no messages in it.")
        return out

    imap = None
    try:
        imap = _imap_connect(target_account, password)
        # One LIST for the whole restore.
        mapping = _discover_mailboxes(imap)
        # What is already on the server? Asked ONCE per message, in All Mail,
        # which on Gmail holds everything that has not been erased.
        allmail = mapping.get("All Mail", "[Gmail]/All Mail")

        def already(mid):
            if not mid:
                return False
            try:
                typ, _ = imap.select(_mb_arg(allmail), readonly=True)
                if typ != "OK":
                    return False
                try:
                    typ, data = imap.uid("SEARCH", "X-GM-RAW",
                                         f"rfc822msgid:{mid.strip('<>')}")
                except Exception:
                    typ, data = imap.uid("SEARCH", None, "HEADER",
                                         "Message-ID", f'"{mid}"')
                return bool(typ == "OK" and data and data[0])
            except Exception:
                return False

        with zipfile.ZipFile(path, "r") as z:
            for i, entry in enumerate(msgs):
                if stop is not None and stop():
                    break
                mid = entry.get("message_id", "")
                if only_missing and already(mid):
                    out["already_there"] += 1
                    if on_progress and i % 10 == 0:
                        on_progress(i + 1, len(msgs), out)
                    continue
                if dry_run:
                    out["restored"] += 1
                    if on_progress and i % 10 == 0:
                        on_progress(i + 1, len(msgs), out)
                    continue
                try:
                    raw = z.read(entry["file"])
                except Exception as e:
                    out["failed"] += 1
                    out["problems"].append(f"{entry.get('subject','')[:40]}: {e}")
                    continue
                # Put it back where it was: every label it wore, or the one
                # folder you chose. Appending the same message to two labels
                # is how a Gmail message ends up wearing both again.
                targets = ([folder_override] if folder_override
                           else (entry.get("labels")
                                 or [entry.get("folder") or "Inbox"]))
                ok_any = False
                for t in targets:
                    err = _imap_append_full(target_account, password, t, raw,
                                            flags=entry.get("flags"),
                                            internaldate=entry.get("date"),
                                            imap=imap)
                    if err:
                        out["problems"].append(
                            f"{entry.get('subject','')[:40]} → {t}: {err}")
                    else:
                        ok_any = True
                if ok_any:
                    out["restored"] += 1
                else:
                    out["failed"] += 1
                if on_progress and i % 10 == 0:
                    on_progress(i + 1, len(msgs), out)
    except Exception as e:
        out["problems"].append(str(e))
        log.error("Restore failed: %s", e)
    finally:
        if imap is not None:
            try:
                imap.logout()
            except Exception:
                pass
    log.info("Restore%s: %d put back, %d already there, %d failed (of %d)",
             " (dry run)" if dry_run else "", out["restored"],
             out["already_there"], out["failed"], out["total"])
    return out


def _read_export_manifest(path) -> dict:
    """The manifest of an export .zip, or {} if it is not one of ours."""
    try:
        with zipfile.ZipFile(path, "r") as z:
            with z.open("manifest.json") as f:
                return json.loads(f.read().decode("utf-8"))
    except Exception as e:
        log.warning("Not a F(re)email export (%s): %s", path, e)
        return {}


_DELETED_DIR = os.path.join(_FM_DIR, "Deleted")


def _deleted_dir():
    os.makedirs(_DELETED_DIR, exist_ok=True)
    return _DELETED_DIR


def _deleted_save(msg) -> str:
    """Write the hidden local copy of a message about to be permanently
    deleted. Returns the token id, or '' on failure."""
    try:
        d = _deleted_dir()
        token = _safe_name(f"{msg.get('account_email','')}_"
                           f"{msg.get('uid','')}_{_uuid.uuid4().hex[:8]}")
        raw = msg.get("_raw")
        if isinstance(raw, str):
            raw = raw.encode("utf-8", "replace")
        if raw:
            with open(os.path.join(d, token + ".eml"), "wb") as f:
                f.write(raw)
        meta = {
            "token":         token,
            "subject":       msg.get("subject", ""),
            "from":          msg.get("from", ""),
            "from_name":     msg.get("from_name", ""),
            "to":            msg.get("_to_hdr", ""),
            "account_email": msg.get("account_email", ""),
            "folder":        msg.get("_folder", ""),
            "date":          msg.get("date", ""),
            "_dt":           msg.get("_dt", ""),
            "_sortkey":      msg.get("_sortkey", 0.0),
            "uid":           msg.get("uid", ""),
            "message_id":    msg.get("_message_id", ""),
            "deleted_at":    _now_iso(),
            "has_raw":       bool(raw),
        }
        with open(os.path.join(d, token + ".json"), "w", encoding="utf-8") as f:
            json.dump(meta, f)
        return token
    except Exception as e:
        log.error("Could not save deleted copy: %s", e)
        return ""


def _deleted_load_all() -> list:
    d = _deleted_dir()
    out = []
    try:
        for fn in os.listdir(d):
            if not fn.endswith(".json"):
                continue
            try:
                with open(os.path.join(d, fn), encoding="utf-8") as f:
                    meta = json.load(f)
                meta["_json_path"] = os.path.join(d, fn)
                meta["_eml_path"]  = os.path.join(d, (meta.get("token", "")
                                                      + ".eml"))
                out.append(meta)
            except Exception:
                continue
    except Exception:
        pass
    out.sort(key=lambda m: m.get("deleted_at", ""), reverse=True)
    return out


def _deleted_remove(meta) -> None:
    for key in ("_json_path", "_eml_path"):
        p = meta.get(key)
        if p and os.path.isfile(p):
            try:
                os.remove(p)
            except OSError:
                pass


def _deleted_clear_all() -> int:
    metas = _deleted_load_all()
    for m in metas:
        _deleted_remove(m)
    return len(metas)


def _deleted_prune(days: int) -> int:
    """Drop copies older than `days`. 0 (or less) = keep forever."""
    try:
        days = int(days)
    except Exception:
        days = 0
    if days <= 0:
        return 0
    cutoff = datetime.now() - timedelta(days=days)
    n = 0
    for m in _deleted_load_all():
        dt = _parse_iso(m.get("deleted_at", ""))
        if dt and dt < cutoff:
            _deleted_remove(m)
            n += 1
    return n


def _deleted_to_msg(meta) -> dict:
    """Rebuild a displayable message dict from a saved deleted copy."""
    raw = b""
    p = meta.get("_eml_path", "")
    if p and os.path.isfile(p):
        try:
            with open(p, "rb") as f:
                raw = f.read()
        except Exception:
            raw = b""
    built = {}
    if raw:
        try:
            m = _email.message_from_bytes(raw)
            built = _build_msg_dict(m, [], None, meta.get("uid") or None,
                                    meta.get("account_email", ""), "Deleted", "")
            built["_raw"] = raw
        except Exception:
            built = {}
    # Overlay saved metadata so the row/reading pane is right even when the raw
    # could not be parsed.
    built.setdefault("id", meta.get("token"))
    built["subject"]       = meta.get("subject") or built.get("subject",
                                                              "(no subject)")
    built["from"]          = meta.get("from") or built.get("from", "")
    built["from_name"]     = meta.get("from_name") or built.get("from_name", "")
    built["date"]          = meta.get("date") or built.get("date", "")
    built["_sortkey"]      = meta.get("_sortkey", built.get("_sortkey", 0.0))
    built["account_email"] = meta.get("account_email", "")
    built["_folder"]       = "Deleted"
    built["unread"]        = False
    built["_deleted_meta"] = meta
    return built


def _delete_impact(msg: dict) -> dict:
    """What would actually happen if this message were trashed?

    Returns {"labels": [...], "self_sent": bool, "multi": bool}. Gmail keeps
    one message per conversation-item and hangs labels on it, so this is the
    difference between "removing it from Sent" and "removing it from five
    places at once"."""
    labels = [l for l in (msg.get("_labels") or [])
              if l.lower() not in ("important", "starred")]
    folder = msg.get("_folder", "")
    if folder and folder not in labels:
        labels = [folder] + labels
    # De-duplicate while keeping order.
    seen, ordered = set(), []
    for l in labels:
        low = l.lower()
        if low in seen:
            continue
        seen.add(low)
        ordered.append(l)
    return {
        "labels":    ordered,
        "self_sent": _is_self_message(msg),
        "multi":     len(ordered) > 1,
    }


def _delete_confirmation_text(msg: dict, impact: dict) -> str:
    """The words shown before anything is touched. Written to be read."""
    subject = (msg.get("subject") or "(no subject)")[:70]
    lines = [f"Move this message to the Gmail Trash?", "",
             f"    {subject}",
             f"    from {msg.get('from_name') or msg.get('from', '')}", ""]
    if impact["labels"]:
        where = ", ".join(impact["labels"])
        if impact["multi"]:
            lines += [
                "On Gmail this is ONE message carrying several labels, so it "
                "will disappear from ALL of these at once:", "",
                f"    {where}", ""]
        else:
            lines += [f"It will disappear from: {where}", ""]
    if impact["self_sent"]:
        lines += [
            "⚠  You sent this message to yourself. The copy in your Inbox "
            "and the copy in Sent are the SAME message — deleting it removes "
            "both. There is no second copy.", ""]
    lines += [
        "It goes to the Trash, where Gmail keeps it for 30 days and you can "
        "restore it. Nothing is erased permanently."]
    return "\n".join(lines)


# ******************************************************************************
# DEL 04j — FOLLOW-UPS: "I am not finished with this mail"
# ******************************************************************************
#
# Deliberately NOT the calendar. A calendar entry says "at 14:00 on Thursday
# something happens". A follow-up says "there is something left to do in THIS
# message, keep nagging me until I have dealt with it". Different thing,
# different data, different popup.
#
# Snooze is not this either: snooze HIDES a message until a time. A follow-up
# leaves the message exactly where it is and comes back to poke you.
#
# THE SCHEDULE, IN THE USER'S OWN TERMS
# -------------------------------------
#   "remind me the first time at X"        → first_at
#   "and then every Y after that"          → repeat_min (0 = only once)
#   "but only Z times"                     → max_count (0 = no limit)
#   "and never after this date"            → until ("" = no end date)
#   "or until I press stop"                → neither of the two above
#
# Two intervals fall out of this for free: the wait before the FIRST reminder
# is independent of the rhythm afterwards, which is exactly "one before the
# first and then another regularity".
#
# THE LAST REMINDER LOOKS DIFFERENT
# ---------------------------------
# When a follow-up is about to run out — the count is used up, or the next
# repeat would fall past the end date — that final popup is styled and worded
# unmistakably differently. Being told "this is the last time you will hear
# about this" is the whole point of setting an end at all; a final reminder
# that looked like every other one would be worse than useless.

_FOLLOWUP_F = os.path.join(_ACCOUNTS_DIR, "followups.json")

_FOLLOWUP_DEFAULTS = {
    "id": "", "key": "", "account": "", "folder": "", "uid": "",
    "subject": "", "from": "", "from_name": "", "note": "",
    "created": "", "first_at": "", "repeat_min": 0, "max_count": 0,
    "until": "", "fired_count": 0, "next_at": "", "done": False,
    "last_shown": "",
    # float to the top (2026-11-23): the choice, when it came up, Done pressed
    "float": False, "surfaced": "", "resolved": False,
    # kind "snooze" (2026-11-24): the plain "tell me on <date>" reminder that
    # replaced the old hiding snooze. One popup, the mail itself is untouched.
    "kind": "",
}


def _load_followups() -> dict:
    store = _load_json_store(_FOLLOWUP_F, {"items": list}, "follow-ups")
    for it in store.get("items", []):
        for k, v in _FOLLOWUP_DEFAULTS.items():
            it.setdefault(k, v)
        if not it.get("id"):
            it["id"] = _new_id()
        if not it.get("next_at"):
            it["next_at"] = it.get("first_at", "")
    return store


def _save_followups(store: dict):
    _save_json_store(_FOLLOWUP_F, store, "follow-ups")


def _followup_new(msg: dict, first_at, repeat_min=0, max_count=0, until=None,
                  note="", float_up=False, kind="") -> dict:
    """Build a follow-up for one message."""
    return {
        "kind":       kind or "",
        "id":         _new_id(),
        "key":        _msg_key(msg),
        "account":    msg.get("account_email", ""),
        "folder":     msg.get("_folder", ""),
        "uid":        msg.get("uid") or "",
        "subject":    msg.get("subject", "") or "(no subject)",
        "from":       msg.get("from", ""),
        "from_name":  msg.get("from_name", "") or msg.get("from", ""),
        "note":       note or "",
        "created":    _now_iso(),
        "first_at":   first_at.isoformat(timespec="seconds"),
        "repeat_min": max(0, int(repeat_min or 0)),
        "max_count":  max(0, int(max_count or 0)),
        "until":      until.isoformat(timespec="seconds") if until else "",
        "fired_count": 0,
        "next_at":    first_at.isoformat(timespec="seconds"),
        "done":       False,
        "last_shown": "",
        "float":      bool(float_up),
        "surfaced":   "",
        "resolved":   False,
    }


def _followup_is_final(item: dict) -> bool:
    """Is the reminder that is about to fire the LAST one?

    Three ways a follow-up can be about to end:
      • it never repeats, so the first is also the last,
      • this firing uses up the allowed count,
      • the next repeat after this one would fall past the end date.
    """
    if item.get("done"):
        return True
    repeat = int(item.get("repeat_min") or 0)
    if repeat <= 0:
        return True
    max_count = int(item.get("max_count") or 0)
    fired_next = int(item.get("fired_count") or 0) + 1
    if max_count and fired_next >= max_count:
        return True
    until = _parse_iso(item.get("until", "") or "")
    if until is not None:
        nxt = _parse_iso(item.get("next_at", "") or "")
        if nxt is None or nxt + timedelta(minutes=repeat) > until:
            return True
    return False


def _followup_due(store: dict, now=None) -> list:
    """Follow-ups whose time has come and that are not finished."""
    now = now or datetime.now()
    out = []
    for it in store.get("items", []):
        if it.get("done"):
            continue
        nxt = _parse_iso(it.get("next_at", "") or "")
        if nxt is not None and nxt <= now:
            out.append(it)
    out.sort(key=lambda i: i.get("next_at", ""))
    return out


def _followup_advance(item: dict, now=None):
    """Record that a reminder has just been shown and work out the next one.

    Sets done=True when the follow-up has run out — by count, by end date, or
    because it never repeated in the first place."""
    now = now or datetime.now()
    item["fired_count"] = int(item.get("fired_count") or 0) + 1
    item["last_shown"]  = now.isoformat(timespec="seconds")

    repeat = int(item.get("repeat_min") or 0)
    if repeat <= 0:
        item["done"] = True
        item["next_at"] = ""
        return item

    max_count = int(item.get("max_count") or 0)
    if max_count and item["fired_count"] >= max_count:
        item["done"] = True
        item["next_at"] = ""
        return item

    # Next occurrence, counted from the time it was DUE, not from now, so a
    # program that was closed for a day does not drift the whole schedule.
    base = _parse_iso(item.get("next_at", "") or "") or now
    nxt = base + timedelta(minutes=repeat)
    while nxt <= now:                      # catch up if we were away
        nxt += timedelta(minutes=repeat)

    until = _parse_iso(item.get("until", "") or "")
    if until is not None and nxt > until:
        item["done"] = True
        item["next_at"] = ""
        return item

    item["next_at"] = nxt.isoformat(timespec="seconds")
    return item


def _followup_stop(store: dict, item_id: str):
    """Stop reminding AND let go of the mail: "resolved" ends the floating at
    the top of the list too (2026-11-23)."""
    for it in store.get("items", []):
        if it.get("id") == item_id:
            it["done"] = True
            it["resolved"] = True
            it["next_at"] = ""
    _save_followups(store)


def _followup_remove(store: dict, item_id: str):
    store["items"] = [i for i in store.get("items", [])
                      if i.get("id") != item_id]
    _save_followups(store)


def _followup_is_floating(item: dict) -> bool:
    """True while the mail of this follow-up sits at the top of its folder,
    unread: its time has come (surfaced), it asked to float, and nobody has
    pressed Done (resolved) or replaced the reminder yet."""
    return (bool(item.get("float")) and bool(item.get("surfaced"))
            and not item.get("resolved"))


def _followup_float_keys(store: dict) -> set:
    """Message keys that are floating at the top right now."""
    return {it.get("key", "") for it in store.get("items", [])
            if _followup_is_floating(it)}


def _followup_active_keys(store: dict) -> set:
    """Message keys with a live follow-up — used to mark them in the list."""
    return {it.get("key", "") for it in store.get("items", [])
            if not it.get("done") or _followup_is_floating(it)}


def _fmt_interval(minutes: int) -> str:
    m = int(minutes or 0)
    if m <= 0:
        return "once"
    if m % 10080 == 0:
        n = m // 10080
        return f"every {n} week{'s' if n > 1 else ''}"
    if m % 1440 == 0:
        n = m // 1440
        return f"every {n} day{'s' if n > 1 else ''}"
    if m % 60 == 0:
        n = m // 60
        return f"every {n} hour{'s' if n > 1 else ''}"
    return f"every {m} min"


def _followup_describe(item: dict) -> str:
    """One line summarising the schedule, for the list and the editor."""
    bits = []
    nxt = _parse_iso(item.get("next_at", "") or "")
    if _followup_is_floating(item):
        bits.append("🔼 at the top of its folder until you press Done")
    elif item.get("done"):
        bits.append("finished")
    elif nxt:
        bits.append(f"next {nxt.strftime('%Y-%m-%d %H:%M')}")
    repeat = int(item.get("repeat_min") or 0)
    bits.append(_fmt_interval(repeat))
    max_count = int(item.get("max_count") or 0)
    if max_count:
        bits.append(f"{item.get('fired_count', 0)}/{max_count} shown")
    elif not item.get("until"):
        bits.append("until stopped")
    until = _parse_iso(item.get("until", "") or "")
    if until:
        bits.append(f"ends {until.strftime('%Y-%m-%d')}")
    return "  ·  ".join(bits)


# ******************************************************************************
# DEL 04k — TAGS: mark a message by hand, with a colour and an icon
# ******************************************************************************
#
# What already existed and is NOT this:
#   • contact colours — colour by SENDER (everything from the bank is blue)
#   • filter row colours — colour by RULE (anything matching "faktura")
#   • star / priority / spam — three fixed flags with fixed meanings
#
# What was missing is Thunderbird's actual tags: a mark YOU put on ONE
# message because of what it means to you, with your own name, colour and
# icon. Press 1-9 on a selected message, or use the reading pane.
#
# Local only. Gmail has labels, which look similar, but writing labels to the
# server is a Phase-2 change nobody asked for — and a tag you can lose because
# a sync went wrong is worse than one that lives in a file you own.

_TAGS_F = os.path.join(_ACCOUNTS_DIR, "tags.json")

# Thunderbird's five, plus a few that match how mail actually arrives here.
# icon is what shows in the message list; colour tints the row.
_DEFAULT_TAGS = [
    {"id": "important", "name": "Important", "color": "#c0392b", "icon": "❗"},
    {"id": "work",      "name": "Work",      "color": "#d68910", "icon": "💼"},
    {"id": "personal",  "name": "Personal",  "color": "#27ae60", "icon": "🏠"},
    {"id": "todo",      "name": "To do",     "color": "#2980b9", "icon": "☑"},
    {"id": "later",     "name": "Later",     "color": "#8e44ad", "icon": "🕓"},
    {"id": "bill",      "name": "Bill",      "color": "#16a085", "icon": "💰"},
    {"id": "shipping",  "name": "Shipping",  "color": "#7f8c8d", "icon": "📦"},
    {"id": "keep",      "name": "Keep",      "color": "#b7950b", "icon": "📌"},
    {"id": "junk",      "name": "Junk",      "color": "#616a6b", "icon": "🗑"},
]


def _load_tags() -> dict:
    """{"tags": [...], "assigned": {msg_key: [tag_id, ...]}}"""
    store = _load_json_store(_TAGS_F,
                             {"tags": lambda: [dict(t) for t in _DEFAULT_TAGS],
                              "assigned": dict}, "tags")
    if not store.get("tags"):
        store["tags"] = [dict(t) for t in _DEFAULT_TAGS]
    for t in store["tags"]:
        t.setdefault("icon", "●")
        t.setdefault("color", "#7f8c8d")
        if not t.get("id"):
            t["id"] = _new_id()
    return store


def _save_tags(store: dict):
    _save_json_store(_TAGS_F, store, "tags")


# ── Address-mails: a manual "there is an address in here" mark (Issu 2026-09-23)
# Purely manual, on purpose — Issu asked for the least load, no auto-scan. Two
# ways in, both from a right-click:
#   • mark the WHOLE mail  → snippet stays ""      (envelope, nothing saved)
#   • save a SELECTION     → snippet is that text  (envelope, click = popup)
# The store is keyed by _msg_key, exactly like tags/snooze/blocklist, so it
# survives a re-fetch and is dropped by itself if the message is gone for good.
_ADDR_F = os.path.join(_ACCOUNTS_DIR, "address_mails.json")


def _load_address_mails() -> dict:
    """{"marked": {msg_key: {"snippet": "<saved address text, or ''>"}}}"""
    return _load_json_store(_ADDR_F, {"marked": dict}, "address_mails")


def _save_address_mails(store: dict):
    _save_json_store(_ADDR_F, store, "address_mails")


def _addr_is_marked(store: dict, msg: dict) -> bool:
    return _msg_key(msg) in (store.get("marked") or {})


def _addr_snippet(store: dict, msg: dict) -> str:
    entry = (store.get("marked") or {}).get(_msg_key(msg))
    return (entry or {}).get("snippet", "") if entry else ""


def _addr_set(store: dict, msg: dict, snippet: str = ""):
    """Mark a message as an address-mail. snippet '' = whole-mail mark; a
    non-empty snippet is stored, and re-marking the whole mail never wipes a
    snippet that is already there."""
    marked = store.setdefault("marked", {})
    key = _msg_key(msg)
    entry = marked.get(key, {})
    if snippet:
        entry["snippet"] = snippet
    else:
        entry.setdefault("snippet", "")
    marked[key] = entry
    _save_address_mails(store)


def _addr_clear(store: dict, msg: dict):
    (store.get("marked") or {}).pop(_msg_key(msg), None)
    _save_address_mails(store)


# ── Manual conversation MERGE groups (DEL 04A1) ───────────────────────────────
# By default F(re)email does NOT merge messages into conversations any more —
# Issu wants each Tradera "Frakthandling" on its own row, one per shipment.
# Merging is now opt-IN: a manual group ties several message keys together so
# they render as ONE collapsible conversation, regardless of the (now off by
# default) automatic "merge by Gmail thread" setting.
_MERGE_F = os.path.join(_ACCOUNTS_DIR, "merge_groups.json")


def _load_merge_groups() -> dict:
    """{"groups": [{"id": "mg_x", "keys": [msg_key, ...]}, ...]}"""
    return _load_json_store(_MERGE_F, {"groups": list}, "merge_groups")


def _save_merge_groups(store: dict):
    _save_json_store(_MERGE_F, store, "merge_groups")


def _merge_group_id_for(store: dict, key: str):
    """Synthetic thread id of the group a message key is in, or None."""
    if not key:
        return None
    for g in store.get("groups", []):
        if key in (g.get("keys") or []):
            return g.get("id")
    return None


def _merge_add_group(store: dict, keys) -> str:
    """Tie `keys` together as one conversation. Any key already in a group is
    pulled out of it first (a key belongs to at most one group); existing groups
    that overlap the new set are absorbed, so merging A+B then B+C yields A+B+C.
    Returns the group id (or "" if fewer than two real keys)."""
    keys = [k for k in dict.fromkeys(keys) if k]     # de-dup, keep order
    if len(keys) < 2:
        return ""
    groups = store.setdefault("groups", [])
    # Absorb any group that shares a key with the new set.
    merged = set(keys)
    survivors = []
    for g in groups:
        if set(g.get("keys") or []) & merged:
            merged.update(g.get("keys") or [])
        else:
            survivors.append(g)
    gid = "mg_" + _new_id()
    survivors.append({"id": gid, "keys": list(merged)})
    store["groups"] = survivors
    return gid


def _merge_remove_key(store: dict, key: str):
    """Take one message out of whatever group it is in; drop groups left with
    fewer than two members."""
    out = []
    for g in store.get("groups", []):
        ks = [k for k in (g.get("keys") or []) if k != key]
        if len(ks) >= 2:
            g["keys"] = ks
            out.append(g)
    store["groups"] = out


def _merge_remove_group_of(store: dict, key: str):
    """Un-merge the WHOLE conversation a key belongs to (split them all apart)."""
    gid = _merge_group_id_for(store, key)
    if gid is None:
        return
    store["groups"] = [g for g in store.get("groups", [])
                       if g.get("id") != gid]


def _normalize_subject(subj: str) -> str:
    """Strip Re:/Sv:/Aw:/Fwd:/Vb: prefixes + surrounding space, for the loose
    "these look like the same thread" match in the Merge picker."""
    s = (subj or "").strip()
    while True:
        s2 = _re.sub(r'(?i)^\s*(re|sv|aw|fw|fwd|vb|vs)\s*:\s*', '', s)
        if s2 == s:
            break
        s = s2
    return s.strip().lower()


def _tag_by_id(store: dict, tag_id: str):
    for t in store.get("tags", []):
        if t.get("id") == tag_id:
            return t
    return None


def _tags_of(store: dict, msg: dict) -> list:
    """The tag dicts on one message, in the order they were defined."""
    ids = set((store.get("assigned") or {}).get(_msg_key(msg), []))
    return [t for t in store.get("tags", []) if t.get("id") in ids]


def _tag_toggle(store: dict, msg: dict, tag_id: str) -> bool:
    """Add or remove a tag. Returns True if it is now ON."""
    key = _msg_key(msg)
    assigned = store.setdefault("assigned", {})
    have = list(assigned.get(key, []))
    if tag_id in have:
        have.remove(tag_id)
        on = False
    else:
        have.append(tag_id)
        on = True
    if have:
        assigned[key] = have
    else:
        assigned.pop(key, None)     # do not keep empty lists forever
    _save_tags(store)
    return on


def _tag_marks(store: dict, msg: dict) -> str:
    """The icons to put in front of a message in the list."""
    return "".join(t.get("icon", "●") for t in _tags_of(store, msg))


def _tag_row_color(store: dict, msg: dict) -> str:
    """The colour of the FIRST tag — one row cannot be three colours, and the
    first one you applied is the one you thought of first."""
    tags = _tags_of(store, msg)
    return tags[0].get("color", "") if tags else ""


def _tag_prune(store: dict, known_keys: set):
    """Optional housekeeping: forget assignments for messages that no longer
    exist. Deliberately NOT called automatically — a message missing from the
    current view is usually just in another folder, not gone."""
    assigned = store.get("assigned", {})
    for key in list(assigned):
        if key not in known_keys:
            del assigned[key]
    _save_tags(store)


# ******************************************************************************
# DEL 04l — FOLDER PLANS: dated folders made on a schedule, and files tidied
#           into them
# ******************************************************************************
#
# THE PROBLEM THIS SOLVES
# -----------------------
# Attachment rules (DEL 04b/04e) drop shipping labels into a folder called
# Frakt. Every month you then make a sub-folder by hand — 08-Augusti — and
# move last month's files into it. That is a chore a program should do.
#
# A PLAN says: on the 3rd of every month, create "08-Augusti" inside
# D:\Frakt, and move the files belonging to a chosen date range into it.
#
# THIS IS ABOUT FILES ON YOUR DISK, not mailboxes on Gmail. Nothing here
# touches a server. Moving files is reversible in Explorer; moving mail on a
# server is not, which is why that half is not done automatically anywhere in
# this program (see DEL 04h).
#
# WHICH DATE A FILE HAS
# ---------------------
# Two sources, tried in order:
#   1. a date in the FILENAME — because your own prefix rules put it there
#      ("GELF---Sandtorp 32---2026-05---faktura.pdf" belongs to May, whatever
#      the file's timestamp says after a copy);
#   2. the file's modification time, as a fallback.
# That order matters: copying files between drives rewrites timestamps, and
# the name is what you actually meant.

_FOLDERPLANS_F = os.path.join(_ACCOUNTS_DIR, "folderplans.json")

# Month names live in the PLAN, not in the code: this program is English, but
# your folders may well be Swedish ("08-Augusti"). Empty = the English list.
_MONTHS_EN = ["January", "February", "March", "April", "May", "June", "July",
              "August", "September", "October", "November", "December"]

_FOLDERPLAN_DEFAULTS = {
    "id": "", "name": "", "enabled": True,
    "base_dir": "",            # the folder the dated sub-folder is made in
    "pattern": "{MM}-{MonthName}",
    "day_of_month": 1,         # create it on this day
    "every_months": 1,         # 1 = every month, 3 = quarterly …
    "month_names": [],         # [] = English; 12 entries to override
    "move_files": False,
    "window": "previous_month",   # previous_month | current_month | custom
    "custom_from": "", "custom_to": "",     # YYYY-MM-DD when window=custom
    "last_run": "",            # ISO date of the period last handled
}

_DATE_IN_NAME_RE = _re.compile(r'(20\d{2})-(\d{2})(?:-(\d{2}))?')


def _load_folderplans() -> dict:
    store = _load_json_store(_FOLDERPLANS_F, {"plans": list}, "folder plans")
    for p in store.get("plans", []):
        for k, v in _FOLDERPLAN_DEFAULTS.items():
            p.setdefault(k, v() if callable(v) else v)
        if not p.get("id"):
            p["id"] = _new_id()
    return store


def _save_folderplans(store: dict):
    _save_json_store(_FOLDERPLANS_F, store, "folder plans")


def _plan_month_names(plan: dict) -> list:
    names = plan.get("month_names") or []
    return names if len(names) == 12 else _MONTHS_EN


def _expand_folder_pattern(plan: dict, when: datetime) -> str:
    """Turn "{MM}-{MonthName}" into "08-August" (or "08-Augusti")."""
    names = _plan_month_names(plan)
    repl = {
        "{YYYY}":      f"{when.year:04d}",
        "{YY}":        f"{when.year % 100:02d}",
        "{MM}":        f"{when.month:02d}",
        "{M}":         str(when.month),
        "{MonthName}": names[when.month - 1],
        "{DD}":        f"{when.day:02d}",
        "{Q}":         f"Q{(when.month - 1) // 3 + 1}",
    }
    out = plan.get("pattern") or "{MM}-{MonthName}"
    for tok, val in repl.items():
        out = out.replace(tok, val)
    return _safe_name(out)


def _plan_target_month(plan: dict, now: datetime) -> datetime:
    """Which month the folder being created is FOR.

    A plan that runs on the 3rd and files "last month" should make a folder
    named after last month — that is what you would have written by hand."""
    if plan.get("window") == "current_month":
        return now
    return _add_months(now.replace(day=1), -1)


def _plan_window(plan: dict, now: datetime):
    """(from_datetime, to_datetime) for which files belong in this folder."""
    if plan.get("window") == "custom":
        f = _parse_iso(plan.get("custom_from", "") or "")
        t = _parse_iso(plan.get("custom_to", "") or "")
        if f and t:
            return f, t.replace(hour=23, minute=59, second=59)
        return None, None
    month = _plan_target_month(plan, now)
    start = month.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
    end   = _add_months(start, 1) - timedelta(seconds=1)
    return start, end


def _plan_due(plan: dict, now=None) -> bool:
    """Is this plan due to run now?

    Runs once per period: on or after the chosen day of the month, and not
    already run for that period. "On or after" matters — if the computer was
    off on the 3rd, it still runs on the 4th instead of skipping a month."""
    if not plan.get("enabled", True) or not plan.get("base_dir"):
        return False
    now = now or datetime.now()
    day = max(1, min(28, int(plan.get("day_of_month") or 1)))
    if now.day < day:
        return False
    every = max(1, int(plan.get("every_months") or 1))
    period = f"{now.year:04d}-{now.month:02d}"
    if plan.get("last_run", "") >= period:
        return False
    if every > 1:
        # Count months from a fixed origin so "every 3 months" is stable.
        if ((now.year * 12 + now.month - 1) % every) != 0:
            return False
    return True


def _file_date(path: str) -> datetime:
    """The date a file belongs to: from its NAME first, then its timestamp."""
    m = _DATE_IN_NAME_RE.search(os.path.basename(path))
    if m:
        y, mo, d = int(m.group(1)), int(m.group(2)), int(m.group(3) or 1)
        try:
            return datetime(y, mo, d)
        except ValueError:
            pass
    try:
        return datetime.fromtimestamp(os.path.getmtime(path))
    except OSError:
        return datetime.fromtimestamp(0)


def _plan_run(plan: dict, now=None, dry_run=False) -> dict:
    """Create the folder and (optionally) move the matching files into it.

    Returns {"folder": path, "moved": [names], "skipped": [(name, why)],
             "error": ""}. Never overwrites: a name clash gets (1), (2)…"""
    now = now or datetime.now()
    result = {"folder": "", "moved": [], "skipped": [], "error": ""}
    base = (plan.get("base_dir") or "").strip()
    if not base:
        result["error"] = "No folder is set for this plan."
        return result
    if not os.path.isdir(base):
        result["error"] = f"The folder does not exist:\n{base}"
        return result

    target_month = _plan_target_month(plan, now)
    folder = os.path.join(base, _expand_folder_pattern(plan, target_month))
    result["folder"] = folder
    if not dry_run:
        try:
            os.makedirs(folder, exist_ok=True)
        except Exception as e:
            result["error"] = f"Could not create {folder}: {e}"
            return result

    if not plan.get("move_files"):
        return result

    start, end = _plan_window(plan, now)
    if start is None:
        result["error"] = "The custom date range is not set properly."
        return result

    try:
        names = os.listdir(base)
    except Exception as e:
        result["error"] = f"Could not read {base}: {e}"
        return result

    for name in names:
        src = os.path.join(base, name)
        if os.path.isdir(src):
            continue                      # only loose files, never folders
        when = _file_date(src)
        if not (start <= when <= end):
            result["skipped"].append((name, when.strftime("%Y-%m-%d")))
            continue
        dst = os.path.join(folder, name)
        n = 1
        while os.path.exists(dst):        # never overwrite anything
            root_, ext_ = os.path.splitext(name)
            dst = os.path.join(folder, f"{root_}({n}){ext_}")
            n += 1
        if dry_run:
            result["moved"].append(name)
            continue
        try:
            shutil.move(src, dst)
            result["moved"].append(name)
        except Exception as e:
            log.warning("Folder plan: could not move %s: %s", src, e)
            result["skipped"].append((name, str(e)[:40]))
    return result


def _plan_mark_run(store: dict, plan: dict, now=None):
    now = now or datetime.now()
    plan["last_run"] = f"{now.year:04d}-{now.month:02d}"
    _save_folderplans(store)


def _plan_describe(plan: dict) -> str:
    every = max(1, int(plan.get("every_months") or 1))
    when = (f"day {plan.get('day_of_month', 1)} of "
            f"{'every month' if every == 1 else f'every {every} months'}")
    what = (f"move files from {plan.get('window', 'previous_month').replace('_', ' ')}"
            if plan.get("move_files") else "create the folder only")
    return f"{when}  ·  {plan.get('pattern','')}  ·  {what}"


# ******************************************************************************
# DEL 04r — FOLDER AGEING: what happens to mail in a folder as it gets old
# ******************************************************************************
#
# Issu 2026-09-09: "Jag har skapat Delete later i Temporär. Jag skickar mail dit
# och jag vill kunna högerklicka på katalogen och välja funktioner, t.ex. delete
# everything older than XX hours, eller mark everything as read after xx hours …
# ungefär som filterregler men på kataloger och bara påverka innehållet,
# beroende på hur gamla mailen är."
#
# So: a filter asks WHO sent it and WHAT it says, and fires once, on arrival.
# This asks only HOW OLD it is, and keeps asking — the same message is looked at
# again every hour it stays in the folder. That is a different question, and it
# belongs on the folder rather than in the rule list, which is why it is its own
# thing instead of one more condition in DEL 04d.
#
# THE LADDER is the point. His own example is two steps of one rule:
#
#     "Delete later"   →  after 24 h  mark it read
#                      →  after 48 h  move it to the Trash
#
# so a rule is a folder plus an ORDERED LIST of steps, not a single action. Each
# message is judged once per run and gets the LAST step whose time has come —
# a 50-hour-old message is trashed, it is not marked read first and trashed on
# the next pass.
#
# WHAT IT WILL NOT DO, and why:
#   • It never ERASES anything. "Delete" here means what Delete means everywhere
#     else in this program: move to the Trash, where Gmail keeps it for 30 days
#     and you can still get it back. The only place mail is truly erased is
#     Empty the Trash, which you press yourself (DEL 04s).
#   • It is a SERVER CHANGE, so it is gated by "allow server changes" like every
#     other one — an ageing rule on an account that has that switch off does
#     nothing at all, silently, and says so in the dialog.
#   • It never touches a folder you have PROTECTED (_is_protected). Protection
#     means "nothing automatic may move mail out of here", and this is exactly
#     the kind of automatic the promise was made about.
#   • It never touches a STARRED message unless you turn that guard off. A star
#     is you saying "not this one", by hand, and no clock should outvote it.
#   • It stops and asks when a single run would touch more than `ask_over`
#     messages. Typing 2 where you meant 200 is a real way to lose a folder, and
#     this is the one number that makes that mistake survivable.
#
# AGE IS WHEN IT ARRIVED (the server's INTERNALDATE), not the Date: header a
# sender wrote — same reasoning as _sweep_age_terms. A mail that sat in a queue
# for a day is 0 hours old to you, because you could not have read it earlier.

_FOLDERAGE_F = os.path.join(_ACCOUNTS_DIR, "folderage.json")

# Every action a step may take, in the order the dropdown offers them: gentlest
# first, so the destructive one is never the thing your hand lands on.
_AGE_ACTIONS = [
    ("read",  "mark it as read"),
    ("move",  "move it to…"),
    ("trash", "move it to the Trash  (this is what “delete” means)"),
]
_AGE_ACTION_LABEL = dict(_AGE_ACTIONS)

AGE_SCAN_MAX      = 3000   # messages examined in one folder in one run
AGE_ASK_OVER      = 50     # …before it stops and asks
AGE_MIN_INTERVAL  = 15     # minutes between two runs of the same rule


def _load_folder_ages() -> dict:
    return _load_json_store(_FOLDERAGE_F, {"rules": list}, "folder ageing")


def _save_folder_ages(store: dict):
    _save_json_store(_FOLDERAGE_F, store, "folder ageing")


def _age_new_rule(account: str, folder: str) -> dict:
    """A fresh rule for one folder, switched OFF and with his own example
    already in it — two steps, because one step would teach the wrong shape."""
    return {
        "id": _new_id(),
        "account": account,
        "folder": folder,
        "include_sub": False,
        "enabled": False,
        "keep_starred": True,
        "ask_over": AGE_ASK_OVER,
        "steps": [
            {"after_hours": 24, "action": "read",  "target": "",
             "only_read": False},
            {"after_hours": 48, "action": "trash", "target": "",
             "only_read": True},
        ],
        "last_run": "",
    }


def _age_steps(rule: dict) -> list:
    """This rule's steps, oldest threshold LAST.

    Sorted here rather than trusted from the file, because "the last step whose
    time has come" is only a safe way to choose when the list really is in
    order, and the dialog lets you type the hours in any order you like."""
    steps = [s for s in (rule.get("steps") or [])
             if isinstance(s, dict) and (s.get("action") in _AGE_ACTION_LABEL)]
    return sorted(steps, key=lambda s: _age_hours(s))


def _age_hours(step: dict) -> float:
    """A step's threshold in hours, as a number, whatever the file holds."""
    try:
        h = float(step.get("after_hours") or 0)
    except (TypeError, ValueError):
        h = 0.0
    return max(0.0, h)


def _age_rules_for(store: dict, account: str, folder: str) -> list:
    """Every ENABLED rule that governs this account's folder.

    A rule with `include_sub` also governs everything nested under its folder,
    so "Temporär" can age a dozen labels at once. Compared with _folder_norm
    for the reason spelled out in _protected_key: the same folder reaches this
    code both as decoded text and as raw modified-UTF-7."""
    want = _folder_norm(folder)
    if not want:
        return []
    out = []
    for r in (store.get("rules") or []):
        if not r.get("enabled"):
            continue
        if (r.get("account") or "") != account:
            continue
        base = _folder_norm(r.get("folder") or "")
        if not base:
            continue
        if base == want or (r.get("include_sub") and want.startswith(base + "/")):
            out.append(r)
    return out


def _age_folders_of(rule: dict, all_folders) -> list:
    """The folders one rule actually works on — itself, plus everything nested
    under it when `include_sub` is on. `all_folders` is the account's known
    mailbox list; anything not on it is simply not there to age."""
    base_raw = rule.get("folder") or ""
    base = _folder_norm(base_raw)
    out = [base_raw]
    if rule.get("include_sub"):
        for f in (all_folders or []):
            n = _folder_norm(f)
            if n != base and n.startswith(base + "/"):
                out.append(f)
    return out


def _age_plan(rule: dict, items, now=None) -> dict:
    """Decide, for one folderful of messages, what happens to each one.

    `items` are the dicts _imap_age_scan returns: uid, ts (epoch seconds when
    the server received it), seen, flagged, subject, sender. Pure arithmetic —
    no network, no Tk — so the whole decision can be tested, and so the preview
    button and the real run can never disagree about what is about to happen.

    Returns {"act": [(item, step), …], "kept": {reason: n}, "problems": [str]}.
    `act` is what would be done; `kept` says, in plain words, why everything
    else was left alone, because "nothing happened" is not an answer."""
    now = now or time.time()
    steps = _age_steps(rule)
    keep_starred = bool(rule.get("keep_starred", True))
    act, kept, problems = [], {}, []

    def _keep(reason):
        kept[reason] = kept.get(reason, 0) + 1

    for st in steps:
        if st.get("action") == "move" and not (st.get("target") or "").strip():
            problems.append(f"The step at {_age_hours(st):g} h has no "
                            f"destination folder, so it was skipped.")

    for it in (items or []):
        ts = it.get("ts") or 0
        if not ts:
            _keep("no date from the server")
            continue
        age_h = (now - ts) / 3600.0
        if keep_starred and it.get("flagged"):
            _keep("starred — you marked it yourself")
            continue
        # The LAST step whose time has come. Steps are sorted by threshold, so
        # this really is the most-overdue one.
        chosen = None
        for st in steps:
            if age_h + 1e-9 >= _age_hours(st):
                chosen = st
            else:
                break
        if chosen is None:
            _keep("not old enough yet")
            continue
        action = chosen.get("action")
        if action == "move" and not (chosen.get("target") or "").strip():
            _keep("the step has no destination")
            continue
        # "…but only if I have read it" — a guard for the destructive steps.
        # On a "mark it read" step it would mean "mark the read ones read",
        # so it is ignored there rather than quietly doing nothing.
        if chosen.get("only_read") and action != "read" and not it.get("seen"):
            _keep("still unread")
            continue
        if action == "read" and it.get("seen"):
            _keep("already read")
            continue
        act.append((it, chosen))
    return {"act": act, "kept": kept, "problems": problems}


def _age_step_describe(step: dict) -> str:
    """One step as a sentence: "after 48 h — move it to the Trash (only if
    already read)"."""
    h = _age_hours(step)
    when = (f"after {h:g} h" if h < 48 else
            f"after {h:g} h  ({h / 24:g} days)")
    what = _AGE_ACTION_LABEL.get(step.get("action"), step.get("action") or "?")
    if step.get("action") == "move":
        what = f"move it to “{step.get('target') or '…'}”"
    extra = (" · only if already read"
             if step.get("only_read") and step.get("action") != "read" else "")
    return f"{when} — {what}{extra}"


def _age_describe(rule: dict) -> str:
    """A whole rule on one line, for the sidebar menu and the rule list."""
    steps = _age_steps(rule)
    if not steps:
        return "no steps yet"
    bits = []
    for s in steps:
        what = _AGE_ACTION_LABEL.get(s.get("action"), "?").split("  ")[0]
        if s.get("action") == "move":
            what = f"→ {s.get('target') or '…'}"
        bits.append(f"{_age_hours(s):g}h {what}")
    return "  ·  ".join(bits)


def _age_due(rule: dict, now=None) -> bool:
    """Has enough time passed to look at this rule again?

    A quarter of an hour. The clock does not move fast enough to make a
    difference in less, and re-scanning a folder every 30 seconds would spend
    the whole day logging in to Gmail to be told nothing has changed."""
    if not rule.get("enabled"):
        return False
    last = rule.get("last_run") or ""
    if not last:
        return True
    try:
        prev = datetime.fromisoformat(last)
    except Exception:
        return True
    return (datetime.now() - prev) >= timedelta(minutes=AGE_MIN_INTERVAL)


def _age_mark_run(store: dict, rule: dict, now=None):
    rule["last_run"] = (now or datetime.now()).isoformat(timespec="seconds")
    for r in store.get("rules", []):
        if r.get("id") == rule.get("id"):
            r["last_run"] = rule["last_run"]
    _save_folder_ages(store)


def _imap_age_scan(email_addr, password, folder, min_hours=0.0,
                   cap=AGE_SCAN_MAX) -> tuple:
    """List one folder with just enough about each message to judge its age.

    Returns (items, problems). READ-ONLY throughout: select(readonly=True) and
    BODY.PEEK, so a scan — including the preview button — cannot change a thing
    on Gmail even if everything else went wrong.

    Each item is {uid, ts, seen, flagged, subject, sender}. `ts` is INTERNALDATE
    as epoch seconds: when the SERVER got it.

    `min_hours` is used only to narrow the search with BEFORE, and deliberately
    with a whole day of slack (BEFORE is date-only, and the server's idea of
    "today" is not necessarily ours). It can only ever return MORE than is
    wanted — the real cut is made in _age_plan, with the actual timestamps."""
    items, problems = [], []
    imap = _imap_connect(email_addr, password)
    try:
        mapping = _discover_mailboxes(imap)
        raw = _resolve_mailbox(imap, folder, mapping)
        typ, _ = imap.select(_mb_arg(raw), readonly=True)
        if typ != "OK":
            return [], [f"{folder}: could not be opened on the server."]
        crit = ["ALL"]
        if min_hours and min_hours > 0:
            cut = (datetime.now() - timedelta(hours=float(min_hours))
                   + timedelta(days=1)).date()
            crit = ["BEFORE", cut.strftime("%d-%b-%Y")]
        typ, data = imap.uid("SEARCH", None, *crit)
        if typ != "OK":
            return [], [f"{folder}: the server refused to list it."]
        uids = [u.decode() for u in (data[0].split() if data and data[0] else [])]
        if not uids:
            return [], []
        if len(uids) > cap:
            problems.append(f"{folder} holds {len(uids)} messages; the "
                            f"{cap} oldest were looked at this time.")
            uids = uids[:cap]
        typ, fetched = imap.uid(
            "FETCH", ",".join(uids),
            "(UID FLAGS INTERNALDATE "
            "BODY.PEEK[HEADER.FIELDS (SUBJECT FROM)])")
        if typ != "OK":
            return [], [f"{folder}: the server refused to describe it."]
        for entry in (fetched or []):
            if not isinstance(entry, tuple) or len(entry) < 2:
                continue
            meta, raw_hdr = entry[0] or b"", entry[1]
            um = _re.search(rb"UID (\d+)", meta)
            if not um:
                continue
            fm = _re.search(rb"FLAGS \(([^)]*)\)", meta)
            flags = (fm.group(1) if fm else b"").decode("ascii", "replace").lower()
            ts = 0
            try:
                tt = imaplib.Internaldate2tuple(meta)
                if tt:
                    ts = time.mktime(tt)
            except Exception:
                ts = 0
            subj, sender = "", ""
            try:
                hdr = _email.message_from_bytes(raw_hdr or b"")
                subj   = _dh(hdr.get("Subject", "") or "")
                sender = _dh(hdr.get("From", "") or "")
            except Exception:
                pass
            items.append({"uid": um.group(1).decode(), "ts": ts,
                          "seen": "\\seen" in flags,
                          "flagged": "\\flagged" in flags,
                          "subject": subj, "sender": sender})
    except Exception as e:
        log.error("Age scan failed %s/%s: %s", email_addr, folder, e)
        problems.append(f"{folder}: {e}")
    finally:
        try:
            imap.logout()
        except Exception:
            pass
    return items, problems


# ******************************************************************************
# DEL 04m — SAVED SEARCHES: a search you can keep, as if it were a folder
# ******************************************************************************
#
# "Everything from the accountant, wherever it is" is a question you ask again
# and again. Saving it turns the answer into a folder in the sidebar — the
# machinery for virtual folders (Notes, Snoozed, Follow-ups) already exists,
# so this is mostly a matter of remembering the question.
#
# A saved search is a FILTER, not a copy: it is re-evaluated every time you
# open it, so it always shows the truth rather than a stale snapshot.

_SEARCHES_F = os.path.join(_ACCOUNTS_DIR, "searches.json")

_SEARCH_DEFAULTS = {
    "id": "", "name": "", "query": "", "from": "", "subject": "",
    "folder": "",            # "" = every folder
    "tag": "",               # tag id
    "unread_only": False, "has_attachment": False,
    "scope": "loaded",       # "loaded" | "archive" | "both"
    "created": "",
}


def _load_searches() -> dict:
    store = _load_json_store(_SEARCHES_F, {"searches": list}, "saved searches")
    for s in store.get("searches", []):
        for k, v in _SEARCH_DEFAULTS.items():
            s.setdefault(k, v)
        if not s.get("id"):
            s["id"] = _new_id()
    return store


def _save_searches(store: dict):
    _save_json_store(_SEARCHES_F, store, "saved searches")


def _search_matches(search: dict, msg: dict, tag_store=None) -> bool:
    """Does one message satisfy a saved search?"""
    q = (search.get("query") or "").strip().lower()
    if q:
        hay = " ".join(str(msg.get(k, "")) for k in
                       ("subject", "from", "from_name", "body"))
        if q not in hay.lower():
            return False
    for key, field in (("from", "from"), ("subject", "subject")):
        needle = (search.get(key) or "").strip().lower()
        if needle:
            hay = (str(msg.get(field, "")) + " " +
                   str(msg.get("from_name", ""))).lower()
            if needle not in hay:
                return False
    folder = (search.get("folder") or "").strip()
    if folder and folder != msg.get("_folder", ""):
        return False
    if search.get("unread_only") and not msg.get("unread"):
        return False
    if search.get("has_attachment") and not msg.get("attachments"):
        return False
    tag_id = (search.get("tag") or "").strip()
    if tag_id:
        if tag_store is None:
            return False
        if tag_id not in {t["id"] for t in _tags_of(tag_store, msg)}:
            return False
    return True


def _search_describe(search: dict) -> str:
    bits = []
    for label, key in (("text", "query"), ("from", "from"),
                       ("subject", "subject"), ("folder", "folder")):
        val = (search.get(key) or "").strip()
        if val:
            bits.append(f"{label}: {val}")
    if search.get("unread_only"):
        bits.append("unread only")
    if search.get("has_attachment"):
        bits.append("with attachment")
    if search.get("tag"):
        bits.append("tagged")
    return "  ·  ".join(bits) or "everything"


# ******************************************************************************
# DEL 04n — SENDER ANALYSIS: who mails you, how much, and what you ignore
# ******************************************************************************
#
# Two questions with one answer:
#   "which newsletters can I get rid of?"  (bulk unsubscribe)
#   "which ones do I never even open?"     (dead senders)
# Both are the same table — who sends, how often, and whether you read it.
#
# HOW "NEVER OPENED" IS DECIDED
# -----------------------------
# Honestly, and only from what this program can actually see: a sender is
# counted as ignored when EVERY message from them is still unread. There is
# no read-tracking beyond the mailbox's own \Seen flag, so this is a
# conservative signal — it never claims you ignored something you opened
# elsewhere, it just notices the ones that pile up untouched.


def _sender_summary(messages, blocklist=None, tag_store=None,
                    exclude_junk=True) -> list:
    """Group messages by sender. Returns rows sorted by how much they send.

    Each row: {addr, name, count, unread, bytes, first, last, unsub, sample}
    where `sample` is the newest message from that sender — the one an
    unsubscribe would be driven from."""
    rows = {}
    for m in messages:
        addr = (parseaddr(m.get("from", ""))[1] or m.get("from", "")).lower()
        if not addr:
            continue
        if exclude_junk and blocklist is not None:
            if _is_blocked(blocklist, m) or _is_local_spam(blocklist, m):
                continue
        r = rows.get(addr)
        if r is None:
            r = rows[addr] = {"addr": addr,
                              "name": m.get("from_name", "") or addr,
                              "count": 0, "unread": 0, "bytes": 0,
                              "first": "", "last": "", "unsub": False,
                              "sample": m}
        r["count"] += 1
        if m.get("unread"):
            r["unread"] += 1
        raw = m.get("_raw")
        if raw:
            r["bytes"] += len(raw)
        dt = m.get("_dt", "") or ""
        if dt:
            if not r["first"] or dt < r["first"]:
                r["first"] = dt
            if not r["last"] or dt > r["last"]:
                r["last"] = dt
                r["sample"] = m          # newest wins as the sample
        if not r["unsub"]:
            u = _find_unsubscribe(m)
            if u.get("mailto") or u.get("http"):
                r["unsub"] = True
    out = list(rows.values())
    for r in out:
        # "Ignored" = you have opened none of them, and there are enough of
        # them for that to mean something.
        r["ignored"] = (r["count"] >= 3 and r["unread"] == r["count"])
        r["days_since"] = ""
        last = _parse_msg_dt(r["last"]) if r["last"] else None
        if last:
            r["days_since"] = (datetime.now() - last).days
    out.sort(key=lambda r: (-r["count"], r["addr"]))
    return out


def _archive_size_report(base_dir: str) -> dict:
    """Totals per year and per month, straight from the archive's own folder
    names (account/folder/YYYY-MM/*.eml).

    No message is opened: the layout already carries the dates, so this stays
    instant even on an archive with years in it."""
    report = {"years": {}, "months": {}, "accounts": {}, "folders": {},
              "files": 0, "bytes": 0}
    try:
        if not os.path.isdir(base_dir):
            return report
        for root_, _dirs, names in os.walk(base_dir):
            eml = [n for n in names if n.lower().endswith(".eml")]
            if not eml:
                continue
            rel = os.path.relpath(root_, base_dir).split(os.sep)
            account = rel[0] if len(rel) > 0 else "?"
            folder  = rel[1] if len(rel) > 1 else "?"
            month   = rel[2] if len(rel) > 2 else "undated"
            year    = month[:4] if _re.match(r"^\d{4}-\d{2}$", month) else "undated"
            size = 0
            for n in eml:
                try:
                    size += os.path.getsize(os.path.join(root_, n))
                except OSError:
                    pass
            for bucket, key in (("years", year), ("months", month),
                                ("accounts", account), ("folders", folder)):
                cur = report[bucket].setdefault(key, {"files": 0, "bytes": 0})
                cur["files"] += len(eml)
                cur["bytes"] += size
            report["files"] += len(eml)
            report["bytes"] += size
    except Exception as e:
        log.warning("Size report failed: %s", e)
    return report


# ******************************************************************************
# DEL 04o — BROWSER PROFILES: open a link with the right login
# ******************************************************************************
#
# WhyBrowse (the sister program in this folder) keeps several PROFILES, each
# with its own cookies and logins — one per Gmail account. So a link in a mail
# that arrived at gotanetreserv@… should open in the gotanetreserv profile,
# already logged in as that identity, instead of landing in profile 1 as
# whoever you happened to be last.
#
# HOW IT WORKS
#   F(re)email launches:   WhyBrowse.exe --profile=<id> "<url>"
#   WhyBrowse reads that flag (get_launch_profile) and, if it is already
#   running, forwards "profile<TAB>url" to the running window over its local
#   pipe. Both sides fall back cleanly: no profile, or an unknown one, behaves
#   exactly as before.
#
# It is deliberately generic — "browser command + profile flag" — so it works
# with anything that takes a profile on the command line (Chrome's
# --profile-directory=, Firefox's -P) rather than being welded to WhyBrowse.
#
# WHY CLICKING A LINK USED TO TAKE SECONDS  (fixed 2026-08-08)
#   Handing the URL to Windows, or launching the browser command above, starts
#   a WHOLE SECOND BROWSER PROCESS whose only job is to say "open this" to the
#   window that is already on screen — and then quit. For WhyBrowse that means
#   loading Qt and Chromium first (and, as a one-file .exe, unpacking ~200 MB
#   into a temp folder) every single time you click a link. Seconds, for four
#   words of text.
#
#   So we now write the link STRAIGHT INTO the pipe of the WhyBrowse that is
#   already running (see _handoff_to_running_browser). No process is started,
#   nothing is unpacked, and the tab appears in about a millisecond. Launching
#   a browser is only the fallback for when none is running.
#
#   Note that this is about the LAUNCH, not the lookup: typing the browser's
#   path in by hand (instead of letting Windows work out the default) saves
#   well under a millisecond on its own. It is worth doing anyway — it is what
#   tells us WHERE to look for the pipe — but it was never where the wait came
#   from.

_BROWSERPROFILES_F = os.path.join(_ACCOUNTS_DIR, "browser_profiles.json")

_BROWSER_DEFAULTS = {
    "browser_path": "",          # empty = find WhyBrowse next to this program
    "profile_flag": "--profile={profile}",
    "map": dict,                 # account_email -> profile id/name
    "default_profile": "",       # used when an account has no mapping
    "enabled": True,
    # Push the link straight into the browser that is already open, instead of
    # starting a second copy of it just to pass the address along. This is the
    # whole difference between "instant" and "several seconds".
    "direct_handoff": True,
    # The escape hatch: ignore everything above and let Windows decide, exactly
    # as the program behaved before any of this existed.
    "system_default": False,
}


def _load_browser_profiles() -> dict:
    return _load_json_store(_BROWSERPROFILES_F, _BROWSER_DEFAULTS,
                            "browser profiles")


def _save_browser_profiles(store: dict):
    _save_json_store(_BROWSERPROFILES_F, store, "browser profiles")


def _browser_folders() -> list:
    """The folders WhyBrowse could be installed in, most likely first.

    Everything here — the pipe name, the .exe, the .py — hangs off the folder
    the browser lives in, so this one list feeds both the "launch it" and the
    "talk to the one that is running" paths."""
    here = _BASE_DIR
    parent = os.path.dirname(here)
    out, seen = [], set()
    # Py\ and Folder-exe\WhyBrowse\ come from the 0---Python layout, where the
    # home folder holds Helpfiles and the programs sit one level down. In the
    # old layout those two do not exist and the list is unchanged.
    for folder in (_own_dir(), here, os.path.join(here, "Py"),
                   os.path.join(here, "Folder-exe", "WhyBrowse"),
                   parent, os.path.join(parent, "Py"),
                   os.path.join(here, "2026-07-18"),
                   os.path.join(parent, "2026-07-18")):
        f = os.path.normpath(folder)
        if f not in seen and os.path.isdir(f):
            seen.add(f)
            out.append(f)
    return out


def _guess_browser_path() -> str:
    """Find WhyBrowse next to this program, since that is where it lives.

    The .py comes first when we are running from source, because that is what
    Issu actually has open (the window is a pythonw process) and starting the
    matching one keeps a single browser with a single set of logins. A frozen
    F(re)email has no interpreter to run a .py with, so there the .exe wins."""
    names = (("WhyBrowse.exe", "WhyBrowse.py") if getattr(sys, "frozen", False)
             else ("WhyBrowse.py", "WhyBrowse.exe"))
    for folder in _browser_folders():
        for name in names:
            p = os.path.join(folder, name)
            if os.path.isfile(p):
                return p
    return ""


# ── The fast path: talk to the browser that is ALREADY open ───────────────────
#
# WhyBrowse listens on a Windows named pipe whose name is an md5 of its own
# folder, and (since 2026-08-08) writes that name into
#     <browser folder>/Helpfiles/WhyBrowse/ipc.json
# precisely so that another program does not have to reproduce the hash. Push
# "profile<TAB>url" (or just "url") into that pipe and the tab opens in the
# window that is already on screen. No process is launched at all.

def _whybrowse_pipe_names(folder: str) -> list:
    """Pipe names a WhyBrowse living in `folder` could be listening on."""
    names, seen = [], set()

    def _add(n):
        if n and n not in seen:
            seen.add(n)
            names.append(n)

    try:                                   # what the running browser says
        with open(os.path.join(folder, "Helpfiles", "WhyBrowse", "ipc.json"),
                  "r", encoding="utf-8") as f:
            _add((json.load(f) or {}).get("pipe", ""))
    except Exception:
        pass
    # Fallback for an older WhyBrowse that does not publish ipc.json yet: the
    # md5 of the folder, in the capitalisations Windows hands paths back with.
    for variant in (folder, os.path.normpath(folder),
                    folder[:1].upper() + folder[1:],
                    folder[:1].lower() + folder[1:]):
        try:
            _add("WhyBrowse_ipc_" +
                 hashlib.md5(variant.encode("utf-8")).hexdigest())
        except Exception:
            pass
    return names


def _pipe_write(pipe_name: str, payload: str, timeout_ms=300):
    """Write `payload` into a local named pipe.

    Returns (ok, note). `note` is there so a failure can SAY something useful
    instead of silently falling back — "access denied" in particular means the
    browser is running with different privileges (one of the two was started
    as administrator), which no amount of retrying will fix."""
    if os.name != "nt":
        return False, "not Windows"
    path = r"\\.\pipe\%s" % pipe_name
    GENERIC_WRITE, OPEN_EXISTING = 0x40000000, 3
    ERROR_FILE_NOT_FOUND, ERROR_ACCESS_DENIED, ERROR_PIPE_BUSY = 2, 5, 231
    try:
        import ctypes
        k32 = ctypes.windll.kernel32
        k32.CreateFileW.argtypes = [ctypes.c_wchar_p, ctypes.c_uint32,
                                    ctypes.c_uint32, ctypes.c_void_p,
                                    ctypes.c_uint32, ctypes.c_uint32,
                                    ctypes.c_void_p]
        k32.CreateFileW.restype = ctypes.c_void_p
        k32.WriteFile.argtypes = [ctypes.c_void_p, ctypes.c_char_p,
                                  ctypes.c_uint32,
                                  ctypes.POINTER(ctypes.c_uint32),
                                  ctypes.c_void_p]
        invalid = ctypes.c_void_p(-1).value
        deadline = time.time() + (timeout_ms / 1000.0)
        while True:
            h = k32.CreateFileW(path, GENERIC_WRITE, 0, None,
                                OPEN_EXISTING, 0, None)
            if h and h != invalid:
                break
            err = k32.GetLastError()
            if err == ERROR_PIPE_BUSY and time.time() < deadline:
                k32.WaitNamedPipeW(path, 100)   # it IS there, just busy
                continue
            if err == ERROR_ACCESS_DENIED:
                return False, ("the running browser was started with "
                               "different privileges (run as administrator?)")
            if err == ERROR_FILE_NOT_FOUND:
                return False, "not running"
            return False, "Windows error %d" % err
        try:
            if payload is None:                 # ping: connect, send nothing
                return True, "reachable"
            data = payload.encode("utf-8")
            written = ctypes.c_uint32(0)
            ok = bool(k32.WriteFile(ctypes.c_void_p(h), data, len(data),
                                    ctypes.byref(written), None))
            k32.FlushFileBuffers(ctypes.c_void_p(h))
            if ok and written.value == len(data):
                return True, "handed over"
            return False, "the browser accepted the connection but not the link"
        finally:
            k32.CloseHandle(ctypes.c_void_p(h))
    except Exception as e:
        return False, "%s: %s" % (type(e).__name__, e)


def _handoff_to_running_browser(store: dict, url: str, profile: str,
                                ping_only=False):
    """Hand `url` to the WhyBrowse that is already open.

    Returns (ok, note, milliseconds). Every candidate that is not listening
    fails in a fraction of a millisecond, so guessing wrong costs nothing."""
    t0 = time.time()
    folders, seen = [], set()
    for cand in ([os.path.dirname((store.get("browser_path") or "").strip())] +
                 [os.path.dirname(_guess_browser_path())] + _browser_folders()):
        if cand and os.path.isdir(cand) and cand not in seen:
            seen.add(cand)
            folders.append(cand)
    payload = None if ping_only else \
        (("%s\t%s" % (profile, url)) if profile else url)
    note = "no browser folder to look in"
    for folder in folders:
        for name in _whybrowse_pipe_names(folder):
            ok, note = _pipe_write(name, payload)
            if ok:
                return True, note, (time.time() - t0) * 1000.0
            if "privileges" in note:      # found it, but we may not write to it
                return False, note, (time.time() - t0) * 1000.0
    return False, note, (time.time() - t0) * 1000.0


def _links_in_message(msg: dict, limit=25) -> list:
    """The web links in a message, de-duplicated, in the order they appear."""
    text = (msg.get("body") or "")
    html = (msg.get("_html") or "")
    found, seen = [], set()
    for url in _URL_RE.findall(text) + [h for h, _t in _HREF_RE.findall(html)]:
        url = _htmllib.unescape(url).rstrip('.,);"\'')
        if not url.lower().startswith(("http://", "https://")):
            continue
        if url in seen:
            continue
        seen.add(url)
        found.append(url)
        if len(found) >= limit:
            break
    return found


def _profile_for_account(store: dict, account_email: str) -> str:
    """Which browser profile belongs to this Gmail account."""
    if not store.get("enabled", True):
        return ""
    mapping = store.get("map") or {}
    return (mapping.get(account_email or "")
            or mapping.get((account_email or "").lower())
            or store.get("default_profile", "") or "")


def _browser_command(store: dict, url: str, profile: str) -> list:
    """Build the command line to open `url`, or [] to mean "system default".

    An empty Browser field no longer means "ask Windows" — it means "find
    WhyBrowse yourself", because handing the address to Windows only leads
    back to the same browser the long way round. Tick "always use the Windows
    default browser" in the dialog if you really want the old behaviour."""
    if store.get("system_default"):
        return []
    path = (store.get("browser_path") or "").strip()
    if not path:
        path = _guess_browser_path()
    if not path or not os.path.isfile(path):
        return []
    cmd = []
    if path.lower().endswith(".py"):
        exe = sys.executable or "python.exe"
        pyw = exe.replace("python.exe", "pythonw.exe")
        cmd = [pyw if os.path.isfile(pyw) else exe, path]
    else:
        cmd = [path]
    if profile:
        flag = (store.get("profile_flag") or "--profile={profile}")
        # A flag may be one argument ("--profile=x") or two ("-P x").
        expanded = flag.replace("{profile}", profile)
        cmd.extend(expanded.split(" ", 1) if " " in expanded else [expanded])
    cmd.append(url)
    return cmd


# ******************************************************************************
# DEL 04p — BOUNCES, MISSING ATTACHMENTS, AND SWEDISH HOLIDAYS
# ******************************************************************************

# ── 1. Delivery failures ──────────────────────────────────────────────────────
#
# A bounce arrives as a cryptic machine-written message from a name you do not
# recognise, burying the one fact you need — WHICH mail failed and WHY — under
# a wall of headers. This finds both and says them in plain words, with the
# common causes spelled out, because "550 5.1.1" means nothing to anyone.

_BOUNCE_SENDERS = ("mailer-daemon", "postmaster", "mail delivery subsystem",
                   "mail delivery system", "no-reply@dropbox")
_BOUNCE_SUBJECTS = ("undelivered mail returned to sender",
                    "delivery status notification (failure)",
                    "mail delivery failed", "returned mail",
                    "delivery has failed", "undeliverable",
                    "message not delivered", "olevererbart")

# SMTP codes worth translating, and what to actually DO about them.
_BOUNCE_CAUSES = [
    (r"5\.1\.1|550[- ].*(user unknown|no such user|does not exist|"
     r"recipient not found|address rejected)",
     "The address does not exist",
     "A typo, or the account is gone. Check the spelling against the "
     "address book, and if it looks right, ask them another way."),
    (r"5\.2\.2|552|mailbox full|quota exceeded|over quota",
     "Their mailbox is full",
     "Nothing you can fix — they must clear space. Try again in a few days, "
     "or reach them another way."),
    (r"5\.7\.1|550[- ].*(spam|blocked|blacklist|policy|not allowed)|"
     r"554[- ].*(spam|reject)",
     "Their mail server refused it as spam",
     "Often a link or an attachment type. Try again with fewer links, no "
     "attachment, and plain wording — or ask them to whitelist you."),
    (r"5\.4\.4|dns|host not found|domain not found|unrouteable|unrouteable",
     "The domain does not exist",
     "The part after the @ is wrong, or the domain has expired."),
    (r"4\.\d\.\d|451|452|greylist|try again later|temporar",
     "A temporary problem — it may still arrive",
     "The receiving server asked us to try later. Most servers retry for a "
     "day or two by themselves."),
    (r"message too large|5\.3\.4|552[- ].*size",
     "The message was too big",
     "Send the attachment as a link instead, or split it up. Gmail's own "
     "limit is 25 MB, and many company servers are stricter."),
    (r"5\.7\.26|dmarc|spf|dkim",
     "The sender could not be verified (SPF/DKIM/DMARC)",
     "Usually means the mail was sent through the wrong server. If this "
     "keeps happening, the account's app password or SMTP settings are the "
     "place to look."),
]


def _is_bounce(msg: dict) -> bool:
    frm  = ((msg.get("from") or "") + " " +
            (msg.get("from_name") or "")).lower()
    subj = (msg.get("subject") or "").lower()
    if any(s in frm for s in _BOUNCE_SENDERS):
        return True
    return any(s in subj for s in _BOUNCE_SUBJECTS)


def _bounce_details(msg: dict) -> dict:
    """{"recipient", "cause", "advice", "code"} — what failed and what to do."""
    body = (msg.get("body") or "")[:4000]
    low  = body.lower()
    out  = {"recipient": "", "cause": "", "advice": "", "code": ""}

    # The address that failed, as most servers report it.
    for pat in (r"(?:final-recipient|original-recipient)\s*:\s*[^;\n]*;\s*"
                r"([^\s<>]+@[^\s<>]+)",
                r"<([^\s<>]+@[^\s<>]+)>[^\n]{0,40}(?:failed|rejected|"
                r"not found|unknown)",
                r"(?:to|recipient)\s*:?\s*<?([\w.+-]+@[\w.-]+\.\w+)>?"):
        m = _re.search(pat, body, _re.I)
        if m:
            out["recipient"] = m.group(1).strip()
            break

    m = _re.search(r"\b([45]\.\d\.\d|[45]\d\d)\b", body)
    if m:
        out["code"] = m.group(1)

    for pattern, cause, advice in _BOUNCE_CAUSES:
        if _re.search(pattern, low, _re.I):
            out["cause"], out["advice"] = cause, advice
            break
    if not out["cause"]:
        out["cause"] = "The message could not be delivered"
        out["advice"] = ("The server did not give a reason this program "
                         "recognises — the full text below has the details.")
    return out


def _bounce_recover(msg: dict) -> dict:
    """Best-effort reconstruction of the ORIGINAL message from a bounce, so it
    can be fixed and resent (Issu 2026-08-01). Returns {to, cc, subject, body}.

    A delivery-status bounce usually carries the original as a message/rfc822
    (or text/rfc822-headers) part; the recipient/subject/body are read from
    there. Falls back to _bounce_details + the cleaned bounce subject when the
    original is not embedded."""
    import email as _email
    out = {"to": "", "cc": "", "subject": "", "body": ""}
    raw = msg.get("_raw")
    orig = None
    if raw:
        try:
            top = _email.message_from_bytes(raw)
            for part in top.walk():
                ctype = part.get_content_type()
                if ctype == "message/rfc822":
                    cte = (part.get("Content-Transfer-Encoding") or "").lower()
                    payload = part.get_payload()
                    if cte in ("base64", "quoted-printable"):
                        # Some MTAs base64/QP-encode the embedded original
                        # instead of including it verbatim (7bit). The parser
                        # then mis-reads the still-encoded text as a bogus
                        # sub-message whose "body" IS the raw encoded text — so
                        # take that, decode it, and parse the REAL original from
                        # it. Otherwise the subject/body came back as a base64
                        # blob (Issu wanted the retry to carry "exakt samma
                        # rubrik och meddelande").
                        enc = ""
                        if isinstance(payload, list) and payload:
                            first = payload[0]
                            enc = (first.get_payload()
                                   if hasattr(first, "get_payload") else "")
                        elif isinstance(payload, str):
                            enc = payload
                        try:
                            import base64 as _b64, quopri as _qp
                            raw_orig = (_b64.b64decode(enc or "")
                                        if cte == "base64"
                                        else _qp.decodestring((enc or "").encode()))
                            orig = _email.message_from_bytes(raw_orig)
                        except Exception:
                            orig = None
                    elif isinstance(payload, list) and payload:
                        orig = payload[0]
                    elif hasattr(payload, "walk"):
                        orig = payload
                    if orig is not None:
                        break
                if ctype == "text/rfc822-headers" and orig is None:
                    try:
                        orig = _email.message_from_bytes(
                            part.get_payload(decode=True) or b"")
                    except Exception:
                        pass
        except Exception as e:
            log.debug("bounce recover parse failed: %s", e)
    if orig is not None:
        out["to"]      = _dh(orig.get("To", "") or "")
        out["cc"]      = _dh(orig.get("Cc", "") or "")
        out["subject"] = _dh(orig.get("Subject", "") or "")
        try:
            if orig.is_multipart():
                for p in orig.walk():
                    if p.get_content_type() == "text/plain":
                        out["body"] = (p.get_payload(decode=True) or b"").decode(
                            p.get_content_charset() or "utf-8", "replace")
                        break
            else:
                out["body"] = (orig.get_payload(decode=True) or b"").decode(
                    orig.get_content_charset() or "utf-8", "replace")
        except Exception:
            pass
    if not out["to"]:
        out["to"] = _bounce_details(msg).get("recipient", "")
    if not out["subject"]:
        s = msg.get("subject", "") or ""
        s = _re.sub(r"^(?:undeliverable|delivery (?:status notification|failure|"
                    r"has failed)|mail delivery (?:failed|subsystem)|returned "
                    r"mail|failure notice)\s*[:\-]?\s*", "", s, flags=_re.I).strip()
        out["subject"] = s
    return out


# ── 2. An attachment that never arrived ───────────────────────────────────────

def _promised_attachment_missing(msg: dict) -> str:
    """The sender wrote about an attachment, but none came. Returns the phrase.

    The same detector used on your OWN outgoing mail, pointed the other way —
    so you can ask them straight away instead of noticing a day later.
    Forwarded and quoted mail is excluded: "see attached" inside a quote is
    about the ORIGINAL message, not this one."""
    if msg.get("attachments"):
        return ""
    subject = msg.get("subject", "") or ""
    if subject.lower().startswith(("fwd:", "fw:", "vb:")):
        return ""
    return _mentions_attachment(subject, msg.get("body", "") or "")


# ── 3. Swedish public holidays ────────────────────────────────────────────────
#
# The calendar is used by someone in Sweden, so the days that are actually
# free should look free. Most are fixed; the rest hang off Easter, which
# moves. Anonymous Gregorian algorithm — the standard one, exact for any year.

def _easter_sunday(year: int):
    a = year % 19
    b, c = divmod(year, 100)
    d, e = divmod(b, 4)
    f = (b + 8) // 25
    g = (b - f + 1) // 3
    h = (19 * a + b - d - g + 15) % 30
    i, k = divmod(c, 4)
    l = (32 + 2 * e + 2 * i - h - k) % 7
    m = (a + 11 * h + 22 * l) // 451
    month, day = divmod(h + l - 7 * m + 114, 31)
    return datetime(year, month, day + 1)


def _swedish_holidays(year: int) -> dict:
    """{date: name} for one year. Names are Swedish because that is what the
    days are called — this is DATA about Sweden, not program text."""
    easter = _easter_sunday(year)
    days = {
        datetime(year, 1, 1):   "Nyårsdagen",
        datetime(year, 1, 6):   "Trettondedag jul",
        datetime(year, 5, 1):   "Första maj",
        datetime(year, 6, 6):   "Sveriges nationaldag",
        datetime(year, 12, 24): "Julafton",
        datetime(year, 12, 25): "Juldagen",
        datetime(year, 12, 26): "Annandag jul",
        datetime(year, 12, 31): "Nyårsafton",
        easter - timedelta(days=2): "Långfredagen",
        easter - timedelta(days=1): "Påskafton",
        easter:                     "Påskdagen",
        easter + timedelta(days=1): "Annandag påsk",
        easter + timedelta(days=39): "Kristi himmelsfärdsdag",
        easter + timedelta(days=49): "Pingstdagen",
    }
    # Midsummer's Eve: the Friday falling 19–25 June. Midsummer Day follows.
    for d in range(19, 26):
        cand = datetime(year, 6, d)
        if cand.weekday() == 4:
            days[cand] = "Midsommarafton"
            days[cand + timedelta(days=1)] = "Midsommardagen"
            break
    # All Saints' Day: the Saturday falling 31 Oct – 6 Nov.
    for offset in range(7):
        cand = datetime(year, 10, 31) + timedelta(days=offset)
        if cand.weekday() == 5:
            days[cand] = "Alla helgons dag"
            break
    return {d.date(): name for d, name in days.items()}


_HOLIDAY_CACHE = {}


def _holiday_name(day) -> str:
    """The holiday on a date, or "". Cached per year — the calendar asks this
    for every cell it draws."""
    try:
        d = day.date() if hasattr(day, "date") else day
        year = d.year
        if year not in _HOLIDAY_CACHE:
            _HOLIDAY_CACHE[year] = _swedish_holidays(year)
            if len(_HOLIDAY_CACHE) > 12:
                _HOLIDAY_CACHE.pop(next(iter(_HOLIDAY_CACHE)))
        return _HOLIDAY_CACHE[year].get(d, "")
    except Exception:
        return ""


# ******************************************************************************
# DEL 04q — IMPORT: old mail from Thunderbird, and contacts from a .vcf
# ******************************************************************************
#
# Mail you already have should not be stranded in the program you are leaving.
# Thunderbird stores folders as MBOX files (no extension) and can export
# single messages as .eml — both of which this reads, writing them straight
# into the local archive, which is already .eml files in dated folders.
#
# Nothing is uploaded anywhere. Import is the mirror image of the archive:
# files in, files kept.


def _mbox_split(raw: bytes):
    """Yield each message in an mbox file as raw bytes.

    An mbox separates messages with a line starting "From " (no colon) at the
    very start of a line. Lines inside a body that would look like a separator
    are escaped as ">From " by the writer, and are un-escaped here."""
    if not raw:
        return
    # Normalise line endings so the separator test is simple.
    data = raw.replace(b"\r\n", b"\n")
    lines = data.split(b"\n")
    current, started = [], False
    for line in lines:
        if line.startswith(b"From ") and (not current or started):
            if current:
                yield b"\n".join(current)
                current = []
            started = True
            continue                      # the separator itself is not content
        if line.startswith(b">From "):
            line = line[1:]               # un-escape
        current.append(line)
    if current and any(l.strip() for l in current):
        yield b"\n".join(current)


def _import_mail_file(path: str) -> list:
    """Read one .eml or mbox file and return the raw messages inside it.

    The format is decided by looking at the content, not the extension:
    Thunderbird's mbox files usually have no extension at all."""
    try:
        with open(path, "rb") as f:
            raw = f.read()
    except Exception as e:
        log.warning("Could not read %s: %s", path, e)
        return []
    if not raw.strip():
        return []
    if raw.lstrip()[:5] == b"From ":
        return [m for m in _mbox_split(raw) if m.strip()]
    return [raw]


def _import_messages(cfg: dict, paths: list, account_label="",
                     folder_label="Imported", progress=None) -> dict:
    """Import mail files into the local archive.

    Returns {"files", "messages", "written", "skipped", "errors"}. Existing
    messages are skipped by the archive's own Message-ID check, so importing
    the same folder twice does not double it."""
    stats = {"files": 0, "messages": 0, "written": 0, "skipped": 0,
             "errors": []}
    for path in paths:
        stats["files"] += 1
        if progress:
            progress(os.path.basename(path), stats)
        for raw in _import_mail_file(path):
            stats["messages"] += 1
            try:
                em = _email.message_from_bytes(raw)
                msg = _build_msg_dict(em, [b"\\Seen"], None, None,
                                      account_label or "imported",
                                      folder_label, "")
                msg["_raw"] = raw
                if _archive_message(cfg, msg):
                    stats["written"] += 1
                else:
                    stats["skipped"] += 1
            except Exception as e:
                stats["errors"].append(f"{os.path.basename(path)}: {e}")
                log.warning("Import failed for one message in %s: %s", path, e)
    return stats


# ── vCard (.vcf) contacts ─────────────────────────────────────────────────────

def _vcard_parse(text: str) -> list:
    """Contacts from a .vcf file: [{"name", "email", "group"}, ...].

    Handles the parts that matter — FN, N, EMAIL (with any TYPE= parameters),
    ORG for the group — plus RFC 6350 line folding, where a line beginning
    with a space continues the previous one. A card with no e-mail address is
    skipped: this is an address book for mail."""
    people, cur = [], None
    lines = []
    for raw in (text or "").replace("\r\n", "\n").split("\n"):
        if raw[:1] in (" ", "\t") and lines:
            lines[-1] += raw[1:]
        else:
            lines.append(raw)

    for line in lines:
        up = line.upper().strip()
        if up.startswith("BEGIN:VCARD"):
            cur = {"name": "", "email": "", "group": ""}
            continue
        if up.startswith("END:VCARD"):
            if cur and cur["email"]:
                if not cur["name"]:
                    cur["name"] = cur["email"].split("@")[0]
                people.append(cur)
            cur = None
            continue
        if cur is None or ":" not in line:
            continue
        name_part, _sep, value = line.partition(":")
        prop = name_part.split(";")[0].upper()
        value = value.strip()
        if not value:
            continue
        if prop == "FN":
            cur["name"] = value
        elif prop == "N" and not cur["name"]:
            # "Surname;First;;;" -> "First Surname"
            bits = [b.strip() for b in value.split(";")]
            cur["name"] = " ".join(x for x in (bits[1:2] + bits[0:1]) if x)
        elif prop == "EMAIL" and not cur["email"]:
            cur["email"] = value.split(",")[0].strip()
        elif prop == "ORG" and not cur["group"]:
            cur["group"] = value.split(";")[0].strip()
    return people


def _merge_contacts(store: dict, people: list) -> int:
    """Add contacts, skipping addresses already known. Returns how many were
    new — the same de-duplicating manners as the calendar import.

    Addresses are CLEANED on the way in (Issu 2026-08-01). This is where mail
    from outside lands — a vCard, a CSV export, or the auto-save of someone you
    just wrote to — and a corrupt address stored here would come back on every
    future message to that person, through autocomplete and the picker, long
    after the original slip."""
    have = {(p.get("email") or "").lower()
            for p in store.get("people", [])}
    never = store.get("never_save", [])
    added = 0
    blocked = 0
    for p in people:
        email = (p.get("email") or "").strip()
        if email:
            clean, changed = _clean_one_address(email)
            if changed:
                log.error("ADDRESS CORRUPTION [address book]: %r → %r    %s",
                          email, clean, _addr_forensics(email))
            email = (parseaddr(clean)[1] or clean).strip()
        if not email or email.lower() in have:
            continue
        # Never-save list (Issu 2026-08-25). Checked HERE, the one door every
        # automatic contact comes through: auto-save on reply/send, a vCard,
        # a CSV export. A blocked address is not an error — it is the list
        # doing its job — so it is logged quietly, once per address.
        rule = _never_save_match(email, never)
        if rule:
            blocked += 1
            log.info("Contact not saved (never-save %s %r): %s",
                     rule.get("kind"), rule.get("value"), email)
            continue
        store.setdefault("people", []).append({
            "name": p.get("name", "") or email,
            "email": email,
            "group": p.get("group", ""),
        })
        have.add(email.lower())
        added += 1
    if added:
        _save_addressbook(store)
    return added


def _csv_contacts_parse(text: str) -> list:
    """Contacts from a CSV export (Thunderbird / Google / Outlook): a list of
    {"name", "email"} (Issu 2026-08-01).

    Thunderbird's Address Book → Export → CSV writes a header row; the columns
    vary by language and version, so the email and name columns are found by
    matching the HEADER names rather than fixed positions."""
    import csv, io
    out = []
    try:
        # Sniff the delimiter (Thunderbird uses ',', some locales ';').
        sample = text[:2000]
        try:
            dialect = csv.Sniffer().sniff(sample, delimiters=",;\t")
        except Exception:
            dialect = csv.excel
        reader = csv.reader(io.StringIO(text), dialect)
        rows = list(reader)
    except Exception as e:
        log.warning("CSV parse failed: %s", e)
        return out
    if not rows:
        return out
    header = [h.strip().lower() for h in rows[0]]

    def _find(*keys, exclude=()):
        # Key-major: try the most specific key first, across every column, so
        # "display name" wins over a bare "name" that would also hit "first
        # name". `exclude` skips columns whose header contains any excluded word.
        for k in keys:
            for i, h in enumerate(header):
                if k in h and not any(x in h for x in exclude):
                    return i
        return -1

    # Prefer a "primary email" column, then any column mentioning e-mail.
    # Swedish Thunderbird writes "Primär e-post", "Visningsnamn", "Förnamn",
    # "Efternamn" (Issu exports from a Swedish Thunderbird) — matched here so a
    # Swedish export gets the proper display name instead of falling back to
    # crude @-detection with a first-name-only label.
    i_email = _find("primary email", "primär e-post", "e-mail address",
                    "email address", "e-postadress", "e-post", "epost",
                    "e-mail", "email", "mail")
    i_disp  = _find("display name", "visningsnamn", "full name",
                    "name", "namn",
                    exclude=("first", "last", "given", "surname",
                             "family", "file", "nick",
                             "förnamn", "efternamn", "smeknamn"))
    i_first = _find("first name", "förnamn", "given")
    i_last  = _find("last name", "efternamn", "surname", "family")

    # If no header row was recognised, treat the whole file as "email[,name]".
    header_is_data = (i_email == -1)
    data_rows = rows if header_is_data else rows[1:]

    for row in data_rows:
        if not row:
            continue
        if header_is_data:
            # Find the first cell that looks like an address.
            email = next((c.strip() for c in row
                          if "@" in c and "." in c.split("@")[-1]), "")
            name = next((c.strip() for c in row if c.strip() and c.strip() != email), "")
        else:
            email = row[i_email].strip() if 0 <= i_email < len(row) else ""
            name = ""
            if 0 <= i_disp < len(row) and row[i_disp].strip():
                name = row[i_disp].strip()
            else:
                first = row[i_first].strip() if 0 <= i_first < len(row) else ""
                last  = row[i_last].strip()  if 0 <= i_last  < len(row) else ""
                name = (first + " " + last).strip()
        if email and "@" in email:
            out.append({"name": name or email, "email": email})
    return out


# ******************************************************************************
# DEL 05 — MOCK DATA  (used only in DEMO mode — no account configured yet)
# ******************************************************************************

def _mock_accounts():
    """Return placeholder account list until OAuth is wired up.

    The first entry is always the virtual 'All Accounts' aggregate.
    Real accounts follow.  Claude Code: replace the real entries with
    whatever OAuth returns; keep ALL_ACCOUNTS_ID as the first element.
    """
    return [
        # ── Virtual aggregate — always first ────────────────────────────────
        {
            "email":   ALL_ACCOUNTS_ID,
            "name":    "All Accounts",
            "unread":  15,           # TODO (Claude Code): sum across real accounts
            "virtual": True,
            "default_sender": "you@gmail.com",   # default From: when composing here
        },
        # ── Real accounts (mock until OAuth) ────────────────────────────────
        {"email": "you@gmail.com",  "name": "Your Name",    "unread": 3,  "virtual": False},
        {"email": "work@gmail.com", "name": "Work Account", "unread": 12, "virtual": False},
    ]

# "Snoozed" is a VIRTUAL folder — it is not an IMAP mailbox, it is simply the
# local snooze list rendered as if it were one (DEL 04d).
# "Snoozed" and "Notes" are VIRTUAL — they are not IMAP mailboxes. Snoozed is
# the local snooze list; Notes is a folder of .eml files on your own disk that
# no server ever sees (DEL 04g).
_FOLDERS = ["Inbox", "Notes", "Follow-ups", "Snoozed", "Starred", "Sent",
            "Drafts", "Spam", "Trash", "All Mail", "Deleted"]
_VIRTUAL_FOLDERS = {"Snoozed", "Notes", "Follow-ups", "Deleted"}

_FOLDER_ICONS = {"Inbox": "📥", "Starred": "⭐", "Sent": "📤", "Drafts": "📝",
                 "Spam": "⚠", "Trash": "🗑", "All Mail": "🗂", "Notes": "🗒",
                 "Snoozed": "⏰", "Follow-ups": "🔔", "Deleted": "♻"}

# COMPACT sidebar: the non-Inbox standard folders, grouped into rows that render
# side-by-side in columns to save vertical space (default on; toggle in View).
# Every non-Inbox entry of _FOLDERS must appear here exactly once.
# (Notes rides on the Inbox row itself — see _populate_sidebar — so it is not
# listed here.)
_COMPACT_ROWS = [["Sent", "Drafts"],
                 ["Spam", "Trash", "Deleted"],
                 ["Starred", "All Mail"],
                 ["Follow-ups", "Snoozed"]]

# Thunderbird (and some IMAP setups) leave DUPLICATE custom folders that mean
# the same thing as a standard one — "Junk"=Spam, "Skickat"=Sent, "Utkast"=
# Drafts, "Papperskorg"=Trash. With "Merge duplicate folders" on (default) a
# custom folder whose leaf name matches one of these is hidden, since the real
# Gmail folder it duplicates is already shown. Keys are lower-case leaf names.
_DUP_FOLDER_ALIASES = {
    "junk": "Spam", "skräppost": "Spam", "skrappost": "Spam", "spam": "Spam",
    "skickat": "Sent", "skickade": "Sent", "sent": "Sent", "sent mail": "Sent",
    "utkast": "Drafts", "drafts": "Drafts",
    "papperskorg": "Trash", "borttaget": "Trash", "trash": "Trash",
    "deleted items": "Trash", "deleted messages": "Trash",
    "arkiv": "All Mail", "archive": "All Mail", "all mail": "All Mail",
}

# Message-list column layout — shared by the header row and every data row
# so they can never drift out of alignment. All columns are left-aligned;
# (header_text, column_index, minsize_px, weight)
def _thread_order(msg):
    """Chronological key for messages inside one conversation.

    Explicitly NOT the message id: with a real Gmail account the id is the
    IMAP UID as a STRING, so sorting by it puts "100" before "99" and the
    thread comes out in the wrong order — which also fed the reading pane the
    wrong "previous message" for its latest-round view."""
    return (msg.get("_sortkey", 0.0), str(msg.get("id", "")))


# A ✉ column sits between 📎 and ★ (Issu 2026-09-23): it marks a mail that
# holds an address. Adding it here shifted every column after 📎 up by one, so
# the data-row grid, the sort map and the "+" toggle index all moved with it —
# search for "column=" in _render_one_row and the c== ladder in _sort_key.
_MSG_COLUMNS = [
    ("📎",            0, 26,  0),
    ("✉",             1, 26,  0),
    ("★",             2, 26,  0),
    ("Subject",       3, 160, 3),
    ("+",             4, 26,  0),
    ("Correspondent", 5, 120, 2),
    ("!",             6, 26,  0),
    ("⚠",             7, 26,  0),
    ("Date",          8, 90,  0),
]

def _mock_messages(folder="Inbox", account=ALL_ACCOUNTS_ID):
    """Return placeholder messages.

    Each message now carries 'account_email' so the unified view can show
    which account it belongs to, and so Reply knows the correct From: address.

    TODO (Claude Code): replace with IMAP/Gmail API fetch per account,
    then merge+sort when account == ALL_ACCOUNTS_ID.
    """
    # Messages belonging to you@gmail.com
    msgs_personal = [
        {"id": 1, "thread_id": 1, "account_email": "you@gmail.com",
         "from": "alice@example.com", "from_name": "Alice Johnson",
         "subject": "Q3 report is ready for review",
         "date": "Today 09:14",
         "body": ("Hi,\n\nI've finished the Q3 report. "
                  "Please take a look when you have a moment.\n\n"
                  "Main highlights:\n  - Revenue up 18% YoY\n"
                  "  - Customer count: 4,201\n  - NPS improved to 67\n\n"
                  "Let me know if you need changes.\n\nBest,\nAlice"),
         "unread": True, "starred": True, "priority": "high", "spam": False,
         "attachments": []},
        {"id": 2, "thread_id": 2, "account_email": "you@gmail.com",
         "from": "bob@example.com", "from_name": "Bob Martinez",
         "subject": "Lunch tomorrow?",
         "date": "Today 08:45",
         "body": ("Hey,\n\nAre you free for lunch tomorrow around noon? "
                  "There's a new place I've been wanting to try.\n\nBob"),
         "unread": True, "starred": False, "priority": "normal", "spam": False,
         "attachments": []},
        {"id": 3, "thread_id": 3, "account_email": "you@gmail.com",
         "from": "newsletter@techdigest.io", "from_name": "Tech Digest",
         "subject": "This week in AI: GPT-5, Gemini Ultra 2, and more",
         "date": "Yesterday",
         "body": ("Your weekly roundup of the biggest AI stories.\n\n"
                  "• OpenAI releases GPT-5 with 1M context window\n"
                  "• Google Gemini Ultra 2 benchmarks leaked\n"
                  "• EU AI Act enforcement begins\n"
                  "• Meta open-sources Llama 4\n\nRead more at techdigest.io"),
         "unread": False, "starred": False, "priority": "low", "spam": False,
         "attachments": []},
        {"id": 6, "thread_id": 6, "account_email": "you@gmail.com",
         "from": "david@example.com", "from_name": "David Kim",
         "subject": "Invoice #2024-087 attached",
         "date": "Sun 14:22",
         "body": ("Hi,\n\nPlease find the invoice for last month's work attached.\n\n"
                  "Total: €1,250.00\nDue: 30 days\n\nThank you!\n\nDavid"),
         "unread": False, "starred": True, "priority": "normal", "spam": False,
         "attachments": ["invoice_2024-087.pdf"]},
    ]

    # Messages belonging to work@gmail.com
    # NOTE: The "Project Phoenix — deadline" thread (id 40 / 41 / 42,
    # thread_id 4) is deliberately interleaved with other messages below
    # (at least one unrelated message between every part of the thread).
    # This is needed for future testing — do not move the three deadline
    # messages back next to each other.
    msgs_work = [
        {"id": 40, "thread_id": 4, "account_email": "work@gmail.com",
         "from": "carol@example.com", "from_name": "Carol White",
         "subject": "Project Phoenix — deadline",
         "date": "Mon 09:10",
         "body": ("Hi all,\n\nCan we realistically hit the 10th for "
                  "Project Phoenix, or should we push the deadline?\n\nCarol"),
         "unread": False, "starred": False, "priority": "normal", "spam": False,
         "attachments": []},
        {"id": 5, "thread_id": 5, "account_email": "work@gmail.com",
         "from": "noreply@github.com", "from_name": "GitHub",
         "subject": "[freemail] Pull request #7: Add OAuth flow",
         "date": "Mon 11:05",
         "body": ("dev opened a pull request:\n\nAdd Google OAuth 2.0 login\n\n"
                  "This PR adds the Google OAuth flow.\n\nView on GitHub →"),
         "unread": True, "starred": False, "priority": "low", "spam": False,
         "attachments": []},
        {"id": 41, "thread_id": 4, "account_email": "work@gmail.com",
         "from": "you@gmail.com", "from_name": "Me",
         "subject": "Re: Project Phoenix — deadline",
         "date": "Mon 13:45",
         "body": ("Hi Carol,\n\nThe 10th looks tight given the OAuth work "
                  "still in progress. I'd suggest the 15th instead.\n\n"
                  "Thoughts?"),
         "unread": False, "starred": False, "priority": "normal", "spam": False,
         "attachments": []},
        {"id": 7, "thread_id": 7, "account_email": "work@gmail.com",
         "from": "eva@example.com", "from_name": "Eva Lindström",
         "subject": "Sprint review notes",
         "date": "Mon 09:00",
         "body": ("Hi team,\n\nAttached are the sprint review notes from Friday.\n\n"
                  "Key decisions:\n  - Feature X ships next week\n"
                  "  - Bug #441 is P1\n\nEva"),
         "unread": True, "starred": False, "priority": "normal", "spam": False,
         "attachments": ["sprint_review_notes.docx"]},
        {"id": 42, "thread_id": 4, "account_email": "work@gmail.com",
         "from": "carol@example.com", "from_name": "Carol White",
         "subject": "Re: Project Phoenix — deadline",
         "date": "Mon 16:30",
         "body": ("Absolutely, we can push it to the 15th if needed.\n\n"
                  "I'll inform the rest of the team.\n\nCarol"),
         "unread": False, "starred": False, "priority": "normal", "spam": False,
         "attachments": []},
        {"id": 8, "thread_id": 8, "account_email": "work@gmail.com",
         "from": "boss@example.com", "from_name": "The Boss",
         "subject": "Yearly review — please read",
         "date": "Sun 18:05",
         "body": ("Please read the attached review document before our meeting.\n\n"
                  "Looking forward to our discussion.\n\nBoss"),
         "unread": True, "starred": True, "priority": "high", "spam": False,
         "attachments": ["yearly_review.pdf"]},
    ]

    # Select which pool to use
    if account == ALL_ACCOUNTS_ID:
        pool = msgs_personal + msgs_work
    elif account == "work@gmail.com":
        pool = msgs_work
    else:
        pool = msgs_personal

    # Folder filtering (mock logic)
    if folder == "Sent":
        result = []
        for m in pool:
            mc = m.copy()
            mc["from_name"] = "Me"
            mc["from"]      = mc["account_email"]
            mc["subject"]   = "Re: " + mc["subject"]
            result.append(mc)
        return result
    if folder == "Spam":
        return []
    if folder == "Drafts":
        return [pool[0].copy()] if pool else []
    if folder == "Starred":
        return [m for m in pool if m.get("starred")]
    if folder == "Trash":
        return []
    # Inbox / All Mail / default
    return pool


# ******************************************************************************
# DEL 05b — SHARED RECIPIENT FIELDS (used by BOTH compose windows)
# ******************************************************************************
#
# Compose and Smart Reply are two separate windows that both put addresses on a
# message, and until now only Compose had the address hygiene and the address-
# book picker. Anything that is about "who is this going to" therefore lives
# HERE, once, and both windows inherit it — so a fix to the address cleaner can
# never again land in one window and not the other.
#
# What a window must provide to use this mixin:
#   self.top                 — the Toplevel the dialogs should hang off
#   self.app                 — FreemailApp (may be None in demo/standalone)
#   self.e_to / e_cc / e_bcc — tk.Entry widgets (e_cc/e_bcc optional)
#   self._touch_draft()      — optional; a no-op fallback is provided below


class _ChipEntry(tk.Frame):
    """A To:/Cc:/Bcc: field that shows each address as a small removable,
    movable "chip" — Thunderbird-style rectangular units — instead of one
    long comma-separated string (Issu 2026-08-05: "det kan bli fel om jag
    inte vet om det ska kommasepareras eller ej" after hand-moving text
    between fields).

    Right-click a chip to move it straight to another field (To/Cc/Bcc) or
    remove it — no manual comma-editing involved. `sibling_fields` (set by
    the caller once all three fields exist) is the {"To": .., "Cc": ..,
    "Bcc": ..} map a chip's move-menu offers.

    Drop-in replacement for the plain tk.Entry that sat here before: still
    supports .get() / .insert(0, text) / .delete(0, "end") / .focus_set() /
    .icursor() / .bind() / .configure(validate=…) / .register(), so none of
    the address-book picker, autocomplete, sanitiser or draft-save code
    around it had to change."""

    _ENTRY_ONLY_OPTS = {"validate", "validatecommand", "insertofftime",
                        "insertontime", "show", "exportselection", "justify"}

    def __init__(self, parent, field_name, sibling_fields=None,
                 collapse_over=0, **entry_kw):
        bg = entry_kw.get("bg", C_BG2)
        super().__init__(parent, bg=bg)
        self.field_name = field_name
        self.sibling_fields = sibling_fields  # filled in after all 3 exist
        self._bg = bg
        self._chips = []          # [(address, chip_frame), ...]
        self._rows = []           # wrap rows currently laid out
        # ── Folding a mailing-list-sized Cc (Issu 2026-09-20) ─────────────
        # "Vissa folk är tokiga och skickar meddelanden till dussintals
        # mottagare (i CC). Det tar upp en himla plats och vanligtvis så vill
        # man inte se vem de andra är." Reply All on one of those fills this
        # field with thirty chips, which wrap onto row after row and push the
        # message itself off the screen.
        #
        # Above `collapse_over` chips the field shows ONE row — as many as the
        # width takes — and a "+N more ▾" pill. DISPLAY ONLY: get() returns
        # every chip either way, so a folded field sends exactly what an open
        # one does. `_on_fold_change` lets the window put a matching ▾/▴ button
        # beside the caption, which is where he asked for it.
        self.collapse_over = int(collapse_over or 0)
        self._collapsed = True
        self._pill = None
        self._laying_out = False
        self._on_fold_change = None
        self._last_layout = (None, None, None)  # count, width, folded
        # Chips wrap onto as many rows as needed (Thunderbird-style), with the
        # typing entry always on its own row underneath — so a long Cc: list
        # is never hidden behind the 📖 button (Issu 2026-08-05).
        self._chip_bar = tk.Frame(self, bg=bg)
        self._chip_bar.pack(side="top", fill="x")
        self.entry = tk.Entry(self, **entry_kw)
        self.entry.pack(side="top", fill="x", expand=True)
        self.bind("<Configure>", self._relayout)
        # ── Typing a SECOND address by hand (Issu 2026-08-29) ─────────────
        # "Det är svårt att veta hur man lägger till fler manuella adresser i
        # To. Jag fick skriva in en… sedan hämta någon från kontaktbok… sedan
        # skriva in en… sedan radera den från kontaktbok."
        #
        # Exactly right, and the field's fault: a typed address stayed as loose
        # text in the entry and only ever became a chip when something ELSE
        # rewrote the field. Picking a contact did that as a side effect, which
        # is why using the address book and then throwing the contact away was
        # the only discoverable way to commit what you had typed and get an
        # empty box for the next one.
        #
        # Comma and semicolon now do it directly — the separators anyone would
        # try first — and Enter, Tab and clicking away are wired to the same
        # thing (see _wire_autocomplete / _commit_all_recipients). A more
        # specific KeyRelease binding wins over the generic one autocomplete
        # installs, so this deliberately swallows the comma keystroke; the
        # <<ChipCommitted>> event below is what closes the stale popup.
        for _seq in ("<KeyRelease-comma>", "<KeyRelease-semicolon>"):
            self.entry.bind(_seq, self.commit_typed)

    def commit_typed(self, _event=None):
        """Turn whatever is half-typed in the entry into chip(s).

        Safe to call at any time — with an empty entry it does nothing and
        reports so, which is what lets Enter fall through to its normal
        "move to the next field" job when there is nothing to commit."""
        raw = self.entry.get()
        parts = [p.strip() for p in _re.split(r"[;,]", raw) if p.strip()]
        if not parts:
            return False
        self.entry.delete(0, "end")
        for p in parts:
            self._add_chip(p)
        try:
            self.event_generate("<<ChipCommitted>>")
        except Exception:
            pass
        return True

    # ── chip management ──────────────────────────────────────────────────
    def _add_chip(self, addr):
        # A "mailto:info@…" copied off a web page becomes the plain address the
        # moment it lands here, so the chip reads right and there is nothing to
        # delete by hand (Issu 2026-09-09). Everything downstream cleans it too
        # — _clean_one_address — but this is the one place he can SEE it.
        addr = _strip_mailto(addr)
        if not addr or addr in [a for a, _ in self._chips]:
            return
        chip = tk.Frame(self._chip_bar, bg=C_BG4)
        lbl = tk.Label(chip, text=addr, bg=C_BG4, fg=C_FG,
                       font=("Segoe UI", 9), padx=5, pady=1, cursor="hand2")
        lbl.pack(side="left")
        xbtn = tk.Label(chip, text="×", bg=C_BG4, fg=C_FG_DIM,
                        font=("Segoe UI", 9, "bold"), cursor="hand2", padx=3)
        xbtn.pack(side="left")
        xbtn.bind("<Button-1>", lambda e, a=addr: self._remove_chip(a))
        for w in (chip, lbl):
            w.bind("<Button-3>", lambda e, a=addr: self._chip_menu(e, a))
        add_tooltip(lbl, f"Right-click to move {addr} to another field, "
                         f"or click × to remove it.")
        self._chips.append((addr, chip))
        self._relayout()

    def _remove_chip(self, addr):
        for a, chip in list(self._chips):
            if a == addr:
                chip.destroy()
                self._chips.remove((a, chip))
                self._relayout()
                return

    # ── Folding ──────────────────────────────────────────────────────────
    def can_fold(self):
        """True when there are enough chips for folding to mean anything."""
        return self.collapse_over > 0 and len(self._chips) > self.collapse_over

    def is_folded(self):
        return bool(self._collapsed and self.can_fold())

    def toggle_fold(self, _event=None):
        self._collapsed = not self._collapsed
        self._last_layout = (None, None, None)
        self._relayout()
        return "break"

    def set_folded(self, folded):
        if bool(folded) != bool(self._collapsed):
            self.toggle_fold()

    def _make_pill(self, parent, text, tip):
        pill = tk.Frame(parent, bg=C_BG3, cursor="hand2")
        lbl = tk.Label(pill, text=text, bg=C_BG3, fg=C_ACCENT,
                       font=("Segoe UI", 8, "bold"), padx=6, pady=1,
                       cursor="hand2")
        lbl.pack()
        for w in (pill, lbl):
            w.bind("<Button-1>", self.toggle_fold)
        add_tooltip(lbl, tip)
        return pill

    def _relayout(self, event=None):
        """Pack chips left-to-right, wrapping onto a new row whenever the
        next one would run past the field's current width — or, when the list
        is folded, stopping after ONE row and saying how many are left."""
        # ── Never re-enter (Issu 2026-09-20) ─────────────────────────────
        # Folding changes the field's HEIGHT, which fires <Configure>, which is
        # bound straight back to this method. update_idletasks() below runs
        # that pending event mid-loop, so the inner call destroyed the very row
        # the outer loop was still packing chips into — "bad window path name".
        # The count/width guard alone could not catch it: the inner call sees a
        # genuinely different state and is right to redraw. One flag; the outer
        # pass finishes and the next <Configure> settles whatever is left.
        if getattr(self, "_laying_out", False):
            return
        avail = self.winfo_width()
        if avail <= 1:
            return   # not mapped/sized yet — the next <Configure> will do it
        n       = len(self._chips)
        foldable = self.can_fold()
        folded   = foldable and self._collapsed
        state = (n, avail, folded)
        if state == self._last_layout:
            return   # nothing actually changed — avoid a relayout loop
        self._last_layout = state
        self._laying_out = True
        try:
            self._relayout_now(avail, n, foldable, folded)
        finally:
            self._laying_out = False

    def _relayout_now(self, avail, n, foldable, folded):
        """The actual packing — only ever called from _relayout, behind its
        re-entrancy flag."""

        for _addr, chip in self._chips:
            chip.pack_forget()
        if self._pill is not None:
            try:
                self._pill.destroy()
            except Exception:
                pass
            self._pill = None
        for row in self._rows:
            row.destroy()
        self._rows = []

        row = tk.Frame(self._chip_bar, bg=self._bg)
        row.pack(side="top", fill="x", anchor="w")
        self._rows.append(row)
        used = 0
        # Keep room on the row for the "+N more" pill, or it would be the
        # thing that wraps — which is the one item that must stay visible.
        room   = max(1, avail - (104 if foldable else 0))
        shown  = 0
        for _addr, chip in self._chips:
            chip.update_idletasks()
            w = chip.winfo_reqwidth() + 4
            if used + w > room and used > 0:
                if folded:
                    break          # one row and no more — that is the point
                row = tk.Frame(self._chip_bar, bg=self._bg)
                row.pack(side="top", fill="x", anchor="w")
                self._rows.append(row)
                used = 0
            chip.pack(in_=row, side="left", padx=(0, 3), pady=2)
            chip.lift()   # the row frame is created AFTER the chip and would
                          # otherwise paint its own background on top of it
            used += w
            shown += 1
        hidden = n - shown

        if foldable and (hidden > 0 or not folded):
            if folded:
                text = f"+{hidden} more  ▾"
                tip  = (f"{hidden} more recipient(s) are in this field and "
                        f"will be sent — they are only folded away to keep "
                        f"the window usable. Click to see them all.")
            else:
                text = "▴  fewer"
                tip  = ("Fold the list back to one row. Nothing is removed; "
                        "every address still goes out.")
            self._pill = self._make_pill(row, text, tip)
            self._pill.pack(in_=row, side="left", padx=(2, 0), pady=2)
            self._pill.lift()

        if callable(self._on_fold_change):
            try:
                self._on_fold_change(n, hidden, folded, foldable)
            except Exception as e:
                log.debug("fold callback: %s", e)

    # (end of _relayout_now)

    def _chip_menu(self, event, addr):
        m = tk.Menu(self, tearoff=0, bg=C_BG2, fg=C_FG,
                   activebackground=C_BG4, activeforeground=C_FG)
        for name, field in (self.sibling_fields or {}).items():
            if name == self.field_name or field is None:
                continue
            m.add_command(label=f"Move to {name}",
                          command=lambda a=addr, f=field: self._move_chip(a, f))
        m.add_separator()
        m.add_command(label="Remove", command=lambda a=addr: self._remove_chip(a))
        m.tk_popup(event.x_root, event.y_root)

    def _move_chip(self, addr, target_field):
        self._remove_chip(addr)
        target_field._add_chip(addr)
        try:
            self.event_generate("<<ChipMoved>>")
        except Exception:
            pass

    # ── Entry-compatible surface — everything around this widget still
    #    talks to it as if it were a plain tk.Entry ─────────────────────────
    def get(self):
        addrs = [a for a, _ in self._chips]
        typed = self.entry.get().strip()
        if typed:
            addrs.append(typed)
        return ", ".join(addrs)

    def insert(self, index, text):
        for part in (text or "").split(","):
            part = part.strip()
            if part:
                self._add_chip(part)

    def delete(self, start, end=None):
        for _addr, chip in list(self._chips):
            chip.destroy()
        self._chips = []
        if self._pill is not None:
            try:
                self._pill.destroy()
            except Exception:
                pass
            self._pill = None
        for row in self._rows:
            row.destroy()
        self._rows = []
        self._last_layout = (None, None, None)
        self._collapsed = True
        self.entry.delete(0, "end")
        if callable(self._on_fold_change):
            try:
                self._on_fold_change(0, 0, False, False)
            except Exception:
                pass

    def focus_set(self):
        self.entry.focus_set()

    def icursor(self, index):
        try:
            self.entry.icursor(index)
        except Exception:
            pass

    def bind(self, sequence=None, func=None, add=None):
        # Typing/navigation events belong on the inner Entry (that's where
        # the cursor actually is); anything else falls back to the Frame.
        # <Tab> belongs on the inner Entry for the same reason as the rest: the
        # Frame never has the keyboard focus, so a Tab bound there would simply
        # never fire. <<ChipCommitted>> is the exception — commit_typed raises
        # it on the Frame — so it falls through to super() on purpose.
        if sequence in ("<KeyRelease>", "<Down>", "<Up>", "<Return>",
                       "<Escape>", "<FocusOut>", "<FocusIn>", "<Tab>"):
            return self.entry.bind(sequence, func, add)
        return super().bind(sequence, func, add)

    def register(self, func):
        return self.entry.register(func)

    def configure(self, **kwargs):
        entry_kw = {k: kwargs.pop(k) for k in list(kwargs)
                   if k in self._ENTRY_ONLY_OPTS}
        if entry_kw:
            self.entry.configure(**entry_kw)
        if kwargs:
            tk.Frame.configure(self, **kwargs)

    config = configure


class _RecipientFields:
    """Address-book picker + address sanitiser, shared by ComposeWindow and
    SmartReplyWindow."""


    # A window without crash-safe drafts (Smart Reply) still gets called here.
    def _touch_draft(self, event=None):
        return None

    # ── Keep the corruption OUT of the field in the first place ──────────────
    def _guard_address_entry(self, entry, label):
        """Refuse characters that have no business in a recipient field.

        The corruption Issu reported ("issusbarn@♣gmail.com") was cleaned on
        send, but by then it had already been typed, saved to a draft and
        possibly stored as a contact. This stops it at the keyboard — including
        on paste, since Tk validates the whole inserted string.

        Deliberately NARROW. A display name may be "Ärna Öberg" or any script on
        earth, so letters, digits, spaces and punctuation all pass. Only these
        are refused, and none of them can be typed on purpose here:
          Cc  control characters
          Cf  invisible formatting (zero-width space, RTL override…)
          Co/Cs/Cn  private-use, surrogates, unassigned
          So  "other symbols" — ♣ ★ ☺ and the dingbats/emoji block
        Every refusal is logged with its code point, so if this ever fires the
        log finally says what the character was and which field it went into."""
        try:
            import unicodedata
        except Exception:
            return                      # no unicodedata, no guard — never fatal

        blocked = {"Cc", "Cf", "Co", "Cs", "Cn", "So"}

        def _validate(action, index, inserted):
            # %S is the inserted text on an insert — but the DELETED text on a
            # delete. Validating both would make it impossible to remove a bad
            # character that is already in the field (e.g. from an old draft),
            # which is the opposite of helping. 1 = insert; everything else
            # (0 = delete, -1 = focus/forced) passes untouched.
            if action != "1":
                return True
            bad = [c for c in (inserted or "")
                   if unicodedata.category(c) in blocked and c != "\t"]
            if not bad:
                return True
            for c in bad:
                try:
                    nm = unicodedata.name(c)
                except ValueError:
                    nm = "unnamed"
                log.error("ADDRESS CORRUPTION BLOCKED AT THE KEYBOARD "
                          "[%s field]: refused U+%04X %s (inserting %r)",
                          label, ord(c), nm, inserted)
            # Pasting a whole address with one bad character in it should not
            # throw the address away — put the good part in. It has to happen
            # after this callback returns, because Tk switches validation OFF
            # for good if the validate command edits the widget itself.
            keep = "".join(c for c in inserted
                           if unicodedata.category(c) not in blocked)
            if keep:
                try:
                    at = int(index)
                except (TypeError, ValueError):
                    at = None
                if at is not None:
                    def _insert_clean():
                        try:
                            entry.insert(at, keep)
                        except Exception:
                            pass
                    try:
                        entry.after_idle(_insert_clean)
                    except Exception:
                        pass
            return False

        try:
            vcmd = (entry.register(_validate), "%d", "%i", "%S")
            entry.configure(validate="key", validatecommand=vcmd)
        except Exception as e:
            log.warning("Could not guard the %s field: %s", label, e)

    def _guard_text_entry(self, entry, label):
        """Like _guard_address_entry but for a SUBJECT line — looser, because a
        subject may legitimately carry emoji and any symbol (☺ 🎉 ™). Only the
        genuinely invalid categories (control / invisible-format / private-use /
        surrogate / unassigned) are refused, so the same invisible-junk-at-the-
        keyboard route is blocked without stopping legitimate characters."""
        try:
            import unicodedata
        except Exception:
            return
        blocked = _TEXT_STRIP_CATS

        def _validate(action, index, inserted):
            if action != "1":            # only insertions; see _guard_address_entry
                return True
            bad = [c for c in (inserted or "")
                   if c not in _TEXT_KEEP_CTRL
                   and unicodedata.category(c) in blocked]
            if not bad:
                return True
            for c in bad:
                try:
                    nm = unicodedata.name(c)
                except ValueError:
                    nm = "unnamed"
                log.error("TEXT CORRUPTION BLOCKED AT THE KEYBOARD [%s]: "
                          "refused U+%04X %s (inserting %r)",
                          label, ord(c), nm, inserted)
            keep = "".join(c for c in inserted
                           if c in _TEXT_KEEP_CTRL
                           or unicodedata.category(c) not in blocked)
            if keep:
                try:
                    at = int(index)
                except (TypeError, ValueError):
                    at = None
                if at is not None:
                    entry.after_idle(lambda: self._safe_insert(entry, at, keep))
            return False

        try:
            vcmd = (entry.register(_validate), "%d", "%i", "%S")
            entry.configure(validate="key", validatecommand=vcmd)
        except Exception as e:
            log.warning("Could not guard the %s field: %s", label, e)

    @staticmethod
    def _safe_insert(entry, at, text):
        try:
            entry.insert(at, text)
        except Exception:
            pass

    # ── The little 📖 button that sits at the end of a recipient row ──────────
    def _pick_btn(self, parent, get_entry, label):
        b = tk.Button(parent, text="📖", bg=C_BTN_STD, fg=C_BTN_FG,
                      font=("Segoe UI", 9), relief="flat", cursor="hand2",
                      padx=6, pady=0,
                      command=lambda: self._pick_into(get_entry(), label))
        b.pack(side="right", padx=(4, 0))
        add_tooltip(b, f"Pick {label} recipients from your address book "
                       f"(Favorites first).")
        # Every row that gets a picker is a recipient row, so this is the one
        # place that has to remember to guard the typing as well.
        try:
            self._guard_address_entry(get_entry(), label)
        except Exception:
            pass
        return b

    # ── Recipient picker (Issu 2026-08-01) ────────────────────────────────────
    def _pick_into(self, entry, label):
        """Popup to add people from the address book to a recipient field.

        Favorites are the first tab (people you flagged ★ in the address book);
        "All" lists everyone. Multi-select, filter box, double-click or "Add"
        appends them to the field the 📖 button belongs to."""
        app = self.app
        people = list(app._addressbook_store.get("people", [])) if app else []

        top = tk.Toplevel(self.top)
        top.title(f"Choose {label} recipients — F(re)email")
        top.configure(bg=C_BG3)
        _center_over(top, self.top, 540, 540)
        top.transient(self.top)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())

        tk.Label(top, text=f"👥  Add to {label}", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(pady=(12, 2))

        state = {"fav_only": any(p.get("favorite") for p in people)}

        # ── Favorites | All tabs ─────────────────────────────────────────────
        tabbar = tk.Frame(top, bg=C_BG3)
        tabbar.pack(fill="x", padx=14)
        fav_btn = tk.Button(tabbar, text="★ Favorites", relief="flat",
                            font=("Segoe UI", 9, "bold"), cursor="hand2",
                            padx=12, pady=3)
        all_btn = tk.Button(tabbar, text="All contacts", relief="flat",
                            font=("Segoe UI", 9, "bold"), cursor="hand2",
                            padx=12, pady=3)
        fav_btn.pack(side="left")
        all_btn.pack(side="left", padx=(4, 0))

        # ── Filter box ───────────────────────────────────────────────────────
        frow = tk.Frame(top, bg=C_BG3, padx=14)
        frow.pack(fill="x", pady=(8, 4))
        tk.Label(frow, text="Filter:", bg=C_BG3, fg=C_FG_DIM, width=8,
                 anchor="e", font=("Segoe UI", 9)).pack(side="left")
        e_filter = tk.Entry(frow, bg=C_BG2, fg=C_FG, relief="flat",
                            insertbackground=C_ACCENT, font=("Segoe UI", 9),
                            insertofftime=0, insertontime=9999999)
        no_blink(e_filter)
        e_filter.pack(side="left", fill="x", expand=True, ipady=2)

        # ── List ─────────────────────────────────────────────────────────────
        lwrap = tk.Frame(top, bg=C_BG2)
        lwrap.pack(fill="both", expand=True, padx=14, pady=(0, 6))
        lsb = tk.Scrollbar(lwrap, bg=C_BG3, troughcolor=C_BG1)
        lsb.pack(side="right", fill="y")
        lb = tk.Listbox(lwrap, bg=C_BG2, fg=C_FG, selectmode="extended",
                        selectbackground=C_MSG_SEL, selectforeground=C_FG_UNRD,
                        highlightthickness=0, relief="flat", activestyle="none",
                        font=("Segoe UI", 9), exportselection=False,
                        yscrollcommand=lsb.set)
        lsb.configure(command=lb.yview)
        lb.pack(side="left", fill="both", expand=True)

        shown = []      # people entries in current list order

        def _refresh():
            for b, on in ((fav_btn, state["fav_only"]), (all_btn, not state["fav_only"])):
                b.configure(bg=C_ACCENT2 if on else C_BTN_STD,
                            fg=C_FG_UNRD if on else C_FG_DIM)
            q = e_filter.get().strip().lower()
            lb.delete(0, "end")
            shown.clear()
            for p in people:
                if state["fav_only"] and not p.get("favorite"):
                    continue
                hay = (p.get("name", "") + " " + p.get("email", "")
                       + " " + p.get("group", "")).lower()
                if q and q not in hay:
                    continue
                shown.append(p)
                star = "★ " if p.get("favorite") else "   "
                grp = f"   ·   {p['group']}" if p.get("group") else ""
                lb.insert("end",
                          f"{star}{p.get('name','') or p.get('email','')}"
                          f"   <{p.get('email','')}>{grp}")
            if not shown:
                lb.insert("end", "   (no matching contacts)")

        def _set_tab(fav):
            state["fav_only"] = fav
            _refresh()

        fav_btn.configure(command=lambda: _set_tab(True))
        all_btn.configure(command=lambda: _set_tab(False))
        e_filter.bind("<KeyRelease>", lambda e: _refresh())

        def _add(close=False):
            sel = [i for i in lb.curselection() if i < len(shown)]
            emails = [shown[i].get("email", "") for i in sel
                      if shown[i].get("email")]
            if emails:
                cur = entry.get().strip()
                parts = [x.strip() for x in _re.split(r"[;,]", cur) if x.strip()]
                for em in emails:
                    if em not in parts:
                        parts.append(em)
                entry.delete(0, "end")
                entry.insert(0, ", ".join(parts) + (", " if parts else ""))
                self._touch_draft()
            if close:
                top.destroy()

        lb.bind("<Double-Button-1>", lambda e: _add(close=False))

        brow = tk.Frame(top, bg=C_BG3)
        brow.pack(fill="x", padx=14, pady=(0, 12))
        tk.Button(brow, text="Add selected", bg=C_BTN_NEW, fg=C_BTN_FG,
                  font=("Segoe UI", 9, "bold"), relief="flat", cursor="hand2",
                  padx=12, pady=4, command=lambda: _add(close=False)
                  ).pack(side="left")
        tk.Button(brow, text="Add & close", bg=C_BTN_NEW, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=12, pady=4, command=lambda: _add(close=True)
                  ).pack(side="left", padx=(6, 0))
        if app is not None:
            tk.Button(brow, text="Edit address book…", bg=C_BTN_STD, fg=C_BTN_FG,
                      font=("Segoe UI", 9), relief="flat", cursor="hand2",
                      padx=12, pady=4,
                      command=lambda: (top.destroy(),
                                       app._addressbook_dialog(parent=self.top))
                      ).pack(side="right")
        tk.Button(brow, text="Close", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=12, pady=4, command=top.destroy).pack(side="right",
                                                             padx=(0, 6))
        _refresh()
        if not people:
            lb.delete(0, "end")
            lb.insert("end", "   Your address book is empty.")
            lb.insert("end", "   Import contacts: File → Import → Contacts (.vcf).")

    # ── Address-book autocomplete (To:/Cc:/Bcc:) ──────────────────────────────
    # A small, non-modal suggestion popup that opens right under whichever
    # recipient field you're typing in, matching what's typed so far against
    # BOTH name and address (and group) in the address book, filtered live on
    # every keystroke. Click a row, or use Up/Down + Enter, to drop it into
    # the field — look away and it just closes, no OK/Cancel, no dialog
    # stealing focus (Issu 2026-08-10: "en icke-dominerande popup ... i to,
    # cc, bcc ... som filtreras alltefter jag skriver in mer").
    #
    # Used to be wired to To: only, inside ComposeWindow. Now shared by every
    # recipient field in both ComposeWindow and SmartReplyWindow — call
    # _wire_autocomplete() once per field, right after it's built.
    def _wire_autocomplete(self, entry, next_focus=None):
        """Attach the suggestion popup to one recipient field (To/Cc/Bcc).

        next_focus: optional no-arg callable — where plain Enter goes when no
        popup is open, so each field keeps its own existing tab order."""
        if not hasattr(self, "_ac_top"):
            self._ac_top   = None   # the popup Toplevel, or None when hidden
            self._ac_list  = None   # its Listbox
            self._ac_data  = []     # candidates currently shown, same order as the list
            self._ac_field = None   # which entry the open popup belongs to
        entry.bind("<KeyRelease>",
                   lambda e, ent=entry: self._ac_update(ent, e))
        entry.bind("<Down>",   lambda e, ent=entry: self._ac_move(1, ent))
        entry.bind("<Up>",     lambda e, ent=entry: self._ac_move(-1, ent))
        entry.bind("<Return>",
                   lambda e, ent=entry, nf=next_focus: self._ac_return(ent, nf))
        entry.bind("<Escape>", lambda e, ent=entry: self._ac_escape(ent))
        entry.bind("<FocusOut>",
                   lambda e, ent=entry: self.top.after(
                       180, lambda: (self._ac_hide_if(ent),
                                     self._commit_field(ent))))
        # Tab out of the field, or click away from it, and what you typed
        # becomes a chip like everything else (Issu 2026-08-29) — leaving the
        # field is as clear a "I'm done with this address" as pressing Enter.
        entry.bind("<Tab>", lambda e, ent=entry: self._commit_field(ent))
        # A committed chip makes the open suggestion list stale — it was built
        # from a token that no longer exists.
        try:
            entry.bind("<<ChipCommitted>>",
                       lambda e, ent=entry: self._ac_hide_if(ent))
        except Exception:
            pass

    def _commit_field(self, entry):
        """Turn a half-typed address in one recipient field into a chip.

        A no-op for anything that is not a chip field, and for a chip field
        with nothing typed in it — so it is safe to hang off Tab and FocusOut,
        which fire constantly."""
        try:
            if hasattr(entry, "commit_typed"):
                entry.commit_typed()
        except Exception as e:
            log.warning("could not commit a typed recipient: %s", e)

    def _ac_token(self, entry):
        """(current_token, all_segments) for `entry` — the token is the part
        after the last comma/semicolon, i.e. whatever is being typed now."""
        full = entry.get()
        segs = _re.split(r'[;,]', full)
        return segs[-1].strip(), segs

    def _ac_candidates(self, token):
        """Suggestions while typing: FAVOURITES only (Issu 2026-10-10) — anyone
        else is picked from the address book (the 📖 button). If nobody has
        been starred yet, everyone is suggested, as the 📖 picker does."""
        if not token or self.app is None:
            return []
        q = token.lower()
        people = self.app._addressbook_store.get("people", [])
        if any(p.get("favorite") for p in people):
            people = [p for p in people if p.get("favorite")]
        out = [p for p in people
               if q in (p.get("name", "").lower())
               or q in (p.get("email", "").lower())
               or q in (p.get("group", "").lower())]
        return out[:7]

    def _ac_update(self, entry, event=None):
        if event and event.keysym in ("Up", "Down", "Return", "Escape", "Tab"):
            return
        token, _ = self._ac_token(entry)
        cands = self._ac_candidates(token)
        if cands:
            self._ac_show(cands, entry)
        else:
            self._ac_hide_if(entry)

    def _ac_show(self, cands, entry):
        if self._ac_top is None or not self._ac_top.winfo_exists():
            self._ac_top = tk.Toplevel(self.top)
            self._ac_top.overrideredirect(True)
            self._ac_top.configure(bg=C_SEP)
            self._ac_list = tk.Listbox(
                self._ac_top, bg=C_BG2, fg=C_FG,
                selectbackground=C_MSG_SEL, selectforeground=C_FG_UNRD,
                highlightthickness=0, relief="flat", activestyle="none",
                font=("Segoe UI", 9))
            self._ac_list.pack(fill="both", expand=True, padx=1, pady=1)
            # Mouse click selects; after(1) lets the selection settle first.
            self._ac_list.bind("<Button-1>",
                               lambda e: self.top.after(1, self._ac_accept))
        self._ac_field = entry
        self._ac_data = cands
        self._ac_list.delete(0, "end")
        for p in cands:
            nm = p.get("name", "") or p.get("email", "")
            self._ac_list.insert("end", f"{nm}  <{p.get('email','')}>")
        self._ac_list.selection_clear(0, "end")
        self._ac_list.selection_set(0)
        self._ac_list.activate(0)
        entry.update_idletasks()
        x = entry.winfo_rootx()
        y = entry.winfo_rooty() + entry.winfo_height()
        w = max(entry.winfo_width(), 220)
        h = min(len(cands), 7) * 20 + 4
        self._ac_top.geometry(f"{w}x{h}+{x}+{y}")
        self._ac_top.deiconify()
        self._ac_top.lift()

    def _ac_hide(self):
        if self._ac_top is not None and self._ac_top.winfo_exists():
            self._ac_top.destroy()
        self._ac_top   = None
        self._ac_list  = None
        self._ac_field = None

    def _ac_hide_if(self, entry):
        # A FocusOut fires for the field you're LEAVING — only close the
        # popup if it still belongs to that field. Otherwise a delayed
        # FocusOut from To: could close a popup Cc: just opened a moment
        # later (Tab or a click straight from one recipient field to the
        # next).
        if self._ac_field is entry:
            self._ac_hide()

    def _ac_move(self, delta, entry):
        if not (self._ac_top and self._ac_list and self._ac_top.winfo_exists()
                and self._ac_field is entry):
            return
        cur = self._ac_list.curselection()
        i = (cur[0] if cur else 0) + delta
        i = max(0, min(i, self._ac_list.size() - 1))
        self._ac_list.selection_clear(0, "end")
        self._ac_list.selection_set(i)
        self._ac_list.activate(i)
        return "break"

    def _ac_accept(self):
        entry = self._ac_field
        if not (entry and self._ac_top and self._ac_list
                and self._ac_top.winfo_exists()):
            return False
        cur = self._ac_list.curselection()
        idx = cur[0] if cur else 0
        if idx >= len(self._ac_data):
            self._ac_hide(); return False
        email = self._ac_data[idx].get("email", "")
        _, segs = self._ac_token(entry)
        segs[-1] = email
        newval = ", ".join(s.strip() for s in segs if s.strip())
        entry.delete(0, "end")
        entry.insert(0, newval + ", ")
        entry.icursor("end")
        self._ac_hide()
        entry.focus_set()
        return True

    def _ac_return(self, entry, next_focus=None, event=None):
        # If suggestions are open for THIS field, accept the highlighted one;
        # otherwise fall through to that field's own tab order.
        if (self._ac_top and self._ac_top.winfo_exists()
                and self._ac_field is entry):
            if self._ac_accept():
                return "break"
        # Nothing to accept — but there may be an address typed by hand. Turn
        # it into a chip and STAY here, ready for the next one (Issu
        # 2026-08-29). Enter only walks on to the next field once this one has
        # nothing half-typed left in it, so the old tab order still works; you
        # just press Enter twice when you have typed an address, which is what
        # every other mail client does.
        if hasattr(entry, "commit_typed") and entry.commit_typed():
            entry.focus_set()
            return "break"
        if next_focus:
            next_focus()
        return "break"

    def _ac_escape(self, entry, event=None):
        # Close suggestions if they're open for THIS field (and swallow the
        # key); otherwise let the window's own <Escape> binding run.
        if (self._ac_top and self._ac_top.winfo_exists()
                and self._ac_field is entry):
            self._ac_hide()
            return "break"

    # ── Address hygiene ───────────────────────────────────────────────────────
    def _sanitize_recipients(self, top) -> bool:
        """Clean the To:/Cc:/Bcc: fields in place and flag suspicious addresses.

        Silently removes characters that cannot appear in an address (so a
        stray "♣" in "…@♣gmail.com" is dropped and the field visibly corrects
        itself), then asks about anything that still looks wrong — chiefly a
        domain that resembles a mangled gmail.com. Returns False if the user
        chose to go back and fix it."""
        problems = []
        for label, widget in (("To", getattr(self, "e_to", None)),
                              ("Cc", getattr(self, "e_cc", None)),
                              ("Bcc", getattr(self, "e_bcc", None))):
            if widget is None:
                continue
            raw  = widget.get()
            segs = [s.strip() for s in _re.split(r"[;,]", raw)]
            cleaned, any_changed = [], False
            for s in segs:
                if not s:
                    continue
                c, changed = _clean_one_address(s)
                # `changed` alone means "illegal characters were removed". The
                # text can also differ for a perfectly legal reason — a pasted
                # "mailto:" link being unwrapped (2026-09-09) — and the field
                # should redraw for that too, so compare the strings as well.
                any_changed = any_changed or changed or (c != s)
                cleaned.append(c)
                look = _gmail_lookalike(c)
                bare = parseaddr(c)[1] or c
                if look:
                    problems.append(
                        f"  • {label}:  {c}\n        did you mean  {look}  ?")
                elif bare and not _EMAIL_RE.match(bare):
                    problems.append(
                        f"  • {label}:  {c}\n        does not look like a valid "
                        f"address")
            if any_changed:
                widget.delete(0, "end")
                widget.insert(0, ", ".join(cleaned))
        # ── Subject line (Issu 2026-08-01) ───────────────────────────────────
        # Strip invisible/control junk (it self-corrects, exactly like the
        # address fields) and warn if a "�" is present — that means a letter
        # was already lost upstream (his "ä blev ?") and the subject should be
        # retyped before it goes out. Emoji and ordinary symbols are left alone.
        subj_w = getattr(self, "e_subj", None)
        if subj_w is not None:
            raw = subj_w.get()
            clean, changed, _forensics, has_repl = _scan_text_corruption(raw)
            if changed:
                subj_w.delete(0, "end")
                subj_w.insert(0, clean)
            if has_repl:
                problems.append(
                    "  • Subject contains “�” — a letter was lost (e.g. an "
                    "“ä”).\n        Please retype it before sending.")
        if problems:
            if not messagebox.askyesno(
                    "Check before sending",
                    "Some things look wrong:\n\n"
                    + "\n".join(problems)
                    + "\n\nSend anyway?",
                    parent=top, default="no"):
                return False
        return True

    # ── Remembered window position (Issu 2026-08-11) ─────────────────────────
    # "gör så att det minns last position och att jag kan välja en position
    # som min default, som jag kan återgå till ... någonstans (om last
    # position är jobbig)" — Reply and Smart Reply now each remember wherever
    # you last left THEM (independently — `self._geo_key` is "compose" or
    # "smart_reply", set by the subclass __init__ before any of this runs),
    # and separately let you pin one spot as YOUR default to jump back to
    # whenever the remembered spot turns out to be awkward.
    def _apply_remembered_geometry(self, top, parent, width, height):
        key = getattr(self, "_geo_key", None)
        last = self.cfg.get(f"{key}_win_last") if key else None
        if isinstance(last, dict) and "x" in last and "y" in last:
            self._place_geometry(top, last, width, height)
        else:
            _center_over(top, parent, width, height)

    @staticmethod
    def _place_geometry(top, geo, fallback_w, fallback_h):
        try:
            w = int(geo.get("w") or fallback_w)
            h = int(geo.get("h") or fallback_h)
            x = int(geo.get("x", 0))
            y = int(geo.get("y", 0))
            sw, sh = top.winfo_screenwidth(), top.winfo_screenheight()
            # Clamp fully on-screen — a spot saved on a bigger, or since
            # disconnected, second monitor must never leave the window
            # somewhere you can no longer reach.
            x = max(0, min(x, sw - min(w, sw)))
            y = max(0, min(y, sh - min(h, sh)))
            top.geometry(f"{w}x{h}+{x}+{y}")
        except Exception:
            top.geometry(f"{fallback_w}x{fallback_h}")

    def _on_geo_configure(self, event):
        """Keep the in-memory "last position" current on every move/resize.
        Cheap (a dict update) on purpose — the disk write happens once, when
        the window actually closes; see _persist_geo."""
        top = getattr(self, "top", None)
        key = getattr(self, "_geo_key", None)
        if not key or event.widget is not top:
            return
        try:
            self.cfg[f"{key}_win_last"] = {
                "x": top.winfo_x(), "y": top.winfo_y(),
                "w": top.winfo_width(), "h": top.winfo_height(),
            }
        except Exception:
            pass

    def _persist_geo(self):
        """Flush the remembered position to disk now that the window is
        actually closing. Same guard as FreemailApp._on_close: never write
        back over settings that were just restored from a backup."""
        if getattr(self.app, "_settings_restored", False):
            return
        # Zoom and splitter go with the position: one write, one moment, so a
        # window that is closing cannot leave half its layout behind.
        try:
            self._layout_capture()
        except Exception as e:
            log.debug("layout capture failed: %s", e)
        try:
            _save_settings(self.cfg)
        except Exception:
            pass

    def _set_default_geo(self):
        """Pin the window's CURRENT position/size as the default to return
        to later, from the Position menu."""
        key = getattr(self, "_geo_key", None)
        top = getattr(self, "top", None)
        if not key or top is None:
            return
        try:
            self.cfg[f"{key}_win_default"] = {
                "x": top.winfo_x(), "y": top.winfo_y(),
                "w": top.winfo_width(), "h": top.winfo_height(),
            }
            self._persist_geo()
            self._flash_ok("Default position saved!")
        except Exception:
            pass

    def _goto_default_geo(self, width, height):
        """Jump to the saved default position — the way back if wherever the
        window last landed turns out to be awkward."""
        key  = getattr(self, "_geo_key", None)
        top  = getattr(self, "top", None)
        default = self.cfg.get(f"{key}_win_default") if key else None
        if isinstance(default, dict) and "x" in default:
            self._place_geometry(top, default, width, height)
        else:
            _center_over(top, self.root, width, height)
            self._flash_ok("No default saved yet — centred instead")

    def _build_position_menu(self, tb):
        """The 📍 toolbar button: save-as-default / go-to-default for this
        window's remembered position. `self._geo_w/_geo_h` (set right before
        the window's geometry is first applied in __init__) are the fallback
        size if no default has been pinned yet."""
        w, h = getattr(self, "_geo_w", 680), getattr(self, "_geo_h", 560)
        mb = tk.Menubutton(tb, text="📍 Position", bg=C_BTN_STD, fg=C_BTN_FG,
                           font=("Segoe UI", 9), relief="flat",
                           padx=8, pady=3, cursor="hand2")
        menu = tk.Menu(mb, tearoff=0, bg=C_BG2, fg=C_FG,
                       activebackground=C_BG4, activeforeground=C_FG,
                       font=("Segoe UI", 9))
        menu.add_command(label="📌 Set current position as default",
                          command=self._set_default_geo)
        menu.add_command(label="↩ Go to default position",
                          command=lambda: self._goto_default_geo(w, h))
        mb.configure(menu=menu)
        mb.pack(side="left", padx=2)
        add_tooltip(mb, "This window opens wherever you last left it. Pin a "
                        "spot here as your default, and jump back to it any "
                        "time the remembered position ends up somewhere "
                        "awkward.")
        return mb

    # ── Reply layout: zoom, splitter, Default and Favourite (Issu 2026-09-20)
    #
    # "Originaldelen i Reply, kan må gott av zoom +-, för att lättare kunna
    # läsa den texten... och att reply sedan minns förra inställning, av zoom
    # och hur jag har expanderat fönstret/originalmeddelande-delen, och en (go
    # back to) default-knapp (och gärna en favoritknapp där jag kan spara mitt
    # favoritläge)." …and, the same day: "min svars-del … skulle också kunna
    # må bra av zoom, faktiskt. Zoom kan vara dubbel uppsättning."
    #
    # So there are TWO sizes, not one, and they are deliberately independent:
    #
    #     "orig"   — THEIR words. The read-only pane beside your answer in
    #                Reply; the sender's paragraph blocks in Smart Reply.
    #     "answer" — YOURS. The box you type in, in every compose window
    #                including New message, Forward and Note.
    #
    # Shared by both windows because they have the same shape: their words on
    # one side of a splitter, yours on the other. What differs is only which
    # widget carries which font and which way the splitter runs, so a subclass
    # opts in with a handful of small hooks:
    #
    #     self._layout_key            — "compose" or "smart_reply"
    #     _layout_set_zoom(pt)        — point size for THEIR text
    #     _layout_set_zoom_answer(pt) — point size for YOURS
    #     _layout_get_sash()          — where the splitter is now, in pixels
    #     _layout_set_sash(v)         — put the splitter there
    #
    # Each hook has a do-nothing default below, so a window that has no
    # original pane (New message) or no splitter simply provides fewer of
    # them rather than special-casing anything.
    _ZOOM_MIN, _ZOOM_MAX = 7, 28

    # Which attribute, which config key and which label belong to each of the
    # two sizes. One table, so nothing can drift apart.
    _ZOOM_KINDS = {
        "orig":   ("_zoom_pt",        "zoom",        "_zoom_lbl"),
        "answer": ("_zoom_pt_answer", "zoom_answer", "_zoom_lbl_answer"),
    }

    # Default no-ops: a window only overrides the ones it actually has.
    def _layout_set_zoom(self, pt):
        pass

    def _layout_set_zoom_answer(self, pt):
        pass

    def _layout_get_sash(self):
        return 0

    def _layout_set_sash(self, value):
        pass

    def _layout_defaults(self):
        """The numbers this window ships with — what ↺ Default restores."""
        return dict(_REPLY_LAYOUT_DEFAULTS.get(
            getattr(self, "_layout_key", ""),
            {"zoom": 10, "sash": 0, "w": 680, "h": 560}))

    def _layout_cfg_key(self, what):
        return f"{getattr(self, '_layout_key', 'reply')}_layout_{what}"

    # ── Zoom ──────────────────────────────────────────────────────────────────
    def _layout_zoom_init(self):
        """Read BOTH remembered sizes and clamp them, before the widgets exist.

        Called from __init__ so each pane can be created at the size you left
        it at — building at 9 pt and re-fonting afterwards would show a visible
        jump every single time the window opens."""
        d = self._layout_defaults()
        for kind, (attr, cfgname, _lbl) in self._ZOOM_KINDS.items():
            fallback = d.get(cfgname, 10)
            try:
                pt = int(self.cfg.get(self._layout_cfg_key(cfgname), fallback))
            except Exception:
                pt = fallback
            setattr(self, attr, max(self._ZOOM_MIN, min(self._ZOOM_MAX, pt)))
        return self._zoom_pt

    def _layout_zoom(self, delta=0, absolute=None, kind="orig", save=True):
        """A − / A + / Ctrl-wheel for one of the two sizes.

        `absolute` is what ↺ Default and ★ Favourite use; `kind` is "orig"
        (their text) or "answer" (yours)."""
        attr, cfgname, lblattr = self._ZOOM_KINDS.get(
            kind, self._ZOOM_KINDS["orig"])
        d   = self._layout_defaults()
        cur = getattr(self, attr, d.get(cfgname, 10))
        try:
            pt = int(absolute) if absolute is not None else cur + int(delta)
        except Exception:
            pt = cur
        pt = max(self._ZOOM_MIN, min(self._ZOOM_MAX, pt))
        setattr(self, attr, pt)
        try:
            if kind == "answer":
                self._layout_set_zoom_answer(pt)
            else:
                self._layout_set_zoom(pt)
        except Exception as e:
            log.debug("zoom %s %d pt failed: %s", kind, pt, e)
        lbl = getattr(self, lblattr, None)
        if lbl is not None:
            try:
                lbl.configure(text=f"{pt} pt")
            except Exception:
                pass
        self.cfg[self._layout_cfg_key(cfgname)] = pt
        if save:
            try:
                _save_settings(self.cfg)
            except Exception:
                pass
        return pt

    # ── Splitter ──────────────────────────────────────────────────────────────
    def _layout_sash_save(self):
        try:
            v = int(self._layout_get_sash())
        except Exception:
            return
        if v > 0:
            self.cfg[self._layout_cfg_key("sash")] = v

    def _layout_sash_restore(self, value=None):
        """Put the splitter back. Silently does nothing when there is no
        remembered position (0), which is what leaves a first-ever open
        looking exactly as it always did."""
        d = self._layout_defaults()
        if value is None:
            try:
                value = int(self.cfg.get(self._layout_cfg_key("sash"),
                                         d["sash"]))
            except Exception:
                value = d["sash"]
        try:
            value = int(value)
        except Exception:
            return
        if value <= 0:
            return
        try:
            self._layout_set_sash(value)
        except Exception as e:
            log.debug("splitter restore to %s failed: %s", value, e)

    # ── Whole layouts ─────────────────────────────────────────────────────────
    def _layout_snapshot(self):
        """Everything 📌 Pin remembers: both sizes, the splitter, the window."""
        top = getattr(self, "top", None)
        d   = self._layout_defaults()
        snap = {"sash": d["sash"], "w": d["w"], "h": d["h"]}
        for _kind, (attr, cfgname, _l) in self._ZOOM_KINDS.items():
            snap[cfgname] = getattr(self, attr, d.get(cfgname, 10))
        try:
            v = int(self._layout_get_sash())
            if v > 0:
                snap["sash"] = v
        except Exception:
            pass
        try:
            if top is not None:
                snap["w"] = int(top.winfo_width())
                snap["h"] = int(top.winfo_height())
        except Exception:
            pass
        return snap

    def _layout_apply(self, layout):
        """Zoom, then size, then splitter — in that order on purpose.

        The splitter is measured in pixels, so placing it before the window has
        been resized would put it at the right number in the wrong window. The
        update_idletasks() between the two is what makes the new width real
        before the sash is asked to sit inside it."""
        top = getattr(self, "top", None)
        d   = self._layout_defaults()
        # A favourite pinned before the answer size existed simply has no
        # "zoom_answer" in it; .get falls back to the shipped value rather
        # than leaving that half of the window at whatever it happened to be.
        for kind, (_a, cfgname, _l) in self._ZOOM_KINDS.items():
            self._layout_zoom(absolute=layout.get(cfgname, d.get(cfgname, 10)),
                              kind=kind)
        try:
            w = int(layout.get("w") or d["w"])
            h = int(layout.get("h") or d["h"])
            if top is not None:
                top.geometry(f"{w}x{h}")
                top.update_idletasks()
        except Exception as e:
            log.debug("layout resize failed: %s", e)
        self._layout_sash_restore(layout.get("sash", d["sash"]))

    def _layout_go_default(self):
        self._layout_apply(self._layout_defaults())
        self._flash_ok("Back to the default layout")

    def _layout_go_favourite(self):
        fav = self.cfg.get(self._layout_cfg_key("fav"))
        if not isinstance(fav, dict) or not fav:
            self._flash_ok("No favourite yet — press 📌 to pin this one")
            return
        self._layout_apply(fav)
        self._flash_ok("Your favourite layout")

    def _layout_save_favourite(self):
        snap = self._layout_snapshot()
        self.cfg[self._layout_cfg_key("fav")] = snap
        try:
            _save_settings(self.cfg)
        except Exception:
            pass
        self._flash_ok(f"Favourite saved — {snap['zoom']}/"
                       f"{snap['zoom_answer']} pt, {snap['w']}×{snap['h']}")

    def _layout_capture(self):
        """Called from _persist_geo as the window closes: remember both sizes
        and the splitter alongside the position that is being written anyway."""
        if not getattr(self, "_layout_key", None):
            return
        d = self._layout_defaults()
        for _kind, (attr, cfgname, _l) in self._ZOOM_KINDS.items():
            self.cfg[self._layout_cfg_key(cfgname)] = getattr(
                self, attr, d.get(cfgname, 10))
        self._layout_sash_save()

    # ── The strip itself, in two pieces ───────────────────────────────────────
    # It used to be one frame, and it sat at the far right of the window —
    # which is precisely where the ANSWER is, so it read as though it belonged
    # to the answer (Issu 2026-09-20: "knapparna hamnade längst till höger så
    # ser mer ut som kopplade till min svars-del"). Now each zoom group is
    # built on its own and each window puts it over the pane it acts on.
    _BAR_BTN_BG, _BAR_BTN_FG = C_BTN_STD, C_BTN_FG   # one word recolours them

    def _bar_button(self, bar, text, cmd, tip, pad=7):
        b = tk.Button(bar, text=text, bg=self._BAR_BTN_BG, fg=self._BAR_BTN_FG,
                      font=("Segoe UI", 8, "bold"), relief="flat",
                      cursor="hand2", padx=pad, pady=1, command=cmd)
        b.pack(side="left", padx=2)
        add_tooltip(b, tip)
        return b

    def _build_zoom_group(self, parent, kind, what, long_what):
        """A − / point size / A + for ONE of the two texts.

        `what` is the short caption on the strip and `long_what` the phrase the
        tooltips use: the caption has to name the pane without pushing the last
        button off a window at its minimum width."""
        _attr, _cfgname, lblattr = self._ZOOM_KINDS[kind]
        bar = tk.Frame(parent, bg=C_BG1)
        tk.Label(bar, text=f"🔍 {what}:", bg=C_BG1, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(side="left", padx=(8, 4))
        keys = ("Ctrl −" if kind == "answer" else "Ctrl+Shift −",
                "Ctrl +" if kind == "answer" else "Ctrl+Shift +")
        self._bar_button(bar, "A −", lambda: self._layout_zoom(-1, kind=kind),
                         f"Make {long_what} one point smaller ({keys[0]}).")
        # width=5, not 6: the clamp is 7–28 pt, so "28 pt" is the widest this
        # can ever read, and every pixel here is one the strip needs to fit
        # both halves on a single row.
        lbl = tk.Label(bar, text="", bg=C_BG1, fg=C_ACCENT,
                       font=("Segoe UI", 8, "bold"), width=5, anchor="center")
        lbl.pack(side="left")
        setattr(self, lblattr, lbl)
        self._bar_button(bar, "A +", lambda: self._layout_zoom(+1, kind=kind),
                         f"Make {long_what} one point bigger ({keys[1]}). "
                         f"Holding Ctrl and turning the mouse wheel over the "
                         f"text itself does the same, for whichever of the two "
                         f"you are pointing at.")
        return bar

    def _build_layout_buttons(self, parent):
        """↺ Default · ★ Favourite · 📌 Pin — about the WHOLE window (both
        sizes, the splitter and the window's own size), which is why they sit
        with the answer group rather than with either zoom on its own."""
        bar = tk.Frame(parent, bg=C_BG1)
        self._bar_button(bar, "↺ Default", self._layout_go_default,
           "Put both text sizes, the splitter and the window size back to "
           "what the program ships with — the way out when the remembered "
           "layout has drifted somewhere unusable.")
        self._bar_button(bar, "★ Favourite", self._layout_go_favourite,
           "Jump to the layout you pinned with 📌 Pin — both text sizes, the "
           "splitter and the window size, all at once.")
        self._bar_button(bar, "📌 Pin", self._layout_save_favourite,
           "Pin exactly what you are looking at right now — both text sizes, "
           "the splitter and the window size — as your favourite. ★ Favourite "
           "brings it back any time, in this window and every later one.")
        return bar

    def _recipients_max(self):
        """How many chips a To:/Cc:/Bcc: field shows before folding."""
        try:
            return int(self.cfg.get("compose_recipients_max", 3) or 0)
        except Exception:
            return 3

    def _fold_button(self, row, field, caption_lbl, caption):
        """The ▾ / ▴ beside a recipient caption (Issu 2026-09-20: "en
        expandera-knapp (bredvid CC?)").

        It is not there at all until there is something to fold, so an
        ordinary two-address reply looks exactly as it always did. Folded it
        reads "▾ 28" — the count stays visible even when the addresses do
        not, because "who else got this" and "how many else got this" are
        different questions and only the first one is in the way."""
        # Packed HERE, while the caption is still the last thing on the row —
        # the field itself is packed with expand=True a few lines later and
        # swallows the whole cavity, so a button that waited until its first
        # callback to pack itself ended up on the FAR RIGHT, beside the 📖
        # picker, which is the one place it does not belong.
        btn = tk.Label(row, text="", bg=C_BG3, fg=C_ACCENT, cursor="hand2",
                       font=("Segoe UI", 8, "bold"), padx=2)
        btn.pack(side="left", anchor="n", pady=(3, 0))
        btn.bind("<Button-1>", field.toggle_fold)
        add_tooltip(btn, lambda f=field, c=caption: (
            f"{c} holds {len(f._chips)} addresses. Click to show them all."
            if f.is_folded() else
            f"Fold {c} back to one row — nothing is removed, every address "
            f"still goes out."))

        def _changed(n, hidden, folded, foldable):
            # Emptied rather than un-packed: an empty label is 4 px wide and
            # invisible, and it keeps its place in the row so the button does
            # not jump somewhere else the first time it IS needed.
            if not foldable:
                btn.configure(text="")
                return
            btn.configure(text=(f"▾ {n}" if folded else "▴"))

        field._on_fold_change = _changed
        # Reachable by name afterwards (self._to_fold_btn / _cc_fold_btn /
        # _bcc_fold_btn) — the tests drive them, and a later feature that wants
        # to open a field from elsewhere should not have to go hunting through
        # the row's children for it.
        setattr(self, f"_{caption.lower()}_fold_btn", btn)
        return btn

    # ── One strip, two halves, and a row that appears only when needed ───────
    # Issu 2026-09-20: "det ser ut som att Originaldelens sak och Answerdelens
    # sak, skulle kunna vara på samma rad... spara en rads höjd."
    #
    # They can — when the window is wide enough. Side by side the two halves
    # want about 1170 px, so on a narrow window one row would mean cutting
    # buttons off the right-hand edge, which is exactly the thing the two rows
    # were there to avoid. So the strip decides for itself: ONE row while both
    # halves fit, TWO the moment they do not, re-checked every time the window
    # is resized. Drag the window wider and the second row folds up into the
    # first; drag it narrow again and it comes back.
    #
    # The two halves are children of `zone`, not of either row, because Tk only
    # lets you pack a widget into its own master or a descendant of it — being
    # a child of the container is what lets the same frame be moved between the
    # two rows without rebuilding it.
    def _build_reflow_strip(self, top):
        zone = tk.Frame(top, bg=C_BG1)
        zone.pack(fill="x")
        self._bar_zone  = zone
        self._bar_row1  = tk.Frame(zone, bg=C_BG1)
        self._bar_row1.pack(fill="x")
        self._bar_row2  = tk.Frame(zone, bg=C_BG1)     # packed only when needed
        self._bar_left  = tk.Frame(zone, bg=C_BG1)     # their half (may be empty)
        self._bar_right = tk.Frame(zone, bg=C_BG1)     # yours
        self._bar_left.pack(in_=self._bar_row1, side="left")
        self._bar_right.pack(in_=self._bar_row1, side="right")
        self._bar_one_row = True
        zone.bind("<Configure>", self._reflow_bar)
        return zone

    def _reflow_bar(self, event=None):
        """Put the two halves on one row, or on two, depending on the width."""
        zone = getattr(self, "_bar_zone", None)
        if zone is None:
            return
        avail = zone.winfo_width()
        if avail <= 1:
            return          # not laid out yet; the next <Configure> will do it
        need = (self._bar_left.winfo_reqwidth()
                + self._bar_right.winfo_reqwidth() + 16)
        one = avail >= need
        if one == self._bar_one_row:
            return          # nothing to change — and nothing to flicker
        self._bar_one_row = one
        try:
            self._bar_right.pack_forget()
            if one:
                self._bar_row2.pack_forget()
                self._bar_right.pack(in_=self._bar_row1, side="right")
            else:
                self._bar_row2.pack(fill="x")
                self._bar_right.pack(in_=self._bar_row2, side="right")
        except Exception as e:
            log.debug("strip reflow failed: %s", e)

    def _zoom_labels_refresh(self):
        """Put the current numbers on both labels, once the strip exists."""
        d = self._layout_defaults()
        for _kind, (attr, cfgname, lblattr) in self._ZOOM_KINDS.items():
            lbl = getattr(self, lblattr, None)
            if lbl is not None:
                try:
                    lbl.configure(
                        text=f"{getattr(self, attr, d.get(cfgname, 10))} pt")
                except Exception:
                    pass

    def _bind_zoom_keys(self, top, orig_widgets=(), answer_widgets=()):
        """Ctrl +/−/0 size YOUR text — that is where the cursor is — and
        Ctrl+Shift the same three size THEIRS. Ctrl with the mouse wheel sizes
        whichever pane the pointer is actually over, which needs no rule at
        all to remember."""
        d = self._layout_defaults()

        def _step(delta, kind):
            return lambda e: self._layout_zoom(delta, kind=kind)

        def _reset(kind):
            _a, cfgname, _l = self._ZOOM_KINDS[kind]
            return lambda e: self._layout_zoom(
                absolute=d.get(cfgname, 10), kind=kind)

        for seq, fn in (
                ("<Control-plus>",             _step(+1, "answer")),
                ("<Control-equal>",            _step(+1, "answer")),
                ("<Control-KP_Add>",           _step(+1, "answer")),
                ("<Control-minus>",            _step(-1, "answer")),
                ("<Control-KP_Subtract>",      _step(-1, "answer")),
                ("<Control-0>",                _reset("answer")),
                ("<Control-Shift-plus>",       _step(+1, "orig")),
                ("<Control-Shift-equal>",      _step(+1, "orig")),
                ("<Control-Shift-KP_Add>",     _step(+1, "orig")),
                ("<Control-Shift-underscore>", _step(-1, "orig")),
                ("<Control-Shift-minus>",      _step(-1, "orig")),
                ("<Control-Shift-KP_Subtract>", _step(-1, "orig")),
                ("<Control-Shift-KeyPress-0>", _reset("orig"))):
            try:
                top.bind(seq, lambda e, f=fn: (f(e), "break")[1])
            except Exception:
                pass

        def _wheel_for(kind):
            def _w(e):
                self._layout_zoom(+1 if getattr(e, "delta", 0) > 0 else -1,
                                  kind=kind)
                return "break"
            return _w
        for widgets, kind in ((orig_widgets, "orig"),
                              (answer_widgets, "answer")):
            for w in widgets:
                if w is None:
                    continue
                try:
                    w.bind("<Control-MouseWheel>", _wheel_for(kind))
                except Exception:
                    pass


# ******************************************************************************
# DEL 06 — COMPOSE WINDOW
# ******************************************************************************

class ComposeWindow(_RecipientFields):
    """New message / Reply / Forward compose dialog.

    Parameters
    ----------
    accounts      : list of account dicts (same as FreemailApp._accounts,
                    but WITHOUT the All-Accounts virtual entry)
    default_from  : email address to pre-select in the From: dropdown.
                    When replying from the unified view this is the
                    account_email of the received message.
    """

    def __init__(self, parent_root, settings, app=None, accounts=None,
                 default_from=None, reply_to=None, forward_msg=None,
                 draft=None, prefill=None, note_mode=False, reply_all=False):
        # note_mode: the same editor, but "Send" writes a local .eml note
        # instead of handing anything to SMTP (DEL 04g). Nothing in this
        # window can reach a server when it is on.
        self.note_mode = bool(note_mode)
        self.root     = parent_root
        self.app      = app          # FreemailApp — provides real SMTP send
        self.cfg      = settings
        self._attachments = []       # local file paths to send as attachments
        # ── Crash-safe draft (DEL 04d) ───────────────────────────────────────
        # `draft` is a restored draft dict; otherwise we start a fresh one.
        # _draft_dirty means "there are changes not yet written to disk" and
        # _draft_after is the pending autosave timer, so typing fast does not
        # write the file on every keystroke.
        self._draft       = dict(draft) if draft else {"id": _new_id(),
                                                       "kind": "compose"}
        self._draft.setdefault("id", _new_id())
        self._draft_after = None
        self._closing     = False
        # Current signature text sitting at the end of the body, so it can be
        # swapped out again when From: changes (see _apply_signature).
        self._cur_sig = ""
        self._prefill = prefill or {}   # from a mailto: link, or a template
        # Filter out the virtual All-Accounts entry — only real senders
        self._accounts = [a for a in (accounts or [])
                          if a.get("email") != ALL_ACCOUNTS_ID]
        self._default_from = default_from or (
            self._accounts[0]["email"] if self._accounts else "")

        top = tk.Toplevel(parent_root)
        top.title("New Note — F(re)email" if self.note_mode
                  else "New Message — F(re)email")
        top.configure(bg=C_BG3)
        # 620, not 560: the zoom/layout strip on the Reply row needs that much
        # to show its last button, and Smart Reply has used 620 all along
        # (Issu 2026-09-20).
        top.minsize(620, 460)
        # Reply/New/Forward all share ONE remembered spot ("compose") — opens
        # wherever you left it last time, or centred the very first time.
        self._geo_key = "compose"
        self._geo_w, self._geo_h = 1180, 620
        # Zoom/splitter/favourite live under the same name as the remembered
        # position, and are read BEFORE the widgets exist so the original pane
        # is built at the size you left it at (Issu 2026-09-20). A New message
        # or a Forward has no original text; the bar is simply not built there.
        self._layout_key = "compose"
        self._layout_zoom_init()
        self._apply_remembered_geometry(top, parent_root, self._geo_w, self._geo_h)
        top.bind("<Configure>", self._on_geo_configure)
        # NOT modal, and deliberately NOT transient (Issu 2026-08-08).
        #
        # A compose/reply window used to grab_set(), which froze the whole main
        # window: you could move the mouse and highlight rows, but clicking a
        # folder or another message did nothing — "meningslöst". Writing a mail
        # is exactly when you need to go and look something up in another
        # folder, so this window is now an ordinary independent window. It has
        # its own taskbar entry, the main window stays fully usable behind it,
        # and everything else in the program keeps its grab_set (a real dialog
        # SHOULD be modal — this is not a dialog, it is a document).
        #
        # Escape is bound but no longer closes it outright, for the same reason:
        # a stray Escape must not throw away a half-written mail while you are
        # clicking around. It just steps back to the main window.
        top.focus_force()
        top.bind("<Escape>", lambda e: self._to_background())
        top.protocol("WM_DELETE_WINDOW", lambda: self._discard(top))
        self.top = top

        self._build_ui(top, reply_to, forward_msg, reply_all)
        self._restore_draft(draft)
        self._apply_prefill()
        self._apply_signature(initial=True)
        self._watch_for_changes()

    # ── Layout ────────────────────────────────────────────────────────────────
    def _build_ui(self, top, reply_to, forward_msg, reply_all=False):
        # Toolbar
        tb = tk.Frame(top, bg=C_BG1, pady=4)
        tb.pack(fill="x")
        self._send_btn = tk.Button(
            tb, text="🗒 Save note" if self.note_mode else "✉ Send",
            bg=C_BTN_NOTE if self.note_mode else C_BTN_NEW, fg=C_BTN_FG,
            font=("Segoe UI", 9, "bold"), relief="flat",
            padx=12, pady=3,
            command=lambda: self._do_send(top))
        self._send_btn.pack(side="left", padx=6)
        # ── Send later (DEL 06c) — the same outbox that powers undo-send ──────
        # A note has nowhere to go later, so the button is simply not there.
        if not self.note_mode:
            # Send & archive — only where it means anything: a REPLY, which is
            # the case where the conversation is finished with.
            if reply_to is not None:
                sa_btn = tk.Button(tb, text="✉ Send & archive", bg=C_BTN_LATER,
                          fg=C_BTN_FG, font=("Segoe UI", 9), relief="flat",
                          padx=8, pady=3,
                          command=lambda: self._do_send(top, archive=True))
                sa_btn.pack(side="left", padx=2)
                add_tooltip(sa_btn, "Send this reply AND move the whole "
                                    "conversation out of the Inbox in one click.")
            # ── Send and save (DEL 09p) ──────────────────────────────────────
            # The third Send. Goes out exactly like the first one — same
            # outbox, same undo window — and marks the copy that lands in Sent
            # as protected, so a mass-selection there cannot take it with the
            # rest (Issu 2026-09-15).
            ss_btn = tk.Button(tb, text="✉🔒 Send and save", bg=C_BTN_KEEP,
                      fg=C_BTN_FG, font=("Segoe UI", 9), relief="flat",
                      padx=8, pady=3,
                      command=lambda: self._do_send(top, protect=True))
            ss_btn.pack(side="left", padx=2)
            add_tooltip(ss_btn, "Send it, and protect the copy in Sent: a "
                                "delete that takes several messages at once "
                                "skips it, and deleting it on its own asks "
                                "first. Right-click → 🔓 Unprotect undoes it.")
            sl_btn = tk.Button(tb, text="🕒 Send later", bg=C_BTN_LATER, fg=C_BTN_FG,
                      font=("Segoe UI", 9), relief="flat",
                      padx=8, pady=3,
                      command=self._send_later_dialog)
            sl_btn.pack(side="left", padx=2)
            add_tooltip(sl_btn, "Pick a time and queue the message to go out "
                                "then. It waits in the Outbox until it's due.")
        tk.Button(tb, text="🗑 Discard", bg=C_BTN_DEL, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat",
                  padx=8, pady=3,
                  command=lambda: self._discard(top)).pack(side="left", padx=2)
        tk.Button(tb, text="📎 Attach", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat",
                  padx=8, pady=3,
                  command=self._add_attachment).pack(side="left", padx=2)
        tk.Button(tb, text="📄 Template", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat",
                  padx=8, pady=3,
                  command=self._template_menu).pack(side="left", padx=2)
        self._build_position_menu(tb)
        self._attach_lbl = tk.Label(tb, text="", bg=C_BG1, fg=C_FG_DIM,
                                    font=("Segoe UI", 8))
        self._attach_lbl.pack(side="left", padx=6)

        # Header fields
        hdr = tk.Frame(top, bg=C_BG3, padx=10, pady=6)
        hdr.pack(fill="x")

        def _lbl(parent, text):
            # The caption MUST be a child of its OWN row frame — not of `hdr`.
            # When it was parented to `hdr` the labels packed into the header's
            # leftover cavity instead of beside their fields, so every caption
            # drifted a row down-and-right in a diagonal "staircase" (it looked
            # like "From:/To:/Cc:/Subject: are on the row below their field, and
            # adding Bcc made it two rows below"). Issu 2026-08-01. width=8 so
            # "Subject:" is not clipped; anchor="e" right-aligns them into a
            # tidy column.
            return tk.Label(parent, text=text, bg=C_BG3, fg=C_FG_DIM,
                            font=("Segoe UI", 9), width=8, anchor="e")

        # ── From: dropdown ────────────────────────────────────────────────────
        row_from = tk.Frame(hdr, bg=C_BG3)
        row_from.pack(fill="x", pady=2)
        _lbl(row_from, "From:").pack(side="left")

        # Build sender list: "Name <email>" strings
        sender_options = []
        for a in self._accounts:
            label = f"{a['name']} <{a['email']}>" if a.get("name") else a["email"]
            sender_options.append(label)

        # Pre-select default
        def _email_to_option(email):
            for opt in sender_options:
                if email in opt:
                    return opt
            return sender_options[0] if sender_options else ""

        # Determine correct default
        if reply_to and reply_to.get("account_email"):
            init_from = _email_to_option(reply_to["account_email"])
        elif forward_msg and forward_msg.get("account_email"):
            init_from = _email_to_option(forward_msg["account_email"])
        else:
            init_from = _email_to_option(self._default_from)

        self._from_var = tk.StringVar(value=init_from)
        # Changing the sender swaps the signature (DEL 04d) — the signature is
        # a property of the ACCOUNT, so picking another From: must not leave
        # the previous account's sign-off sitting at the bottom.
        self._from_var.trace_add("write", lambda *a: self._apply_signature())

        if sender_options:
            om = tk.OptionMenu(row_from, self._from_var, *sender_options)
            om.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                         activeforeground=C_FG, highlightthickness=0,
                         relief="flat", font=("Segoe UI", 9), anchor="w",
                         padx=6, pady=2)
            om["menu"].configure(bg=C_BG2, fg=C_FG,
                                 activebackground=C_BG4, activeforeground=C_FG,
                                 font=("Segoe UI", 9))
            om.pack(side="left", fill="x", expand=True)
        else:
            # Fallback if no accounts loaded yet
            tk.Label(row_from, text=self._default_from,
                     bg=C_BG2, fg=C_FG,
                     font=("Segoe UI", 9)).pack(side="left", fill="x", expand=True)

        # Small "pick from the address book" button for a recipient field
        # (the button itself and the picker live in the shared mixin, DEL 05b,
        # so Smart Reply has exactly the same one).
        _pick_btn = self._pick_btn

        # ── To: ───────────────────────────────────────────────────────────────
        row_to = tk.Frame(hdr, bg=C_BG3)
        row_to.pack(fill="x", pady=2)
        _cap_to = _lbl(row_to, "To:")
        _cap_to.pack(side="left", anchor="n", pady=(3, 0))
        self.e_to = _ChipEntry(row_to, "To", collapse_over=self._recipients_max(),
                             bg=C_BG2, fg=C_FG, relief="flat",
                             insertbackground=C_ACCENT, font=("Segoe UI", 10),
                             insertofftime=0, insertontime=9999999)
        no_blink(self.e_to)
        self._fold_button(row_to, self.e_to, _cap_to, "To")
        _pick_btn(row_to, lambda: self.e_to, "To")
        self.e_to.pack(side="left", fill="x", expand=True, ipady=3)
        _reply_all_cc_addr = ""
        if reply_to:
            # Reply to the SENDER — but if that is one of your own accounts
            # (replying to your own message), reply to the original recipients
            # instead, so the mail never comes back addressed to yourself
            # (Issu 2026-08-03).
            _reply_to_addr = _reply_to_address(
                reply_to, [a.get("email") for a in self._accounts])
            self.e_to.insert(0, _reply_to_addr)
            if reply_all:
                # Everyone else who was on the original message (its To: and
                # Cc:), minus you and minus whoever is already in To: above
                # (DEL: Reply All, Issu 2026-08-04).
                _reply_all_cc_addr = _reply_all_cc(
                    reply_to, [a.get("email") for a in self._accounts],
                    _reply_to_addr)
        # Cc:
        row_cc = tk.Frame(hdr, bg=C_BG3)
        row_cc.pack(fill="x", pady=2)
        _cap_cc = _lbl(row_cc, "Cc:")
        _cap_cc.pack(side="left", anchor="n", pady=(3, 0))
        self.e_cc = _ChipEntry(row_cc, "Cc", collapse_over=self._recipients_max(),
                             bg=C_BG2, fg=C_FG, relief="flat",
                             insertbackground=C_ACCENT, font=("Segoe UI", 10),
                             insertofftime=0, insertontime=9999999)
        no_blink(self.e_cc)
        self._fold_button(row_cc, self.e_cc, _cap_cc, "Cc")
        _pick_btn(row_cc, lambda: self.e_cc, "Cc")
        self.e_cc.pack(side="left", fill="x", expand=True, ipady=3)
        if _reply_all_cc_addr:
            self.e_cc.insert(0, _reply_all_cc_addr)

        # Bcc:  (Issu asked for a real Bcc row — recipients here are hidden from
        # everyone else on the message)
        row_bcc = tk.Frame(hdr, bg=C_BG3)
        row_bcc.pack(fill="x", pady=2)
        _cap_bcc = _lbl(row_bcc, "Bcc:")
        _cap_bcc.pack(side="left", anchor="n", pady=(3, 0))
        self.e_bcc = _ChipEntry(row_bcc, "Bcc",
                              collapse_over=self._recipients_max(),
                              bg=C_BG2, fg=C_FG, relief="flat",
                              insertbackground=C_ACCENT, font=("Segoe UI", 10),
                              insertofftime=0, insertontime=9999999)
        no_blink(self.e_bcc)
        self._fold_button(row_bcc, self.e_bcc, _cap_bcc, "Bcc")
        _pick_btn(row_bcc, lambda: self.e_bcc, "Bcc")
        self.e_bcc.pack(side="left", fill="x", expand=True, ipady=3)

        # Say out loud how a SECOND address gets in (Issu 2026-08-29). Once one
        # chip exists the field explains itself, but an empty box looked exactly
        # like a box that holds one address — which is why the address book
        # ended up being used as a way to commit hand-typed text.
        tk.Label(hdr,
                 text="Writing to several people?  Type an address and press "
                      "Enter (or a comma) — it turns into a chip and the field "
                      "is ready for the next one.   📖 picks from your "
                      "contacts.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 anchor="w", justify="left", wraplength=680
                 ).pack(fill="x", pady=(1, 3))

        # Chips can now be right-clicked to jump straight between To/Cc/Bcc
        # (Issu 2026-08-05) — wire each field up to its two siblings.
        _sibs = {"To": self.e_to, "Cc": self.e_cc, "Bcc": self.e_bcc}
        for _f in _sibs.values():
            _f.sibling_fields = _sibs

        # Address-book autocomplete popup — now on all three fields, not just
        # To: (Issu 2026-08-10). Each field keeps its old plain-Enter target
        # (To: → Subject, Cc: → Bcc, Bcc: → Subject) for when no popup is open.
        self._wire_autocomplete(self.e_to,  next_focus=lambda: self.e_subj.focus_set())
        self._wire_autocomplete(self.e_cc,  next_focus=lambda: self.e_bcc.focus_set())
        self._wire_autocomplete(self.e_bcc, next_focus=lambda: self.e_subj.focus_set())

        # "Hide recipients from each other" — the one-click group-mail privacy
        # switch Issu asked for. On send, To/Cc/Bcc are all moved into Bcc and
        # the message is addressed to your own account, so nobody sees anyone
        # else's address (classic BCC-a-group).
        row_priv = tk.Frame(hdr, bg=C_BG3)
        row_priv.pack(fill="x", pady=(0, 2))
        _lbl(row_priv, "").pack(side="left")   # blank caption → aligns the box under the fields  # align under fields
        self._hide_recips = tk.BooleanVar(value=False)
        priv_cb = tk.Checkbutton(
            row_priv,
            text="🔒  Send to me only — put every other recipient in Bcc "
                 "(they can't see each other)",
            variable=self._hide_recips,
            bg=C_BG3, fg=C_FG_DIM, selectcolor=C_BG1,
            activebackground=C_BG3, activeforeground=C_FG,
            font=("Segoe UI", 8), highlightthickness=0, relief="flat", anchor="w")
        priv_cb.pack(side="left", fill="x", expand=True)
        add_tooltip(priv_cb,
                    "For mailing a group without exposing addresses: everyone "
                    "you listed (To, Cc and Bcc) is moved into Bcc, and the "
                    "message is sent to your own address. Each person sees only "
                    "themselves and you.")

        # Subject:
        row_s = tk.Frame(hdr, bg=C_BG3)
        row_s.pack(fill="x", pady=2)
        _lbl(row_s, "Subject:").pack(side="left")
        self.e_subj = tk.Entry(row_s, bg=C_BG2, fg=C_FG, relief="flat",
                               insertbackground=C_ACCENT, font=("Segoe UI", 10, "bold"),
                               insertofftime=0, insertontime=9999999)
        no_blink(self.e_subj)
        self._guard_text_entry(self.e_subj, "Subject")
        self.e_subj.pack(side="left", fill="x", expand=True, ipady=3)
        self.e_subj.bind("<Return>", lambda e: self.t_body.focus_set())

        # Prefill subject
        if reply_to:
            subj = reply_to.get("subject", "")
            self.e_subj.insert(0, "Re: " + subj if not subj.startswith("Re:") else subj)
        elif forward_msg:
            self.e_subj.insert(0, "Fwd: " + forward_msg.get("subject", ""))

        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x")

        # ── Often-used text (DEL 04d2, Issu 2026-09-01) ──────────────────────
        # Its own slim row directly above the writing area, not up in the send
        # toolbar: that row already carries six buttons at a 680 px default
        # width, and three more would push Send off the edge. Here they also
        # sit next to the thing they act on. Built BEFORE the body — the
        # commands only touch self.t_body when clicked, by which time it
        # exists. Shared by New message, Reply, Forward and Note.
        # Remember the message being replied to (for optional quoting on send).
        # Set BEFORE the snippet bar is built: that row now also carries the
        # answer zoom, whose caption depends on whether this is a reply.
        self._reply_to = reply_to
        self._quote_on_send = tk.BooleanVar(value=True)

        self._build_reflow_strip(top)
        self._build_snippet_bar(top)

        if reply_to:
            # ── Reply: original (read-only, left) | your answer (right) ────────
            # The received text stays visible beside where you type, and your
            # answer box starts CLEAN (no quoted wall of text). Tick "Quote
            # original on send" to append the quote — keeps just this one round,
            # never a multi-level chain.
            #
            # The tick and the original's own zoom go into the strip's LEFT
            # half, directly over the pane they belong to. The whole strip used
            # to sit far right, where it read as though it belonged to the
            # answer (Issu 2026-09-20).
            qrow = tk.Frame(self._bar_left, bg=C_BG1)
            qrow.pack(side="left")
            tk.Checkbutton(qrow, text="Quote original on send",
                           variable=self._quote_on_send,
                           bg=C_BG1, fg=C_FG_DIM, selectcolor=C_BG2,
                           activebackground=C_BG1, activeforeground=C_FG,
                           font=("Segoe UI", 8), highlightthickness=0,
                           relief="flat", padx=8, pady=2).pack(side="left")
            self._build_zoom_group(qrow, "orig", "Original",
                                   "the original message").pack(side="left")

            split = tk.PanedWindow(top, orient="horizontal", bg=C_SEP,
                                   sashwidth=4, sashrelief="flat", handlesize=0)
            split.pack(fill="both", expand=True)
            self._reply_split = split

            # Left: original message (read-only)
            orig_frame = tk.Frame(split, bg=C_BG3)
            split.add(orig_frame, minsize=180, width=290)
            tk.Label(orig_frame,
                     text=f"  Original — {reply_to.get('from_name','') or reply_to.get('from','')}",
                     bg=C_BG1, fg=C_FG_DIM, font=("Segoe UI", 8, "bold"),
                     anchor="w", pady=3).pack(fill="x")
            o_sb = tk.Scrollbar(orig_frame, bg=C_BG3, troughcolor=C_BG1)
            o_sb.pack(side="right", fill="y")
            t_orig = tk.Text(orig_frame, bg=C_BG3, fg=C_FG_DIM,
                             font=("Segoe UI", getattr(self, "_zoom_pt", 9)),
                             relief="flat", wrap="word",
                             padx=8, pady=6, yscrollcommand=o_sb.set,
                             insertofftime=0, insertontime=9999999)
            no_blink(t_orig)
            self.t_orig = t_orig
            o_sb.configure(command=t_orig.yview)
            t_orig.pack(fill="both", expand=True)
            t_orig.insert("1.0",
                f"From: {reply_to.get('from','')}\n"
                f"Subject: {reply_to.get('subject','')}\n"
                f"Date: {reply_to.get('date','')}\n"
                f"{'-'*32}\n\n{reply_to.get('body','')}")
            t_orig.configure(state="disabled")
            _bind_mousewheel(t_orig, None)

            # Right: your clean answer
            ans_frame = tk.Frame(split, bg=C_BG2)
            split.add(ans_frame, minsize=240)
            a_sb = tk.Scrollbar(ans_frame, bg=C_BG3, troughcolor=C_BG1)
            a_sb.pack(side="right", fill="y")
            self.t_body = tk.Text(ans_frame, bg=C_BG2, fg=C_FG,
                                  insertbackground=C_ACCENT,
                                  font=("Segoe UI",
                                        getattr(self, "_zoom_pt_answer", 10)),
                                  relief="flat", padx=10, pady=8, wrap="word",
                                  yscrollcommand=a_sb.set,
                                  insertofftime=0, insertontime=9999999)
            no_blink(self.t_body)
            a_sb.configure(command=self.t_body.yview)
            self.t_body.pack(fill="both", expand=True)
            self.t_body.focus_set()

            # Ctrl-wheel over a pane sizes THAT pane; the keyboard shortcuts
            # size your own text, with Shift for theirs.
            self._bind_zoom_keys(top, orig_widgets=(t_orig,),
                                 answer_widgets=(self.t_body,))
            self._zoom_labels_refresh()
            # The splitter is placed in PIXELS, so it has to wait until the
            # window has a real width — after(120) rather than straight away,
            # which is the same reason the message list re-fits its text boxes
            # on a delay. The strip is measured then too: its left half was
            # filled after the strip itself was built, so the first <Configure>
            # sized it while it was still empty.
            top.after(120, self._layout_sash_restore)
            top.after(120, self._reflow_bar)
        else:
            # ── New message / Forward: single body box ─────────────────────────
            body_frame = tk.Frame(top, bg=C_BG2)
            body_frame.pack(fill="both", expand=True)
            self.t_body = tk.Text(body_frame, bg=C_BG2, fg=C_FG,
                                  insertbackground=C_ACCENT,
                                  font=("Segoe UI",
                                        getattr(self, "_zoom_pt_answer", 10)),
                                  relief="flat", padx=10, pady=8, wrap="word",
                                  insertofftime=0, insertontime=9999999)
            no_blink(self.t_body)
            sb = tk.Scrollbar(body_frame, command=self.t_body.yview,
                              bg=C_BG3, troughcolor=C_BG1)
            sb.pack(side="right", fill="y")
            self.t_body.configure(yscrollcommand=sb.set)
            self.t_body.pack(fill="both", expand=True)

            # No original here, so only your own text can be sized — but it
            # is sized the same way, from the same remembered setting.
            self._bind_zoom_keys(top, answer_widgets=(self.t_body,))
            self._zoom_labels_refresh()

            if forward_msg:
                self.t_body.insert("1.0",
                    f"\n\n--- Forwarded message ---\n"
                    f"From: {forward_msg.get('from','')}\n"
                    f"Subject: {forward_msg.get('subject','')}\n\n"
                    f"{forward_msg.get('body','')}")
                self.t_body.mark_set("insert", "1.0")
            self.e_to.focus_set()

    # ── The three layout hooks the shared machinery calls (Issu 2026-09-20) ──
    # Only a REPLY has an original pane and a splitter, so each of these is a
    # no-op in a New message / Forward / Note window rather than an error.
    def _layout_set_zoom(self, pt):
        w = getattr(self, "t_orig", None)
        if w is not None:
            w.configure(font=("Segoe UI", int(pt)))

    def _layout_set_zoom_answer(self, pt):
        w = getattr(self, "t_body", None)
        if w is not None:
            w.configure(font=("Segoe UI", int(pt)))

    def _layout_get_sash(self):
        sp = getattr(self, "_reply_split", None)
        if sp is None:
            return 0
        return int(sp.sash_coord(0)[0])

    def _layout_set_sash(self, value):
        sp = getattr(self, "_reply_split", None)
        if sp is None:
            return
        # Never leave either half too narrow to use, however odd the remembered
        # number is (a favourite pinned on a wide monitor, opened on a laptop).
        total = max(1, sp.winfo_width())
        sp.sash_place(0, max(180, min(int(value), total - 240)), 1)

    # ── Signature (per account, shared between accounts) ───────────────────────
    def _from_email(self) -> str:
        """The bare address of whatever the From: dropdown currently shows."""
        raw = (self._from_var.get() if hasattr(self, "_from_var")
               else self._default_from)
        return parseaddr(raw)[1] or raw

    def _apply_signature(self, initial=False):
        """Put the current account's signature at the end of the body, taking
        the previous account's signature away first.

        Only the block we ourselves appended is removed, and only if it is
        still sitting untouched at the very end — if you edited the signature
        by hand it stays exactly as you left it, and the new one is appended
        below rather than silently eating your text."""
        if self.app is None or not hasattr(self, "t_body"):
            return
        try:
            new_sig = _signature_for(self.app._signature_store, self._from_email())
        except Exception:
            new_sig = ""
        old_block = ("\n\n-- \n" + self._cur_sig) if self._cur_sig else ""
        new_block = ("\n\n-- \n" + new_sig) if new_sig else ""
        if old_block == new_block:
            return
        body = self.t_body.get("1.0", "end-1c")
        if old_block and body.endswith(old_block):
            body = body[: -len(old_block)]
        self.t_body.delete("1.0", "end")
        self.t_body.insert("1.0", body + new_block)
        self._cur_sig = new_sig
        if initial:
            # Put the caret where you actually want to start writing: at the
            # very top for a reply, after the forwarded/blank area otherwise —
            # never below the signature.
            self.t_body.mark_set("insert", "1.0")

    # ── Draft handling (crash-safe autosave) ──────────────────────────────────
    def _restore_draft(self, draft):
        """Refill every field from a draft dict (start-up restore, or an
        undo-send that was cancelled)."""
        if not draft:
            return
        try:
            if draft.get("to"):
                self.e_to.delete(0, "end"); self.e_to.insert(0, draft["to"])
            if draft.get("cc") and hasattr(self, "e_cc"):
                self.e_cc.delete(0, "end"); self.e_cc.insert(0, draft["cc"])
            if draft.get("bcc") and hasattr(self, "e_bcc"):
                self.e_bcc.delete(0, "end"); self.e_bcc.insert(0, draft["bcc"])
            if draft.get("subject"):
                self.e_subj.delete(0, "end")
                self.e_subj.insert(0, draft["subject"])
            if draft.get("body"):
                self.t_body.delete("1.0", "end")
                self.t_body.insert("1.0", draft["body"])
                # The restored body already contains its signature — remember
                # that so a later From: change swaps it correctly.
                self._cur_sig = draft.get("signature", "") or ""
            for p in (draft.get("attachments") or []):
                if os.path.isfile(p) and p not in self._attachments:
                    self._attachments.append(p)
            if self._attachments:
                self._update_attach_label()
            if draft.get("from"):
                # Re-select the stored sender if it is still one of ours.
                for a in self._accounts:
                    if a.get("email") == draft["from"]:
                        label = (f"{a['name']} <{a['email']}>" if a.get("name")
                                 else a["email"])
                        self._from_var.set(label)
                        break
        except Exception as e:
            log.warning("Could not fully restore draft: %s", e)

    def _apply_prefill(self):
        """Fill in fields handed over from a mailto: link or a template."""
        p = self._prefill
        if not p:
            return
        try:
            if p.get("to"):
                self.e_to.delete(0, "end"); self.e_to.insert(0, p["to"])
            if p.get("cc") and hasattr(self, "e_cc"):
                self.e_cc.delete(0, "end"); self.e_cc.insert(0, p["cc"])
            if p.get("subject"):
                self.e_subj.delete(0, "end")
                self.e_subj.insert(0, p["subject"])
            if p.get("body"):
                self.t_body.insert("1.0", p["body"])
        except Exception as e:
            log.warning("Could not apply prefill: %s", e)

    def _watch_for_changes(self):
        """Autosave a few seconds after you stop typing, in every field."""
        for w in (getattr(self, "e_to", None), getattr(self, "e_cc", None),
                  getattr(self, "e_bcc", None), getattr(self, "e_subj", None),
                  getattr(self, "t_body", None)):
            if w is not None:
                w.bind("<KeyRelease>", self._touch_draft, add="+")

    def _draft_snapshot(self) -> dict:
        d = dict(self._draft)
        d.update({
            "kind":        "compose",
            "from":        self._from_email(),
            "to":          self.e_to.get().strip(),
            "cc":          self.e_cc.get().strip() if hasattr(self, "e_cc") else "",
            "bcc":         self.e_bcc.get().strip() if hasattr(self, "e_bcc") else "",
            "subject":     self.e_subj.get().strip(),
            "body":        self.t_body.get("1.0", "end-1c"),
            "attachments": list(self._attachments),
            "signature":   self._cur_sig,
        })
        return d

    def _touch_draft(self, event=None):
        """Schedule an autosave. Restarting the timer on every keystroke means
        the file is written once you pause, not 60 times a minute."""
        if self._closing:
            return
        if self._draft_after is not None:
            try:
                self.top.after_cancel(self._draft_after)
            except Exception:
                pass
        self._draft_after = self.top.after(2500, self._flush_draft)

    def _flush_draft(self):
        self._draft_after = None
        if self._closing:
            return
        try:
            snap = self._draft_snapshot()
            if _draft_is_empty(snap, ignore_prefill=bool(getattr(self, "_reply_to", None))):
                return
            self._draft = snap
            _save_draft(self._draft)
        except Exception as e:
            log.warning("Draft autosave failed: %s", e)

    # ── Templates ─────────────────────────────────────────────────────────────
    # ── Often-used text: two one-click buttons + a ▾ list (DEL 04d2) ──────────
    def _snippet_store(self) -> dict:
        """The saved snippets. Falls back to an empty store when this window
        was opened without an app (headless tests, and the note editor before
        the app finishes starting) — the bar must never be the thing that
        stops you writing a mail."""
        st = getattr(self.app, "_snippet_store", None) if self.app else None
        return st if isinstance(st, dict) else {"snippets": []}

    def _build_snippet_bar(self, top):
        """The row of "drop my usual text in here" buttons.

        Two direct buttons (slot 1 and slot 2) for the things used most, and a
        ▾ list for everything else — Issu 2026-09-01: "1 och 2 = jag kan lägga
        in en sak och behöver bara klicka på respektive knapp… X = dropdown där
        jag kan välja mellan olika alternativ." An unassigned button says
        "Add 1" and opens the editor, so an empty bar teaches what it is for
        instead of doing nothing."""
        # ── One right-hand cluster, all of it about YOUR text ────────────────
        # Issu 2026-09-20: "ADD-knapparna skulle kunna flyttas till innan de
        # nya Zoom, default o.s.v., för att tydligare visa att de har med
        # Answer-delen att göra." So the ➕ buttons, the answer zoom and the
        # three layout buttons travel together, right-aligned — which in a
        # Reply puts them directly over the box you type in, while the
        # original's own zoom sits on the left over the original.
        #
        # It goes into the strip's RIGHT half (_build_reflow_strip), which is
        # what lets the whole thing share a row with the original's half when
        # the window is wide enough to take both.
        bar = tk.Frame(self._bar_right, bg=C_BG1, pady=3)
        bar.pack(side="right")
        tk.Label(bar, text="Often-used text:", bg=C_BG1, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(side="left", padx=(8, 4))
        self._snip_btns = {}
        for slot, fallback in (("slot1", "Add 1"), ("slot2", "Add 2")):
            b = tk.Button(bar, text=f"➕ {fallback}", bg=C_BTN_STD, fg=C_BTN_FG,
                          font=("Segoe UI", 8), relief="flat", cursor="hand2",
                          padx=8, pady=2,
                          command=lambda s=slot: self._snippet_slot_click(s))
            b.pack(side="left", padx=2)
            # Right-click one to (re)assign it without a trip to the menu.
            b.bind("<Button-3>", lambda e, s=slot: self._snippet_assign_menu(s))
            # Attached ONCE, with a callable — add_tooltip's bindings stack,
            # so re-attaching on every refresh would leave the old text behind.
            add_tooltip(b, lambda s=slot: self._snippet_tip(s))
            self._snip_btns[slot] = b
        tk.Button(bar, text="➕ Add ▾", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 8), relief="flat", cursor="hand2",
                  padx=8, pady=2,
                  command=self._snippet_menu).pack(side="left", padx=2)

        tk.Frame(bar, bg=C_SEP, width=1).pack(side="left", fill="y",
                                              padx=(6, 0), pady=2)
        # "Answer" in a reply, "Message" when there is nothing to answer —
        # the caption has to be true in a New message window as well.
        _mine = "Answer" if self._reply_to is not None else "Message"
        self._build_zoom_group(bar, "answer", _mine,
                               "the box you type in").pack(side="left")
        tk.Frame(bar, bg=C_SEP, width=1).pack(side="left", fill="y",
                                              padx=(6, 0), pady=2)
        self._build_layout_buttons(bar).pack(side="left")
        self._refresh_snippet_bar()

    def _refresh_snippet_bar(self):
        """Re-label the two buttons from the store — called on build and again
        every time the editor saves, so a rename shows up in a window that is
        already open."""
        store = self._snippet_store()
        for slot, fallback in (("slot1", "Add 1"), ("slot2", "Add 2")):
            b = getattr(self, "_snip_btns", {}).get(slot)
            if b is None:
                continue
            try:
                b.configure(text="➕ " + _snippet_button_label(store, slot,
                                                              fallback))
            except Exception:
                pass

    def _snippet_tip(self, slot):
        """Hover text for a one-click button: what it will actually type."""
        store = self._snippet_store()
        rec = _snippet_by_id(store, store.get(slot) or "")
        if not rec:
            return ("Nothing on this button yet. Click it to pick a saved "
                    "text, or right-click to assign one.")
        return (f"Types this at the cursor:\n\n{_snip_preview(rec)}\n\n"
                f"Right-click the button to put something else on it.")

    def _insert_snippet(self, rec):
        """Drop a snippet in at the caret.

        The saved text goes in as typed — newlines and all — because only you
        know whether this one belongs mid-sentence (an address) or as its own
        block (a sign-off). The ONE thing added is a space where the text
        would otherwise run straight into the word beside it, and only when
        that snippet's tick-box says so (_snippet_spaced)."""
        if not rec:
            return
        text = rec.get("text") or ""
        if not text:
            return
        try:
            # The characters either side of the caret. "" at the very start;
            # at the end Tk's own trailing newline answers, which counts as
            # whitespace and so adds nothing.
            before = self.t_body.get("insert -1c", "insert")
            after  = self.t_body.get("insert", "insert +1c")
            text = _snippet_spaced(text, before, after,
                                   rec.get("space", True))
        except Exception:
            pass
        try:
            self.t_body.insert("insert", text)
            self.t_body.focus_set()
            self.t_body.see("insert")
        except Exception:
            return
        self._touch_draft()

    def _snippet_slot_click(self, slot):
        """Button 1 / 2: insert its snippet, or — when nothing is assigned yet
        — offer to assign one instead of doing nothing at all."""
        store = self._snippet_store()
        rec = _snippet_by_id(store, store.get(slot) or "")
        if rec:
            self._insert_snippet(rec)
        else:
            self._snippet_assign_menu(slot)

    def _snippet_assign_menu(self, slot):
        """Pick which saved snippet a button stands for (right-click, or a
        click on an empty one)."""
        store = self._snippet_store()
        snips = store.get("snippets") or []
        m = tk.Menu(self.top, tearoff=0, bg=C_BG2, fg=C_FG,
                    activebackground=C_BG4, activeforeground=C_FG)
        n = "1" if slot == "slot1" else "2"
        m.add_command(label=f"Put on button {n}:", state="disabled")
        if not snips:
            m.add_command(label="(nothing saved yet)", state="disabled")
        for s in snips:
            mark = "● " if store.get(slot) == s.get("id") else "   "
            m.add_command(label=mark + (s.get("name") or "(unnamed)"),
                          command=lambda ss=s: self._snippet_set_slot(slot,
                                                                      ss.get("id")))
        if store.get(slot):
            m.add_separator()
            m.add_command(label="Leave this button empty",
                          command=lambda: self._snippet_set_slot(slot, ""))
        m.add_separator()
        m.add_command(label="Edit often-used text…",
                      command=self._open_snippets_dialog)
        try:
            m.tk_popup(self.top.winfo_pointerx(), self.top.winfo_pointery())
        finally:
            m.grab_release()

    def _snippet_set_slot(self, slot, sid):
        store = self._snippet_store()
        store[slot] = sid or ""
        try:
            _save_snippets(store)
        except Exception as e:
            log.warning("could not save snippet slots: %s", e)
        self._refresh_snippet_bar()

    def _snippet_menu(self):
        """The ▾ list — everything saved, whether or not it is on a button."""
        store = self._snippet_store()
        snips = store.get("snippets") or []
        m = tk.Menu(self.top, tearoff=0, bg=C_BG2, fg=C_FG,
                    activebackground=C_BG4, activeforeground=C_FG)
        if not snips:
            m.add_command(label="(no often-used text yet)", state="disabled")
        for s in snips:
            m.add_command(label=(s.get("name") or "(unnamed)"),
                          command=lambda ss=s: self._insert_snippet(ss))
        m.add_separator()
        m.add_command(label="Edit often-used text…",
                      command=self._open_snippets_dialog)
        try:
            m.tk_popup(self.top.winfo_pointerx(), self.top.winfo_pointery())
        finally:
            m.grab_release()

    def _open_snippets_dialog(self):
        """Open the editor and re-label this window's buttons afterwards, so a
        rename or a re-assignment is visible without reopening the compose
        window."""
        if self.app is None:
            return
        try:
            self.app._snippets_dialog(on_close=self._refresh_snippet_bar)
        except Exception as e:
            log.warning("snippets dialog failed: %s", e)

    def _template_menu(self):
        """Drop-down of saved templates, inserted at the caret."""
        store = (self.app._template_store if self.app else {"templates": []})
        temps = store.get("templates", [])
        m = tk.Menu(self.top, tearoff=0, bg=C_BG2, fg=C_FG,
                    activebackground=C_BG4, activeforeground=C_FG)
        if not temps:
            m.add_command(label="(no templates yet)", state="disabled")
            m.add_separator()
            m.add_command(label="Manage templates…",
                          command=lambda: self.app and self.app._templates_dialog())
        else:
            for t in temps:
                m.add_command(label=t.get("name", "(unnamed)"),
                              command=lambda tt=t: self._insert_template(tt))
            m.add_separator()
            m.add_command(label="Manage templates…",
                          command=lambda: self.app and self.app._templates_dialog())
        try:
            m.tk_popup(self.top.winfo_pointerx(), self.top.winfo_pointery())
        finally:
            m.grab_release()

    def _insert_template(self, t):
        """Insert a template. Tokens are expanded against the message being
        replied to when there is one, so {sender} means the person you are
        answering — which is the only reading that makes sense in a reply."""
        ctx = getattr(self, "_reply_to", None) or {
            "_dt": _now_iso(), "from_name": "", "from": "",
            "account_email": self._from_email(), "subject": ""}
        subj = _expand_prefix(t.get("subject", "") or "", ctx)
        body = _expand_prefix(t.get("body", "") or "", ctx)
        if subj and not self.e_subj.get().strip():
            self.e_subj.insert(0, subj)
        if body:
            self.t_body.insert("insert", body)
        self._touch_draft()

    # ── Actions ───────────────────────────────────────────────────────────────
    def _add_attachment(self):
        from tkinter import filedialog
        paths = filedialog.askopenfilenames(
            parent=self.top, title="Attach files")
        for p in paths:
            if p and p not in self._attachments:
                self._attachments.append(p)
        self._update_attach_label()
        self._touch_draft()

    def _update_attach_label(self):
        """Show the count AND the size — the size is the part that decides
        whether Gmail will take the message at all."""
        n = len(self._attachments)
        if not n:
            self._attach_lbl.configure(text="", fg=C_FG_DIM)
            return
        info = _attachment_size_check(self._attachments)
        colour = "#ff9c9c" if info["over"] else (
            "#ffd08a" if info["warn"] else C_FG_DIM)
        self._attach_lbl.configure(
            text=f"{n} file(s), {info['text']}"
                 + ("   — too big for Gmail!" if info["over"] else ""),
            fg=colour)

    def _gather(self, top) -> dict:
        """Validate the form and build the outgoing payload, or return None
        (having already told the user what is missing)."""
        # ── Address hygiene (Issu 2026-08-01) ────────────────────────────────
        # Strip stray characters that had been creeping into addresses, and warn
        # about anything that still looks wrong (e.g. a mangled gmail domain)
        # BEFORE anything is queued.
        if not self._sanitize_recipients(top):
            return None
        to        = self.e_to.get().strip()
        cc        = self.e_cc.get().strip() if hasattr(self, "e_cc") else ""
        bcc       = self.e_bcc.get().strip() if hasattr(self, "e_bcc") else ""
        subj      = self.e_subj.get().strip()
        body      = self.t_body.get("1.0", "end-1c")
        from_addr = (self._from_var.get() if hasattr(self, "_from_var")
                     else self._default_from)
        # Bcc typed by hand — carried through to the payload; the privacy switch
        # and the long-list prompt below can add to it.
        self._bcc_list = [x.strip() for x in _re.split(r"[;,]", bcc) if x.strip()]

        # ── "Hide recipients from each other" switch (Issu 2026-08-01) ────────
        # Move To/Cc/Bcc all into Bcc and address the message to yourself, so no
        # recipient can see any other. Done before the "no recipient" check,
        # because with this on the To: field is deliberately emptied.
        if getattr(self, "_hide_recips", None) and self._hide_recips.get():
            everyone = ([x.strip() for x in _re.split(r"[;,]", to)  if x.strip()]
                        + [x.strip() for x in _re.split(r"[;,]", cc) if x.strip()]
                        + list(self._bcc_list))
            if not everyone:
                messagebox.showwarning(
                    "Missing recipient",
                    "Fill in at least one recipient — they'll be moved to Bcc.",
                    parent=top)
                return None
            me = parseaddr(from_addr)[1] or from_addr
            to, cc = me, ""
            self._bcc_list = everyone
            self._bcc_ok = True          # don't ALSO trigger the long-list prompt
            log.info("Privacy switch: %d recipients moved to Bcc", len(everyone))

        if not to:
            messagebox.showwarning("Missing recipient",
                                   "Please fill in the To: field.", parent=top)
            return None

        # Optionally append the quoted original (reply only) — single round,
        # no nested quote chain.
        if (getattr(self, "_reply_to", None) and
                getattr(self, "_quote_on_send", None) and
                self._quote_on_send.get()):
            orig = self._reply_to
            orig_body = (orig.get("body", "") or "").strip()
            if not orig_body:
                # An EMPTY quote used to go out as "On <date>, X wrote:" with
                # nothing under it — the reply looked like the original text
                # had simply been dropped, which is exactly what Issu saw on
                # 2026-08-08. It happens when the body had not finished
                # downloading. Say so instead of sending a hollow quote.
                if not messagebox.askyesno(
                        "Nothing to quote",
                        "“Quote original on send” is ticked, but the original "
                        "message has no text loaded — so nothing of theirs "
                        "would be included.\n\nSend anyway?\n\nSaying no lets "
                        "you close this, reopen the message and try again.",
                        parent=top, default="no"):
                    return None
                log.warning("Reply sent with an EMPTY quoted original "
                            "(body not loaded) — subject %r", subj[:60])
            else:
                # The same "indent their lines" setting Smart Reply uses, so
                # both kinds of reply look the same (Issu 2026-08-08).
                try:
                    steps = max(0, min(40,
                                       int(self.cfg.get(
                                           "smart_reply_quote_indent", 0))))
                except Exception:
                    steps = 0
                quoted = "\n".join("> " + ln
                                   for ln in orig_body.splitlines())
                quoted = _sr_indent(quoted, steps)
                body = (body.rstrip() +
                        f"\n\nOn {orig.get('date','')}, "
                        f"{orig.get('from_name','') or orig.get('from','')} "
                        f"wrote:\n{quoted}")

        # ── Attachment size (DEL 04e) ────────────────────────────────────────
        # Checked HERE rather than at send time, because with "send later" the
        # SMTP rejection would otherwise arrive hours after you walked away.
        if self._attachments:
            info = _attachment_size_check(self._attachments)
            if info["missing"]:
                names = "\n".join("  • " + os.path.basename(p)
                                  for p in info["missing"][:5])
                if not messagebox.askyesno(
                        "Missing attachment",
                        f"These attachments can no longer be found:\n\n{names}"
                        f"\n\nSend without them?", parent=top, default="no"):
                    return None
                self._attachments = [p for p in self._attachments
                                     if p not in info["missing"]]
                self._update_attach_label()
                info = _attachment_size_check(self._attachments)
            if info["over"]:
                messagebox.showerror(
                    "Attachments too big",
                    f"The attachments come to {info['text']}, and Gmail "
                    f"refuses anything over "
                    f"{_human_size(GMAIL_MAX_BYTES)}.\n\n"
                    f"Remove a file, or send a link to it instead.",
                    parent=top)
                return None
            if info["warn"] and not messagebox.askyesno(
                    "Large attachments",
                    f"The attachments come to {info['text']}, which is close "
                    f"to Gmail's {_human_size(GMAIL_MAX_BYTES)} limit and may "
                    f"be rejected by the recipient's mail server.\n\n"
                    f"Send anyway?", parent=top):
                return None

        # ── A long recipient list (DEL 04p) ──────────────────────────────────
        # Putting thirty people in To: shows every one of them the others'
        # addresses — and invites a reply-all avalanche. BCC is almost always
        # what was meant, so it is offered rather than just warned about.
        to_list = [x.strip() for x in _re.split(r"[;,]", to) if x.strip()]
        cc_list = [x.strip() for x in _re.split(r"[;,]", cc) if x.strip()]
        n_recipients = len(to_list) + len(cc_list)
        if n_recipients >= 5 and not getattr(self, "_bcc_ok", False):
            # Our own dialog, not Tk's: Tk labels its buttons through the
            # SYSTEM message catalogue, so on a Swedish Windows they read
            # "Ja / Nej / Avbryt" in an English-only program (Issu 2026-08-03).
            answer = ask_yes_no_cancel(
                top, "Several recipients",
                f"This goes to {n_recipients} people, and every one of them "
                f"will see the whole list of addresses.",
                yes="Put them all in BCC", no="Send as it is",
                cancel="Back to the message", icon="👥")
            if answer is None:
                return None
            if answer:
                # Sent to yourself, everyone else hidden. That is the
                # standard way to mail a group without publishing it. Any Bcc
                # typed by hand is kept.
                me = parseaddr(from_addr)[1] or from_addr
                bcc_all = to_list + cc_list + list(self._bcc_list)
                to, cc = me, ""
                self._bcc_list = bcc_all
                log.info("Sending to %d recipients as BCC", len(bcc_all))
            else:
                self._bcc_ok = True

        # ── Forgotten-attachment check (DEL 04e) ─────────────────────────────
        if not self._attachments:
            hint = _mentions_attachment(subj, body)
            if hint and not messagebox.askyesno(
                    "No attachment",
                    f'You wrote "{hint}" but nothing is attached.\n\n'
                    f"Send anyway?", parent=top, default="no"):
                return None

        in_reply_to, references = (
            _reply_threading_headers(self._reply_to) if self._reply_to else ("", ""))
        return {
            "from": from_addr, "to": to, "cc": cc, "subject": subj,
            "body": body, "attachments": list(self._attachments),
            "draft_id": self._draft.get("id", ""),
            "bcc": list(getattr(self, "_bcc_list", []) or []),
            "in_reply_to": in_reply_to, "references": references,
        }

    def _do_send(self, top, archive=False, protect=False):
        """Send it. protect=True is the "✉🔒 Send and save" button (DEL 09p) —
        the same send in every respect, plus the mark that makes the copy in
        Sent survive a mass delete."""
        # ── Note mode: write a file, talk to nobody ──────────────────────────
        if self.note_mode:
            self._save_note(top)
            return

        payload = self._gather(top)
        if payload is None:
            return
        # "Send & archive": the reply goes out and the conversation gets out
        # of the inbox in one action (DEL 09h).
        if archive and self.app is not None and getattr(self, "_reply_to", None):
            try:
                self.app._archive_out_of_inbox(self._reply_to, quiet=True)
            except Exception as e:
                log.warning("Archive after send failed: %s", e)
        if self.app is None:
            log.info("SEND (no backend) → from=%s  to=%s  protect=%s",
                     payload["from"], payload["to"], protect)
            self._close_after_send(top)
            self._flash_ok("Message sent and protected!" if protect
                           else "Message sent!")
            return
        # Hand over to the outbox. With undo-send on (the default) this only
        # QUEUES the message and shows the Cancel toast; the actual SMTP call
        # happens when the undo window runs out.
        self.app.queue_send(payload, when=None, kind="normal", protect=protect)
        try:
            self.app._remember_recipients(
                payload, is_reply=bool(getattr(self, "_reply_to", None)))
        except Exception:
            pass
        self._close_after_send(top)

    def _save_note(self, top):
        """Write this window's content to the local Notes folder.

        No recipient is required — a note to yourself does not need one — and
        no network call happens anywhere in this path."""
        subject = self.e_subj.get().strip()
        body    = self.t_body.get("1.0", "end-1c")
        if not subject.strip() and not body.strip():
            messagebox.showwarning("Empty note",
                                   "Write something first.", parent=top)
            return
        me = self._from_email()
        try:
            _note_write(self.cfg, subject=subject or "(no subject)",
                        body=body, from_addr=me, to_addr=me,
                        attachments=self._attachments)
        except Exception as e:
            log.error("Could not write note: %s", e)
            messagebox.showerror("Save note",
                                 f"Could not write the note:\n{e}", parent=top)
            return
        self._closing = True
        if self._draft_after is not None:
            try:
                top.after_cancel(self._draft_after)
            except Exception:
                pass
            self._draft_after = None
        _delete_draft(self._draft.get("id", ""))   # the note IS the saved copy
        self._persist_geo()
        try:
            top.destroy()
        except Exception:
            pass
        self._flash_ok("Note saved!")
        if self.app is not None and self.app._current_folder == "Notes":
            self.app._render_notes()

    def _send_later_dialog(self):
        """Ask when the message should go out, then queue it."""
        payload = self._gather(self.top)
        if payload is None:
            return
        when = _ask_send_time(self.top, self.root)
        if when is None:
            return
        if self.app is None:
            self._flash_ok("Scheduled! (demo)")
            self._close_after_send(self.top)
            return
        self.app.queue_send(payload, when=when, kind="normal")
        try:
            self.app._remember_recipients(
                payload, is_reply=bool(getattr(self, "_reply_to", None)))
        except Exception:
            pass
        self._close_after_send(self.top)

    def _close_after_send(self, top):
        """Close without the discard prompt, marking the draft as QUEUED.

        Not "sent" — the message has only reached the outbox at this point.
        The outbox flips it to "sent" when SMTP actually confirms, and the
        queued marker keeps the start-up restore from offering back a message
        that is already on its way (which would let you send it twice)."""
        self._closing = True
        if self._draft_after is not None:
            try:
                top.after_cancel(self._draft_after)
            except Exception:
                pass
            self._draft_after = None
        try:
            snap = self._draft_snapshot()
            snap["queued"] = _now_iso()
            _save_draft(snap)
        except Exception as e:
            log.warning("Could not mark draft as queued: %s", e)
        self._persist_geo()
        try:
            top.destroy()
        except Exception:
            pass

    def _to_background(self):
        """Escape: step back to the main window WITHOUT closing this one.

        The window is not modal any more (Issu 2026-08-08), so Escape's old
        job — "get me out of this dialog" — would now mean "throw away what I
        was writing", which is the last thing anyone wants. It simply hands
        focus back to the mailbox; the half-written message stays open behind
        it, and its taskbar entry brings it back."""
        try:
            self.root.focus_force()
            self.root.lift()
        except Exception:
            pass

    def _discard(self, top):
        """Closing with content asks what to do with it — losing ten minutes
        of typing to a stray Escape is exactly the thing this program is
        supposed to prevent."""
        snap = self._draft_snapshot()
        if not _draft_is_empty(snap, ignore_prefill=bool(getattr(self, "_reply_to", None))):
            # Our own three-button dialog. Tk's askyesnocancel takes its button
            # words from the SYSTEM message catalogue, so on Swedish Windows
            # this asked an English question and offered "Ja / Nej / Avbryt"
            # (Issu 2026-08-03). Here the buttons say what they DO.
            ans = ask_yes_no_cancel(
                top, "Unsent message",
                "Keep this message as a draft?\n\n"
                "Keep it  —  restored the next time you start\n"
                "Throw it away  —  the text is gone\n"
                "Keep writing  —  back to the message",
                yes="Keep it", no="Throw it away", cancel="Keep writing",
                icon="✉")
            if ans is None:
                return
            if ans:
                self._draft = snap
                _save_draft(self._draft)
            else:
                _delete_draft(snap.get("id", ""))
        else:
            _delete_draft(snap.get("id", ""))
        self._closing = True
        if self._draft_after is not None:
            try:
                top.after_cancel(self._draft_after)
            except Exception:
                pass
        self._persist_geo()
        top.destroy()

    def _flash_ok(self, msg):
        """The "Message sent!" confirmation.

        It used to open dead-centre over the window you were reading, on top of
        the message you had just gone back to. It is now the same kind of thing
        as the delete bar — a small toast in the bottom-right corner, in the
        SHARED stack, so a Send confirmation stands above a delete-undo bar or
        a follow-up reminder instead of hiding it (Issu 2026-08-03: "den där
        SEND-popup får bli som DELETE-popup … men inte på samma plats som
        Delete, så att de krockar"). Auto-closes after 1 second, house rule."""
        _sent_toast(self.root, msg)


# ******************************************************************************
# DEL 06b — SMART REPLY WINDOW
# ******************************************************************************

class SmartReplyWindow(_RecipientFields):
    """Inline-style reply: the received message is split into paragraphs,
    and you write your answer directly under the paragraph you're
    responding to, instead of one big quoted block at the bottom.

    Behaviour
    ---------
    - Only ONE paragraph is "open" (expanded, full text + an answer box
      under it) at a time. All other paragraphs are collapsed to a short
      one-line summary so the window stays manageable on long messages.
    - Clicking any paragraph (open or collapsed) makes IT the open one;
      whatever was open before collapses — but anything you already
      typed under it is kept (just hidden), so switching back and forth
      between paragraphs never loses text.
    - Sending does NOT build a nested ">>> quote" chain. Only the latest
      round is kept as the "base": the original message's paragraphs
      (for context) plus your interleaved answers. There is no reference
      to whatever THAT message was itself replying to.
    - "Include previous round" checkbox (default OFF, sender-side):
        OFF → only your own answer text is sent, concatenated in
              paragraph order — the cleanest possible message.
        ON  → the original paragraphs are sent too, each one immediately
              followed by your answer to it (quoted, dimmed-style marker)
              — i.e. exactly the "Q / your answer" pairing you typed,
              with nothing older than that single round.
    """

    def __init__(self, parent_root, settings, app=None, accounts=None,
                 default_from=None, reply_to=None, reply_all=False):
        self.root    = parent_root
        self.app     = app
        self.cfg     = settings
        self.reply_to = reply_to
        self._reply_all = bool(reply_all)
        self._accounts = [a for a in (accounts or [])
                          if a.get("email") != ALL_ACCOUNTS_ID]
        self._default_from = default_from or (
            self._accounts[0]["email"] if self._accounts else "")

        # Split the original message into answerable paragraphs — blank lines
        # first, falling back to one per line when there are none, so a message
        # without blank lines is not one giant block (Issu 2026-08-03). You can
        # still merge/split by hand with the ✂ / ⬆ buttons on the docked box.
        raw = (reply_to or {}).get("body", "")
        self._orig_paragraphs = _split_reply_paragraphs(raw)

        # One string per paragraph, holding whatever the user has typed as
        # their answer to that paragraph so far. The docked box edits one at a
        # time; `_sel_index` says which. Widget refs are rebuilt on each render.
        self._answers = ["" for _ in self._orig_paragraphs]
        # Paragraphs deliberately SET ASIDE (Issu 2026-08-08): a greeting, a
        # signature, a paragraph you have no intention of answering. They are
        # struck through in the window and left out of the reply entirely, so a
        # long mail shrinks to the parts that actually need an answer.
        self._skipped = set()
        # Set-aside paragraphs ticked ☑ to be folded into one block by
        # _merge_picked() — gathers a greeting, an aside and a sign-off
        # scattered anywhere in the message into a single, correct section,
        # by hand (Issu 2026-08-10: "välja set aside-delar och merge'a ...
        # skapa mina egna, korrekta, sektioner").
        self._merge_picks = set()
        self._sel_index = 0
        self._para_frames = {}
        self._para_marks  = {}

        # ── Pick up where you left off ───────────────────────────────────────
        # Everything typed against THIS message in an earlier sitting comes
        # back: the answers, the paragraph cuts you made by hand, and which
        # paragraphs you set aside (see _reply_progress_get). Keyed on the
        # Message-ID, so it survives the mail being moved by a filter.
        self._progress_key = _reply_key(reply_to or {})
        self._resumed = 0
        saved = _reply_progress_get(self._progress_key)
        if saved.get("paragraphs") and saved.get("answers"):
            try:
                paras = [str(p) for p in saved["paragraphs"]]
                answs = [str(a) for a in saved["answers"]]
                if len(paras) == len(answs) and paras:
                    self._orig_paragraphs = paras
                    self._answers = answs
                    self._skipped = {int(i) for i in saved.get("skipped", [])
                                     if 0 <= int(i) < len(paras)}
                    self._resumed = sum(1 for a in answs if a.strip())
                    log.info("Smart Reply resumed: %d/%d paragraphs already "
                             "answered", self._resumed, len(paras))
            except Exception as e:
                log.warning("Could not restore reply progress: %s", e)

        top = tk.Toplevel(parent_root)
        top.title(f"Smart Reply — F(re)email")
        top.configure(bg=C_BG3)
        top.minsize(620, 560)
        # A little taller than it used to be: the Cc/Bcc rows and the privacy
        # switch take three rows that were not there before, and the paragraph
        # area must still show a paragraph plus its answer box without scrolling.
        # Its own remembered spot, independent from the normal Compose window
        # (Issu 2026-08-11: "antagligen samma med smart reply").
        self._geo_key = "smart_reply"
        self._geo_w, self._geo_h = 720, 720
        # Its own zoom / splitter / favourite, separate from Reply's — the two
        # windows are read at different sizes (Issu 2026-09-20).
        self._layout_key = "smart_reply"
        self._layout_zoom_init()
        self._apply_remembered_geometry(top, parent_root, self._geo_w, self._geo_h)
        top.bind("<Configure>", self._on_geo_configure)
        # NOT modal (Issu 2026-08-08) — see the identical note in ComposeWindow.
        # A Smart Reply is written WHILE looking things up: another folder,
        # another mail in the same thread, the order you are answering about.
        # grab_set() made all of that dead — clicks landed nowhere. The main
        # window now stays completely usable behind this one, and Escape steps
        # back to it instead of throwing the reply away.
        top.focus_force()
        top.bind("<Escape>", lambda e: self._to_background())
        top.protocol("WM_DELETE_WINDOW", lambda: self._discard(top))
        self.top = top

        self._build_ui(top)

    # ── Layout ────────────────────────────────────────────────────────────────
    def _build_ui(self, top):
        # Toolbar
        tb = tk.Frame(top, bg=C_BG1, pady=4)
        tb.pack(fill="x")
        tk.Button(tb, text="✉ Send", bg=C_BTN_NEW, fg=C_BTN_FG,
                  font=("Segoe UI", 9, "bold"), relief="flat",
                  padx=12, pady=3,
                  command=lambda: self._do_send(top)).pack(side="left", padx=6)
        tk.Button(tb, text="🕒 Send later", bg=C_BTN_LATER, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat",
                  padx=8, pady=3,
                  command=lambda: self._send_later(top)).pack(side="left", padx=2)
        tk.Button(tb, text="🗑 Discard", bg=C_BTN_DEL, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat",
                  padx=8, pady=3,
                  command=lambda: self._discard(top)).pack(side="left", padx=2)
        self._build_position_menu(tb)

        # ── What the reply LOOKS like when it arrives (Issu 2026-08-03) ──────
        # Every Smart Reply now sends TWO parts: your answers alone, and the
        # full original text with your answers interleaved. This switch only
        # decides which comes FIRST; the other follows after a separator, with
        # a "begins on line N" hint (and clickable anchors in the HTML copy).
        self._answers_top = tk.BooleanVar(
            value=bool(self.cfg.get("smart_reply_answers_top", True)))
        cb = tk.Checkbutton(tb, text="My answers at the top",
                            variable=self._answers_top,
                            bg=C_BG1, fg=C_FG_DIM, selectcolor=C_BG2,
                            activebackground=C_BG1, activeforeground=C_FG,
                            font=("Segoe UI", 8),
                            highlightthickness=0, relief="flat", padx=4,
                            command=self._remember_sr_prefs)
        cb.pack(side="right", padx=(4, 10))
        add_tooltip(cb, "On: the recipient sees just your answers first, then a "
                        "separator, then the full message with the original "
                        "text and your answers in place. Off: the full version "
                        "comes first.")

        # How the sender's OLD text is shown in the full/interleaved part of the
        # HTML copy (plain text always uses the universal “> ” marker).
        tk.Label(tb, text="Their text:", bg=C_BG1, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(side="right")
        self._quote_style = tk.StringVar(
            value=self.cfg.get("smart_reply_quote_style", "grey"))
        style_labels = [_SR_QUOTE_LABELS[s] for s in _SR_QUOTE_STYLES]
        self._style_by_label = {_SR_QUOTE_LABELS[s]: s for s in _SR_QUOTE_STYLES}
        self._style_label = tk.StringVar(
            value=_SR_QUOTE_LABELS.get(self._quote_style.get(), "Grey text"))
        om_style = tk.OptionMenu(tb, self._style_label, *style_labels,
                                 command=lambda _l: self._remember_sr_prefs())
        om_style.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                           activeforeground=C_FG, highlightthickness=0,
                           relief="flat", font=("Segoe UI", 8))
        om_style["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                                   activeforeground=C_FG, font=("Segoe UI", 8))
        om_style.pack(side="right", padx=4)

        # ── Indent THEIR lines (Issu 2026-08-08) ─────────────────────────────
        # "Ge möjlighet att man kan TABba avsändarens alla rader, default 0
        # (steg)… möjlighet att välja 5 eller 10. Då blir det väldigt tydligt
        # vem som svarar."
        #
        # Every line of the sender's text is pushed right by this many spaces,
        # in BOTH the plain-text and the HTML copy, so their words and your
        # words sit in two visibly different columns. 0 = off, exactly as
        # before. It stacks with the quote style above rather than replacing it.
        self._quote_indent = tk.StringVar(
            value=str(self.cfg.get("smart_reply_quote_indent", 0)))
        om_ind = tk.OptionMenu(tb, self._quote_indent, "0", "5", "10",
                               command=lambda _v: self._remember_sr_prefs())
        om_ind.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                         activeforeground=C_FG, highlightthickness=0,
                         relief="flat", font=("Segoe UI", 8), width=2)
        om_ind["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                                 activeforeground=C_FG, font=("Segoe UI", 8))
        om_ind.pack(side="right", padx=(4, 0))
        _ind_lbl = tk.Label(tb, text="Indent theirs:", bg=C_BG1, fg=C_FG_DIM,
                            font=("Segoe UI", 8))
        _ind_lbl.pack(side="right", padx=(8, 0))
        add_tooltip(_ind_lbl,
                    "Push every line the sender wrote to the right by this "
                    "many spaces, so their text and your answers stand in two "
                    "clearly separate columns. 0 = no indent (the old "
                    "behaviour); 5 or 10 makes it obvious at a glance who is "
                    "saying what.")

        # Header fields (From / To / Subject) — same as the normal
        # Compose window, kept minimal here.
        hdr = tk.Frame(top, bg=C_BG3, padx=10, pady=6)
        hdr.pack(fill="x")

        def _lbl(parent, text):
            # Child of its ROW frame, not `hdr` — see the same fix in
            # ComposeWindow (Issu 2026-08-01: captions were staircasing a row
            # below their fields).
            return tk.Label(parent, text=text, bg=C_BG3, fg=C_FG_DIM,
                            font=("Segoe UI", 9), width=8, anchor="e")

        row_from = tk.Frame(hdr, bg=C_BG3)
        row_from.pack(fill="x", pady=2)
        _lbl(row_from, "From:").pack(side="left")
        sender_options = []
        for a in self._accounts:
            label = f"{a['name']} <{a['email']}>" if a.get("name") else a["email"]
            sender_options.append(label)

        def _email_to_option(email):
            for opt in sender_options:
                if email in opt:
                    return opt
            return sender_options[0] if sender_options else ""

        init_from = _email_to_option(
            self.reply_to.get("account_email", self._default_from))
        self._from_var = tk.StringVar(value=init_from)
        if sender_options:
            om = tk.OptionMenu(row_from, self._from_var, *sender_options)
            om.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                         activeforeground=C_FG, highlightthickness=0,
                         relief="flat", font=("Segoe UI", 9), anchor="w",
                         padx=6, pady=2)
            om["menu"].configure(bg=C_BG2, fg=C_FG,
                                 activebackground=C_BG4, activeforeground=C_FG,
                                 font=("Segoe UI", 9))
            om.pack(side="left", fill="x", expand=True)

        # ── To: / Cc: / Bcc: — the same three rows, the same 📖 picker and the
        # same privacy switch as the normal Compose window (DEL 05b). Smart
        # Reply used to have To: alone, so a reply that needed a second
        # recipient meant closing it and starting again.
        row_to = tk.Frame(hdr, bg=C_BG3)
        row_to.pack(fill="x", pady=2)
        _cap_to = _lbl(row_to, "To:")
        _cap_to.pack(side="left", anchor="n", pady=(3, 0))
        self.e_to = _ChipEntry(row_to, "To", collapse_over=self._recipients_max(),
                             bg=C_BG2, fg=C_FG, relief="flat",
                             insertbackground=C_ACCENT, font=("Segoe UI", 10),
                             insertofftime=0, insertontime=9999999)
        no_blink(self.e_to)
        self._fold_button(row_to, self.e_to, _cap_to, "To")
        self._pick_btn(row_to, lambda: self.e_to, "To")
        self.e_to.pack(side="left", fill="x", expand=True, ipady=3)
        # Reply to the SENDER, unless that is one of your own accounts, in which
        # case reply to the original recipients — never back to yourself
        # (Issu 2026-08-03).
        _reply_to_addr = _reply_to_address(
            self.reply_to, [a.get("email") for a in self._accounts])
        self.e_to.insert(0, _reply_to_addr)

        row_cc = tk.Frame(hdr, bg=C_BG3)
        row_cc.pack(fill="x", pady=2)
        _cap_cc = _lbl(row_cc, "Cc:")
        _cap_cc.pack(side="left", anchor="n", pady=(3, 0))
        self.e_cc = _ChipEntry(row_cc, "Cc", collapse_over=self._recipients_max(),
                             bg=C_BG2, fg=C_FG, relief="flat",
                             insertbackground=C_ACCENT, font=("Segoe UI", 10),
                             insertofftime=0, insertontime=9999999)
        no_blink(self.e_cc)
        self._fold_button(row_cc, self.e_cc, _cap_cc, "Cc")
        self._pick_btn(row_cc, lambda: self.e_cc, "Cc")
        self.e_cc.pack(side="left", fill="x", expand=True, ipady=3)
        if self._reply_all and self.reply_to:
            # Everyone else who was on the original message, minus you and
            # minus whoever is already in To: above (Reply All, Issu
            # 2026-08-04, extended to Smart Reply 2026-08-05).
            _cc_addr = _reply_all_cc(
                self.reply_to, [a.get("email") for a in self._accounts],
                _reply_to_addr)
            if _cc_addr:
                self.e_cc.insert(0, _cc_addr)

        row_bcc = tk.Frame(hdr, bg=C_BG3)
        row_bcc.pack(fill="x", pady=2)
        _cap_bcc = _lbl(row_bcc, "Bcc:")
        _cap_bcc.pack(side="left", anchor="n", pady=(3, 0))
        self.e_bcc = _ChipEntry(row_bcc, "Bcc",
                              collapse_over=self._recipients_max(),
                              bg=C_BG2, fg=C_FG, relief="flat",
                              insertbackground=C_ACCENT, font=("Segoe UI", 10),
                              insertofftime=0, insertontime=9999999)
        no_blink(self.e_bcc)
        self._fold_button(row_bcc, self.e_bcc, _cap_bcc, "Bcc")
        self._pick_btn(row_bcc, lambda: self.e_bcc, "Bcc")
        self.e_bcc.pack(side="left", fill="x", expand=True, ipady=3)

        # Same one-line explanation as Compose (Issu 2026-08-29) — Smart Reply
        # has the identical three fields, so it needs the identical hint.
        tk.Label(hdr,
                 text="Writing to several people?  Type an address and press "
                      "Enter (or a comma) — it turns into a chip and the field "
                      "is ready for the next one.   📖 picks from your "
                      "contacts.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 anchor="w", justify="left", wraplength=680
                 ).pack(fill="x", pady=(1, 3))

        _sibs = {"To": self.e_to, "Cc": self.e_cc, "Bcc": self.e_bcc}
        for _f in _sibs.values():
            _f.sibling_fields = _sibs

        # Address-book autocomplete popup on all three fields (Issu
        # 2026-08-10) — same shared behaviour as the Compose window.
        self._wire_autocomplete(self.e_to,  next_focus=lambda: self.e_subj.focus_set())
        self._wire_autocomplete(self.e_cc,  next_focus=lambda: self.e_bcc.focus_set())
        self._wire_autocomplete(self.e_bcc, next_focus=lambda: self.e_subj.focus_set())

        row_priv = tk.Frame(hdr, bg=C_BG3)
        row_priv.pack(fill="x", pady=(0, 2))
        _lbl(row_priv, "").pack(side="left")   # blank caption → aligns the box under the fields
        self._hide_recips = tk.BooleanVar(value=False)
        priv_cb = tk.Checkbutton(
            row_priv,
            text="🔒  Send to me only — put every other recipient in Bcc "
                 "(they can't see each other)",
            variable=self._hide_recips,
            bg=C_BG3, fg=C_FG_DIM, selectcolor=C_BG1,
            activebackground=C_BG3, activeforeground=C_FG,
            font=("Segoe UI", 8), highlightthickness=0, relief="flat",
            anchor="w")
        priv_cb.pack(side="left", fill="x", expand=True)
        add_tooltip(priv_cb,
                    "For answering a group without exposing addresses: "
                    "everyone you listed (To, Cc and Bcc) is moved into Bcc, "
                    "and the message is sent to your own address. Each person "
                    "sees only themselves and you.")

        row_s = tk.Frame(hdr, bg=C_BG3)
        row_s.pack(fill="x", pady=2)
        _lbl(row_s, "Subject:").pack(side="left")
        self.e_subj = tk.Entry(row_s, bg=C_BG2, fg=C_FG, relief="flat",
                               insertbackground=C_ACCENT, font=("Segoe UI", 10, "bold"),
                               insertofftime=0, insertontime=9999999)
        no_blink(self.e_subj)
        self._guard_text_entry(self.e_subj, "Subject")
        self.e_subj.pack(side="left", fill="x", expand=True, ipady=3)
        subj = self.reply_to.get("subject", "")
        self.e_subj.insert(0, "Re: " + subj if not subj.startswith("Re:") else subj)

        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x")

        hint = tk.Label(top,
            text="Click a paragraph above to answer it — your writing box is "
                 "docked at the bottom and never scrolls away. Ctrl+↑ / Ctrl+↓ "
                 "move to the previous / next paragraph. ● answered · ○ still "
                 "open · ⊘ set aside (left out of the reply). Tick ☑ on "
                 "set-aside paragraphs and use 🔗 Merge picked to fold "
                 "several into one section.",
            bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
            anchor="w", padx=10, pady=4, wraplength=680, justify="left")
        hint.pack(fill="x")

        # ── Progress row (Issu 2026-08-08) ───────────────────────────────────
        # "How far did I get last time?" answered at a glance, plus the two
        # bulk moves that make finishing a long mail in several sittings
        # practical: hide everything already answered, or bring it all back.
        prog = tk.Frame(top, bg=C_BG1)
        prog.pack(fill="x")
        self._progress_lbl = tk.Label(prog, text="", bg=C_BG1, fg=C_ACCENT,
                                      font=("Segoe UI", 8, "bold"),
                                      anchor="w", padx=10, pady=3)
        self._progress_lbl.pack(side="left")
        b_clear = tk.Button(prog, text="↩ Bring all back", bg=C_BTN_STD,
                            fg=C_BTN_FG, font=("Segoe UI", 8), relief="flat",
                            cursor="hand2", padx=8, pady=1,
                            command=self._clear_skips)
        b_clear.pack(side="right", padx=(2, 10))
        add_tooltip(b_clear, "Un-set-aside every paragraph, so the whole "
                             "message is in play again.")
        b_hide = tk.Button(prog, text="⊘ Set aside the answered ones",
                           bg=C_BTN_STD, fg=C_BTN_FG, font=("Segoe UI", 8),
                           relief="flat", cursor="hand2", padx=8, pady=1,
                           command=self._skip_all_answered)
        b_hide.pack(side="right", padx=2)
        add_tooltip(b_hide,
                    "Clear everything you have already answered out of the "
                    "way, leaving only the paragraphs that still need writing. "
                    "Your answers are kept and still go out — this only tidies "
                    "the list in front of you.")

        # ── Build your own sections out of set-aside pieces (Issu 2026-08-10)
        # Tick ☑ on two or more ⊘ set-aside paragraphs — wherever they sit in
        # the message — and fold them into one block. A more deliberate,
        # by-hand alternative to ⬆ Merge up when the bits you want together
        # are not next to each other.
        b_merge_picked = tk.Button(prog, text="🔗 Merge picked",
                                   bg=C_BTN_STD, fg=C_BTN_FG,
                                   font=("Segoe UI", 8), relief="flat",
                                   cursor="hand2", padx=8, pady=1,
                                   command=self._merge_picked)
        b_merge_picked.pack(side="right", padx=2)
        add_tooltip(b_merge_picked,
                    "Tick ☑ on two or more set-aside paragraphs — they can be "
                    "anywhere in the message — then click here to fold them "
                    "into a single block. Handy for gathering a scattered "
                    "greeting, remark and sign-off into one section instead "
                    "of several small ones.")

        # Coming back to a half-finished reply says so, out loud, once.
        if self._resumed:
            tk.Label(top,
                     text=f"↺  Picked up where you left off — {self._resumed} "
                          f"answer(s) from an earlier sitting are already here.",
                     bg="#1e3a1e", fg="#a8e6a8", font=("Segoe UI", 8, "bold"),
                     anchor="w", padx=10, pady=3).pack(fill="x")

        # ── The window splits: sender's paragraphs on top (scrollable), your
        #    writing box DOCKED at the bottom (Issu 2026-08-03: "min skrivbox
        #    ska vara fristående, jag ska inte behöva scrolla dit"). A paned
        #    window so you can size the two against each other.
        # ── Zoom / Default / Favourite (Issu 2026-09-20) ─────────────────────
        # Its own slim row, directly above the paragraphs it acts on. The
        # toolbar at the top already carries Send, Send later, Discard,
        # Position and four preference widgets — three more buttons up there
        # would push Send off the edge at the default width.
        lrow = tk.Frame(top, bg=C_BG1)
        lrow.pack(fill="x")
        # Smart Reply splits top/bottom, not left/right, so there is no side
        # to put each group "over" — both zooms and the three layout buttons
        # stay on this one row, in reading order.
        self._build_zoom_group(lrow, "orig", "Their text",
                               "the sender's paragraphs").pack(side="left",
                                                               pady=2)
        self._build_zoom_group(lrow, "answer", "Answer",
                               "the box you type in").pack(side="left", pady=2)
        tk.Frame(lrow, bg=C_SEP, width=1).pack(side="left", fill="y",
                                               padx=(8, 0), pady=3)
        self._build_layout_buttons(lrow).pack(side="left", pady=2)

        split = tk.PanedWindow(top, orient="vertical", bg=C_SEP, sashwidth=5,
                               sashrelief="flat", handlesize=0)
        split.pack(fill="both", expand=True)
        self._sr_split = split

        body_frame = tk.Frame(split, bg=C_BG2)
        split.add(body_frame, minsize=120, stretch="always")

        self.sr_canvas = tk.Canvas(body_frame, bg=C_BG2, highlightthickness=0)
        sr_sb = tk.Scrollbar(body_frame, orient="vertical",
                             command=self.sr_canvas.yview,
                             bg=C_BG3, troughcolor=C_BG1)
        sr_sb.pack(side="right", fill="y")
        self.sr_canvas.configure(yscrollcommand=sr_sb.set)
        self.sr_canvas.pack(fill="both", expand=True)

        self.sr_inner = tk.Frame(self.sr_canvas, bg=C_BG2)
        self.sr_cwin  = self.sr_canvas.create_window((0, 0), window=self.sr_inner, anchor="nw")
        self.sr_inner.bind("<Configure>",
                           lambda e: self.sr_canvas.configure(
                               scrollregion=self.sr_canvas.bbox("all")))
        self.sr_canvas.bind("<Configure>",
                            lambda e: self.sr_canvas.itemconfig(self.sr_cwin, width=e.width))
        _bind_mousewheel(self.sr_inner, self.sr_canvas)

        # ── Docked writing box ───────────────────────────────────────────────
        dock = tk.Frame(split, bg=C_BG1)
        split.add(dock, minsize=110)
        head = tk.Frame(dock, bg=C_BG1)
        head.pack(fill="x", padx=8, pady=(6, 0))
        self._dock_lbl = tk.Label(head, text="", bg=C_BG1, fg=C_ACCENT,
                                  font=("Segoe UI", 9, "bold"), anchor="w")
        self._dock_lbl.pack(side="left")
        tk.Button(head, text="Next ▶", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 8), relief="flat", cursor="hand2",
                  padx=8, pady=1,
                  command=lambda: self._select_paragraph(self._sel_index + 1)
                  ).pack(side="right", padx=2)
        tk.Button(head, text="◀ Prev", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 8), relief="flat", cursor="hand2",
                  padx=8, pady=1,
                  command=lambda: self._select_paragraph(self._sel_index - 1)
                  ).pack(side="right", padx=2)
        # ── Choose your own paragraphs (Issu 2026-08-03) ─────────────────────
        # "✂ Split into lines" breaks the selected paragraph into one unit per
        # line; "⬆ Merge up" joins it with the one above. Between them you can
        # shape any paragraphing you like — the point of a point-by-point reply.
        b_split = tk.Button(head, text="✂ Split into lines", bg=C_BTN_STD,
                            fg=C_BTN_FG, font=("Segoe UI", 8), relief="flat",
                            cursor="hand2", padx=8, pady=1,
                            command=lambda: self._split_here(self._sel_index))
        b_split.pack(side="right", padx=(12, 2))
        add_tooltip(b_split, "Break this block into one answerable paragraph "
                             "per line, so you can reply to each on its own.")
        b_merge = tk.Button(head, text="⬆ Merge up", bg=C_BTN_STD,
                            fg=C_BTN_FG, font=("Segoe UI", 8), relief="flat",
                            cursor="hand2", padx=8, pady=1,
                            command=lambda: self._merge_up(self._sel_index))
        b_merge.pack(side="right", padx=2)
        add_tooltip(b_merge, "Join this paragraph with the one above it into a "
                             "single block (your answers are kept, joined too).")
        self._dock_txt = tk.Text(dock, height=5, bg=C_BG2, fg=C_FG,
                                 insertbackground=C_ACCENT, relief="flat",
                                 font=("Segoe UI",
                                       getattr(self, "_zoom_pt_answer", 10)),
                                 wrap="word", padx=8, pady=6,
                                 insertofftime=0, insertontime=9999999)
        no_blink(self._dock_txt)
        self._dock_txt.pack(fill="both", expand=True, padx=8, pady=(2, 8))
        self._dock_txt.bind("<KeyRelease>", lambda e: self._save_dock())
        self._dock_txt.bind("<Control-Down>",
                            lambda e: (self._select_paragraph(self._sel_index + 1),
                                       "break")[1])
        self._dock_txt.bind("<Control-Up>",
                            lambda e: (self._select_paragraph(self._sel_index - 1),
                                       "break")[1])

        # Resuming lands you on the first paragraph that still has NO answer,
        # not back at the top — that is where the work is (Issu 2026-08-08).
        start = 0
        if self._resumed:
            start = next((i for i, a in enumerate(self._answers)
                          if not a.strip() and i not in self._skipped), 0)
        self._sel_index = start
        self._render_paragraphs()
        self._select_paragraph(start)
        self._update_progress_line()

        # Ctrl-wheel over the paragraphs sizes them; over the writing box it
        # sizes that. The keyboard shortcuts size your own text, Shift theirs.
        self._bind_zoom_keys(top,
                             orig_widgets=(self.sr_canvas, self.sr_inner),
                             answer_widgets=(self._dock_txt,))
        self._zoom_labels_refresh()
        # Same delay, same reason as the Reply window: a sash is placed in
        # pixels and the window has no real height until Tk has laid it out.
        top.after(120, self._layout_sash_restore)

    # ── The three layout hooks the shared machinery calls (Issu 2026-09-20) ──
    def _layout_set_zoom(self, pt):
        """Re-draw the paragraphs at the new size.

        _save_dock() first: the block that is currently being answered shows an
        inline preview of your answer, and it is rebuilt from self._answers —
        which is only up to date once whatever is in the docked box has been
        put back into it. Without this, zooming mid-sentence would redraw the
        preview from the text as it stood at the last keystroke."""
        try:
            self._save_dock()
        except Exception:
            pass
        self._render_paragraphs()

    def _layout_set_zoom_answer(self, pt):
        w = getattr(self, "_dock_txt", None)
        if w is not None:
            w.configure(font=("Segoe UI", int(pt)))

    def _layout_get_sash(self):
        sp = getattr(self, "_sr_split", None)
        if sp is None:
            return 0
        return int(sp.sash_coord(0)[1])

    def _layout_set_sash(self, value):
        sp = getattr(self, "_sr_split", None)
        if sp is None:
            return
        # Keep both halves usable: at least a paragraph visible on top, at
        # least the writing box at the bottom.
        total = max(1, sp.winfo_height())
        sp.sash_place(0, 1, max(120, min(int(value), total - 140)))

    def _remember_sr_prefs(self):
        """Persist the Smart-Reply preferences (order, quote style, indent)."""
        self._quote_style.set(self._style_by_label.get(
            self._style_label.get(), "grey"))
        self.cfg["smart_reply_answers_top"] = bool(self._answers_top.get())
        self.cfg["smart_reply_quote_style"] = self._quote_style.get()
        try:
            self.cfg["smart_reply_quote_indent"] = int(self._quote_indent.get())
        except Exception:
            self.cfg["smart_reply_quote_indent"] = 0
        try:
            _save_settings(self.cfg)
        except Exception:
            pass

    def _indent_steps(self) -> int:
        """How far the sender's lines are pushed right, as a plain integer."""
        try:
            return max(0, min(40, int(self._quote_indent.get())))
        except Exception:
            return 0

    # ── Saved progress (Issu 2026-08-08) ─────────────────────────────────────
    def _sr_progress_save(self):
        """Write the half-finished reply to disk, so it comes back next time.

        Deliberately does NOT call _save_dock — that would re-arm the autosave
        timer and turn this into a disk write every two seconds forever. It
        picks the current box up directly instead."""
        self._progress_after = None
        try:
            i = getattr(self, "_sel_index", 0)
            if 0 <= i < len(self._answers):
                self._answers[i] = self._dock_txt.get("1.0", "end-1c")
        except Exception:
            pass
        _reply_progress_put(self._progress_key, self._orig_paragraphs,
                            self._answers, self._skipped,
                            subject=(self.reply_to or {}).get("subject", ""))

    def _sr_progress_clear(self):
        """The reply went out (or was thrown away) — forget it."""
        _reply_progress_drop(self._progress_key)

    # ── Paragraph rendering ──────────────────────────────────────────────────
    def _render_paragraphs(self):
        """Draw every sender paragraph as a read-only block you can click to
        select. All are shown at once (no collapsing): you answer the selected
        one in the docked box at the bottom, which never scrolls away."""
        for w in self.sr_inner.winfo_children():
            w.destroy()
        self._para_frames = {}
        self._para_marks  = {}
        for idx, para_text in enumerate(self._orig_paragraphs):
            self._render_one_paragraph(idx, para_text)

    def _render_one_paragraph(self, idx, para_text):
        selected = (idx == getattr(self, "_sel_index", 0))
        skipped  = idx in self._skipped
        answered = bool(self._answers[idx].strip())
        bg = C_BG4 if selected else C_BG3
        outer = tk.Frame(self.sr_inner, bg=C_BG2, cursor="hand2")
        outer.pack(fill="x", padx=10, pady=(8 if idx == 0 else 4, 0))
        block = tk.Frame(outer, bg=bg, padx=10, pady=8,
                         highlightbackground=(C_ACCENT if selected else bg),
                         highlightthickness=1)
        block.pack(fill="x")

        head = tk.Frame(block, bg=bg)
        head.pack(fill="x")
        # ● answered · ○ still open · ⊘ set aside on purpose
        mark_txt = "⊘" if skipped else ("●" if answered else "○")
        mark_fg  = (C_FG_DIM if skipped
                    else (C_ACCENT if answered else C_FG_DIM))
        mark = tk.Label(head, text=mark_txt, bg=bg, fg=mark_fg,
                        font=("Segoe UI", 9))
        mark.pack(side="left", padx=(0, 6))
        self._para_marks[idx] = mark
        cap = f"Them — paragraph {idx + 1} of {len(self._orig_paragraphs)}"
        if skipped:
            cap += "   ·  set aside (left out of the reply)"
        elif answered:
            cap += "   ·  answered"
        if selected:
            cap += "   ·  answering this"
        tk.Label(head, text=cap,
                 bg=bg, fg=(C_ACCENT if selected else C_FG_DIM),
                 font=("Segoe UI", 8, "bold"), anchor="w").pack(side="left")

        # ── Set aside / bring back (Issu 2026-08-08) ─────────────────────────
        # A greeting, a footer, a paragraph you simply do not intend to answer:
        # one click and it is struck through here and dropped from the outgoing
        # reply completely. Click again to bring it back. Nothing is deleted —
        # this only decides what gets sent.
        skip_btn = tk.Label(head, text=("↩ bring back" if skipped
                                        else "⊘ set aside"),
                            bg=bg, fg=C_FG_DIM, cursor="hand2",
                            font=("Segoe UI", 8, "underline"))
        skip_btn.pack(side="right")
        skip_btn.bind("<Button-1>",
                      lambda e, i=idx: (self._toggle_skip(i), "break")[1])
        add_tooltip(skip_btn,
                    "Leave this paragraph out of the reply entirely — it is "
                    "not sent in either part. Use it for greetings, footers "
                    "and anything you have already dealt with. Click again to "
                    "put it back.")

        # Pick this set-aside paragraph for the bulk "🔗 Merge picked" tool
        # (Issu 2026-08-10) — only shown once it is already ⊘ set aside, since
        # picking only ever means "merge with the other picked ones".
        if skipped:
            picked = idx in self._merge_picks
            pick_btn = tk.Label(head, text=("☑" if picked else "☐"),
                                bg=bg, fg=(C_ACCENT if picked else C_FG_DIM),
                                cursor="hand2", font=("Segoe UI", 9))
            pick_btn.pack(side="right", padx=(0, 8))
            pick_btn.bind("<Button-1>",
                          lambda e, i=idx: (self._toggle_merge_pick(i), "break")[1])
            add_tooltip(pick_btn,
                        "Pick this set-aside paragraph to merge with other "
                        "picked ones into a single block — use 🔗 Merge "
                        "picked below once you have ticked two or more.")

        # Struck-through and dimmed when set aside, so the eye skips it too.
        # The point size is the zoom (Issu 2026-09-20) — this IS "originaldelen"
        # in a Smart Reply: their words, block by block.
        _z = getattr(self, "_zoom_pt", 10)
        body_font = (("Segoe UI", _z, "overstrike") if skipped
                     else ("Segoe UI", _z))
        body = tk.Label(block, text=para_text, bg=bg,
                        fg=(C_FG_DIM if skipped else C_FG),
                        font=body_font, anchor="w", justify="left",
                        wraplength=640)
        body.pack(fill="x", pady=(2, 0))

        # An inline preview of your answer, so you can see it on the paragraph
        # itself without opening the dock (it lives in the dock while editing).
        ans = self._answers[idx].strip()
        if ans and not skipped:
            prev = ans.replace("\n", " ")
            if len(prev) > 90:
                prev = prev[:90].rstrip() + "…"
            tk.Label(block, text="↳ " + prev, bg=bg, fg=C_ACCENT,
                     font=("Segoe UI", max(7, _z - 1)), anchor="w",
                     justify="left",
                     wraplength=620).pack(fill="x", pady=(4, 0))

        self._para_frames[idx] = outer
        for w in (outer, block, body, head):
            w.bind("<Button-1>", lambda e, i=idx: self._select_paragraph(i))

    def _toggle_skip(self, idx):
        """Set a paragraph aside, or bring it back."""
        self._save_dock()
        if idx in self._skipped:
            self._skipped.discard(idx)
            self._merge_picks.discard(idx)   # no longer set aside → no longer pickable
        else:
            self._skipped.add(idx)
        self._render_paragraphs()
        self._update_progress_line()

    def _toggle_merge_pick(self, idx):
        """Tick/untick a set-aside paragraph as one to fold into a single
        block with _merge_picked() — the manual way to build your own
        section out of pieces scattered anywhere in the message."""
        if idx not in self._skipped:
            return
        if idx in self._merge_picks:
            self._merge_picks.discard(idx)
        else:
            self._merge_picks.add(idx)
        self._render_paragraphs()

    def _skip_all_answered(self):
        """Set aside every paragraph you have ALREADY answered.

        This is the automatic half of Issu's request: come back to a mail you
        half-answered yesterday and one click clears everything that is done
        out of the way, leaving only what still needs writing. Your answers are
        untouched — they are still sent."""
        self._save_dock()
        done = {i for i, a in enumerate(self._answers) if a.strip()}
        if not done:
            self._flash_ok("Nothing answered yet")
            return
        self._skipped |= done
        self._render_paragraphs()
        self._update_progress_line()
        self._flash_ok(f"{len(done)} answered paragraph(s) set aside")

    def _clear_skips(self):
        """Bring every set-aside paragraph back."""
        if not self._skipped:
            return
        n = len(self._skipped)
        self._skipped = set()
        self._merge_picks = set()
        self._render_paragraphs()
        self._update_progress_line()
        self._flash_ok(f"{n} paragraph(s) brought back")

    def _update_progress_line(self):
        """Keep the "3 of 11 answered" line above the paragraphs honest."""
        lbl = getattr(self, "_progress_lbl", None)
        if lbl is None:
            return
        total    = len(self._orig_paragraphs)
        answered = sum(1 for a in self._answers if a.strip())
        aside    = len(self._skipped)
        txt = f"{answered} of {total} paragraphs answered"
        if aside:
            txt += f"   ·   {aside} set aside"
        left = total - answered - len([i for i in self._skipped
                                       if not self._answers[i].strip()])
        if left > 0:
            txt += f"   ·   {left} still open"
        try:
            lbl.configure(text=txt)
        except Exception:
            pass

    def _save_dock(self):
        """Store what is in the docked box against the selected paragraph, and
        keep its ●/○ marker and inline preview honest as you type."""
        i = getattr(self, "_sel_index", 0)
        if 0 <= i < len(self._answers):
            self._answers[i] = self._dock_txt.get("1.0", "end-1c")
            mk = self._para_marks.get(i)
            if mk is not None and i not in self._skipped:
                has = bool(self._answers[i].strip())
                mk.configure(text=("●" if has else "○"),
                             fg=(C_ACCENT if has else C_FG_DIM))
        self._update_progress_line()
        self._autosave_progress()

    def _autosave_progress(self):
        """Write the half-finished reply to disk a couple of seconds after you
        stop typing. Same idea as the compose window's draft autosave: a crash,
        a power cut or a closed laptop costs at most those two seconds, and
        nothing has to be remembered on purpose (Issu 2026-08-08)."""
        aid = getattr(self, "_progress_after", None)
        if aid is not None:
            try:
                self.top.after_cancel(aid)
            except Exception:
                pass
        try:
            self._progress_after = self.top.after(2000, self._sr_progress_save)
        except Exception:
            self._progress_after = None

    def _select_paragraph(self, idx):
        """Make paragraph `idx` the one the docked box answers. Saves whatever
        was being typed first, so switching never loses text."""
        self._save_dock()
        self._load_dock(idx)

    def _load_dock(self, idx):
        """Point the docked box at paragraph `idx` WITHOUT saving first — the
        caller has already saved (or rebuilt) the answers. Keeping load and save
        apart is what stopped a rebuild from writing a stale box over a freshly
        merged/split answer (Issu 2026-08-03)."""
        idx = max(0, min(idx, len(self._orig_paragraphs) - 1))
        self._sel_index = idx
        self._dock_txt.delete("1.0", "end")
        self._dock_txt.insert("1.0", self._answers[idx])
        self._dock_txt.focus_set()
        self._dock_txt.mark_set("insert", "end")
        prev = self._orig_paragraphs[idx].replace("\n", " ").strip()
        if len(prev) > 48:
            prev = prev[:48].rstrip() + "…"
        aside = "  (set aside — not sent)" if idx in self._skipped else ""
        self._dock_lbl.configure(
            text=f"✍  Your answer to paragraph {idx + 1}:  “{prev}”{aside}")
        self._render_paragraphs()
        self._scroll_paragraph_into_view(idx)
        self._update_progress_line()

    def _split_here(self, idx):
        """Break paragraph `idx` into one paragraph per line, so each line can
        be answered on its own. Your existing answer stays with the FIRST line;
        the new lines start empty."""
        self._save_dock()
        if not (0 <= idx < len(self._orig_paragraphs)):
            return
        lines = [ln.strip() for ln in self._orig_paragraphs[idx].split("\n")
                 if ln.strip()]
        if len(lines) <= 1:
            try:
                self._flash_ok("Nothing to split — it is a single line")
            except Exception:
                pass
            return
        ans = self._answers[idx]
        # Set-aside marks are stored by INDEX, so splitting one paragraph into
        # N shifts everything after it. Rebuild the set rather than leaving it
        # pointing at the wrong paragraphs (Issu 2026-08-08).
        grew = len(lines) - 1
        was_skipped = idx in self._skipped
        self._skipped = {(i + grew if i > idx else i)
                         for i in self._skipped if i != idx}
        # A pick on the block being split does not carry over — unclear which
        # of the new pieces should inherit it, so it is simplest to drop it;
        # re-tick whichever piece(s) you actually want merged.
        self._merge_picks = {(i + grew if i > idx else i)
                             for i in self._merge_picks if i != idx}
        self._orig_paragraphs[idx:idx + 1] = lines
        self._answers[idx:idx + 1] = [ans] + ["" for _ in lines[1:]]
        if was_skipped:
            # A set-aside block stays set aside in all its pieces.
            self._skipped |= set(range(idx, idx + len(lines)))
        self._load_dock(idx)

    def _merge_up(self, idx):
        """Join paragraph `idx` into the one above it (sender text and answers
        both kept, joined). The selection lands on the merged paragraph."""
        self._save_dock()
        if idx <= 0 or idx >= len(self._orig_paragraphs):
            try:
                self._flash_ok("Nothing above to merge into")
            except Exception:
                pass
            return
        self._orig_paragraphs[idx - 1] = (
            self._orig_paragraphs[idx - 1].rstrip()
            + "\n" + self._orig_paragraphs[idx].lstrip())
        a_prev, a_cur = self._answers[idx - 1].strip(), self._answers[idx].strip()
        self._answers[idx - 1] = (a_prev + ("\n\n" if a_prev and a_cur else "")
                                  + a_cur)
        del self._orig_paragraphs[idx]
        del self._answers[idx]
        # Same index bookkeeping as _split_here: everything after the removed
        # paragraph moves up one. The merged block counts as set aside only if
        # BOTH halves were.
        both_aside = (idx in self._skipped) and ((idx - 1) in self._skipped)
        self._skipped = {(i - 1 if i > idx else i)
                         for i in self._skipped if i != idx}
        if both_aside:
            self._skipped.add(idx - 1)
        else:
            self._skipped.discard(idx - 1)
        # Folding two blocks into one drops any pick either half had — same
        # reasoning as _split_here: a combined block is not what was ticked.
        self._merge_picks = {(i - 1 if i > idx else i)
                             for i in self._merge_picks
                             if i not in (idx, idx - 1)}
        self._load_dock(idx - 1)

    def _merge_picked(self):
        """Fold every ☑ picked, set-aside paragraph into ONE block, kept in
        their original order however far apart they started out — the
        point being to gather a scattered greeting, aside and sign-off into
        a single, correct set-aside section by hand (Issu 2026-08-10)."""
        self._save_dock()
        picks = sorted(i for i in self._merge_picks
                       if 0 <= i < len(self._orig_paragraphs)
                       and i in self._skipped)
        if len(picks) < 2:
            self._flash_ok("Tick ☑ on two or more set-aside paragraphs first")
            return
        keep = picks[0]
        self._orig_paragraphs[keep] = "\n\n".join(
            self._orig_paragraphs[i] for i in picks)
        # Same conservative rule _merge_up follows: text is never thrown
        # away, only decided what gets sent — any answers typed against a
        # picked paragraph before it was set aside are kept, joined.
        self._answers[keep] = "\n\n".join(
            a for a in (self._answers[i].strip() for i in picks) if a)
        drop = set(picks[1:])
        for i in sorted(drop, reverse=True):
            del self._orig_paragraphs[i]
            del self._answers[i]
        def _reindex(i):
            return i - sum(1 for d in drop if d < i)
        self._skipped = {_reindex(i) for i in self._skipped if i not in drop}
        self._skipped.add(keep)
        self._merge_picks = set()
        self._load_dock(_reindex(keep))
        self._flash_ok(f"{len(picks)} set-aside paragraphs merged into one")

    def _scroll_paragraph_into_view(self, idx):
        try:
            w = self._para_frames.get(idx)
            if not w:
                return
            self.sr_canvas.update_idletasks()
            total = max(1, self.sr_inner.winfo_height())
            canv_h = max(1, self.sr_canvas.winfo_height())
            top = w.winfo_y()
            bot = top + max(1, w.winfo_height())
            y0 = self.sr_canvas.canvasy(0)
            if top < y0:
                self.sr_canvas.yview_moveto(max(0.0, top / total))
            elif bot > y0 + canv_h:
                self.sr_canvas.yview_moveto(max(0.0, (bot - canv_h) / total))
        except Exception:
            pass

    # ── Actions ───────────────────────────────────────────────────────────────
    def _collect_bodies(self):
        """Return (plain, html) for the two-part reply — the docked box's
        current text is saved first so the latest keystroke is never lost.

        Paragraphs you set aside (⊘) are dropped here, so they appear in
        NEITHER part of the outgoing message — that is the whole point of
        setting one aside (Issu 2026-08-08)."""
        self._save_dock()
        pairs = [(p, a) for i, (p, a) in
                 enumerate(zip(self._orig_paragraphs, self._answers))
                 if i not in self._skipped]
        style = self._style_by_label.get(self._style_label.get(), "grey")
        sig = ""
        if self.app is not None:
            from_addr = (self._from_var.get() if hasattr(self, "_from_var")
                         else self._default_from)
            sig = _signature_for(self.app._signature_store,
                                 parseaddr(from_addr)[1] or from_addr) or ""
        return _smart_reply_bodies(pairs,
                                   answers_on_top=bool(self._answers_top.get()),
                                   style=style, signature=sig,
                                   indent=self._indent_steps())

    def _gather(self, top):
        """Validate + build the outgoing payload, or return None having already
        said what is missing.

        One path for both Send and Send later, so the address cleaning, the
        privacy switch and the signature can never apply to only one of them
        (they used to be two near-copies, and only Compose had any of it)."""
        # Address hygiene first — the same cleaner Compose uses (DEL 05b).
        if not self._sanitize_recipients(top):
            return None
        to        = self.e_to.get().strip()
        cc        = self.e_cc.get().strip() if hasattr(self, "e_cc") else ""
        bcc       = self.e_bcc.get().strip() if hasattr(self, "e_bcc") else ""
        subj      = self.e_subj.get().strip()
        from_addr = (self._from_var.get() if hasattr(self, "_from_var")
                     else self._default_from)
        bcc_list  = [x.strip() for x in _re.split(r"[;,]", bcc) if x.strip()]

        # "Send to me only" — everyone into Bcc, addressed to yourself.
        if getattr(self, "_hide_recips", None) and self._hide_recips.get():
            everyone = ([x.strip() for x in _re.split(r"[;,]", to)  if x.strip()]
                        + [x.strip() for x in _re.split(r"[;,]", cc) if x.strip()]
                        + list(bcc_list))
            if not everyone:
                messagebox.showwarning(
                    "Missing recipient",
                    "Fill in at least one recipient — they'll be moved to Bcc.",
                    parent=top)
                return None
            me = parseaddr(from_addr)[1] or from_addr
            to, cc, bcc_list = me, "", everyone
            log.info("Smart Reply privacy switch: %d recipients moved to Bcc",
                     len(everyone))

        if not to:
            messagebox.showwarning("Missing recipient",
                                   "Please fill in the To: field.", parent=top)
            return None
        # The signature is folded in by the builder, so it lands once at the
        # very end of both the plain and the HTML copy (DEL 06b).
        body, html = self._collect_bodies()
        # Only answers that are actually going out count — an answer on a
        # paragraph you set aside is not sent, so it cannot make the reply
        # non-empty either (Issu 2026-08-08).
        live = [a for i, a in enumerate(self._answers)
                if i not in self._skipped and a.strip()]
        if not live:
            messagebox.showwarning(
                "Empty reply",
                "Write at least one answer before sending."
                + ("\n\nEverything you have answered is currently set aside "
                   "(⊘) — press “↩ Bring all back” to include it."
                   if any(a.strip() for a in self._answers) else ""),
                parent=top)
            return None

        in_reply_to, references = (
            _reply_threading_headers(self.reply_to) if self.reply_to else ("", ""))
        return {"from": from_addr, "to": to, "cc": cc, "subject": subj,
                "body": body, "body_html": html,
                "attachments": [], "draft_id": "", "bcc": bcc_list,
                "in_reply_to": in_reply_to, "references": references}

    def _queue(self, top, payload, when):
        """Hand the payload to the one and only send path, remember the people
        it went to, and close."""
        if self.app is None:
            log.info("SEND smart-reply (no backend) → from=%s  to=%s",
                     payload["from"], payload["to"])
            self._persist_geo()
            top.destroy()
            self._flash_ok("Message sent!")
            return
        # Same outbox as everything else, so undo-send works here too.
        self.app.queue_send(payload, when=when, kind="normal")
        # Auto-save the contacts (a Smart Reply IS a reply, so it follows the
        # reply setting — on by default).
        try:
            self.app._remember_recipients(payload, is_reply=True)
        except Exception:
            pass
        # The reply has gone — the saved half-finished copy has done its job
        # and must not come back the next time this message is opened.
        self._sr_progress_clear()
        aid = getattr(self, "_progress_after", None)
        if aid is not None:
            try:
                self.top.after_cancel(aid)
            except Exception:
                pass
            self._progress_after = None
        self._persist_geo()
        top.destroy()

    def _do_send(self, top):
        payload = self._gather(top)
        if payload is None:
            return
        self._queue(top, payload, when=None)

    def _send_later(self, top):
        """Smart Reply's own 'send later' — collects the answers exactly like
        _do_send, then queues the result for a chosen time."""
        payload = self._gather(top)
        if payload is None:
            return
        when = _ask_send_time(top, self.root)
        if when is None:
            return
        self._pending_when = when
        self._queue(top, payload, when=when)

    def _to_background(self):
        """Escape: hand focus back to the mailbox, keep this reply open.

        Same reasoning as ComposeWindow._to_background — the window is no
        longer modal, so Escape must not mean "throw away my answers"."""
        try:
            self.root.focus_force()
            self.root.lift()
        except Exception:
            pass

    def _discard(self, top):
        """Closing a Smart Reply that has answers in it asks first — the same
        protection the normal compose window has always had. Your progress is
        also saved against this message either way, so reopening Smart Reply on
        it later brings the answers back (see _sr_progress_save)."""
        # Pick up the box as it stands right now, without re-arming the
        # autosave timer on a window that is about to close.
        try:
            i = getattr(self, "_sel_index", 0)
            if 0 <= i < len(self._answers):
                self._answers[i] = self._dock_txt.get("1.0", "end-1c")
        except Exception:
            pass
        aid = getattr(self, "_progress_after", None)
        if aid is not None:
            try:
                self.top.after_cancel(aid)
            except Exception:
                pass
            self._progress_after = None
        answered = sum(1 for a in self._answers if a.strip())
        if answered:
            ans = ask_yes_no_cancel(
                top, "Unfinished reply",
                f"You have answered {answered} of "
                f"{len(self._orig_paragraphs)} paragraphs.\n\n"
                "Keep it  —  the answers come back next time you open Smart "
                "Reply on this message\n"
                "Throw it away  —  the answers are gone\n"
                "Keep writing  —  back to the reply",
                yes="Keep it", no="Throw it away", cancel="Keep writing",
                icon="✍")
            if ans is None:
                return
            if ans:
                self._sr_progress_save()
            else:
                self._sr_progress_clear()
        self._persist_geo()
        top.destroy()

    def _flash_ok(self, msg):
        """The "Message sent!" confirmation.

        It used to open dead-centre over the window you were reading, on top of
        the message you had just gone back to. It is now the same kind of thing
        as the delete bar — a small toast in the bottom-right corner, in the
        SHARED stack, so a Send confirmation stands above a delete-undo bar or
        a follow-up reminder instead of hiding it (Issu 2026-08-03: "den där
        SEND-popup får bli som DELETE-popup … men inte på samma plats som
        Delete, så att de krockar"). Auto-closes after 1 second, house rule."""
        _sent_toast(self.root, msg)


# ******************************************************************************
# DEL 06c — SEND-TIME PICKER, UNDO-SEND TOAST, NOTIFICATION TOAST
# ******************************************************************************
#
# Three small windows that all live in the bottom-right corner of the screen
# (or, for the picker, centred on its parent). They are deliberately plain
# Toplevels rather than messageboxes because a modal dialog is exactly what
# you do NOT want when the whole point is "one quick click to cancel".


def _sent_toast(root, msg, seconds=1.4):
    """A one-line "done" toast in the bottom-right corner stack.

    Same shape and position rules as the delete-undo bar, minus the button:
    there is nothing to undo once the outbox has it, and the undo toast for
    that is a separate window with its own Cancel."""
    try:
        w = tk.Toplevel(root)
        w.overrideredirect(True)
        w.attributes("-topmost", True)
        w.configure(bg="#1a5c2a")
        _corner_stack(w, 300, 54)
        inner = tk.Frame(w, bg=C_TOAST_BG)
        inner.pack(fill="both", expand=True, padx=(3, 0))
        tk.Label(inner, text=f"✔  {msg}", bg=C_TOAST_BG, fg="#90ee90",
                 font=("Segoe UI", 10, "bold"), anchor="w").pack(
                     fill="both", expand=True, padx=12)

        def _bye():
            _corner_forget(w)
            try:
                if w.winfo_exists():
                    w.destroy()
            except Exception:
                pass
        w.after(int(seconds * 1000), _bye)
        return w
    except Exception as e:
        log.warning("sent toast failed: %s", e)
        return None


def _screen_corner(win, width, height, margin=18):
    """Place a window in the bottom-right corner of the screen, ignoring any
    toast already standing there.

    Kept, but nothing uses it any more: every toast now goes through
    _corner_stack (DEL 03), which puts it ABOVE whatever is already in the
    corner. Reach for this one only if you ever want a window that deliberately
    sits at the very bottom on its own."""
    try:
        sw = win.winfo_screenwidth()
        sh = win.winfo_screenheight()
        win.geometry(f"{width}x{height}+{sw - width - margin}"
                     f"+{sh - height - margin - 40}")
    except Exception:
        win.geometry(f"{width}x{height}")


def _ask_send_time(parent, root, purpose="send"):
    """Modal picker: pick a future point in time. Returns a datetime, or None.

    `purpose` only changes the wording — the same picker is used for "send
    this later" and for "hide this until", and a snooze dialog that says
    "Send this message later" would be plain wrong."""
    is_send = (purpose == "send")
    title   = "Send later" if is_send else "Notify me"
    heading = ("🕒  Send this message later" if is_send
               else "⏰  Notify me about this message on…")
    note    = ("F(re)email must be running at that time."
               if is_send else
               "The message stays exactly where it is. You get a pop-up "
               "then (or when the program starts, if it was closed).")
    ok_text = "Schedule" if is_send else "Set reminder"
    result = {"dt": None}

    top = tk.Toplevel(parent)
    top.title(title)
    top.configure(bg=C_BG3)
    top.resizable(False, False)
    _center_over(top, parent, 400, 330 if is_send else 520)
    top.transient(parent)
    top.grab_set()
    top.focus_force()
    top.bind("<Escape>", lambda e: top.destroy())

    tk.Label(top, text=heading,
             bg=C_BG3, fg=C_ACCENT, font=("Segoe UI", 12, "bold")).pack(pady=(14, 2))
    tk.Label(top, text=note,
             bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic")).pack()

    now = datetime.now()

    def _tomorrow_at(hour, minute=0, days=1):
        d = (now + timedelta(days=days)).replace(hour=hour, minute=minute,
                                                 second=0, microsecond=0)
        return d

    def _tonight():
        d = now.replace(hour=18, minute=0, second=0, microsecond=0)
        return d if d > now else _tomorrow_at(18)

    def _next_monday():
        d = _tomorrow_at(8, 0, days=(7 - now.weekday()) or 7)
        return d

    choices = [
        ("In 5 minutes",     lambda: now + timedelta(minutes=5)),
        ("In 30 minutes",    lambda: now + timedelta(minutes=30)),
        ("In 1 hour",        lambda: now + timedelta(hours=1)),
        ("In 3 hours",       lambda: now + timedelta(hours=3)),
        ("Tonight 18:00",    _tonight),
        ("Tomorrow 08:00",   lambda: _tomorrow_at(8)),
        ("Monday 08:00",     _next_monday),
    ]
    if not is_send:
        # A reminder is usually days to months away, not minutes (Issu
        # 2026-11-24: "om 2 månader ... veckor, månader och år").
        def _at9(dt):
            return dt.replace(hour=9, minute=0, second=0, microsecond=0)
        choices = [
            ("Tomorrow 08:00",   lambda: _tomorrow_at(8)),
            ("Monday 08:00",     _next_monday),
            ("In 1 week",        lambda: _at9(now + timedelta(weeks=1))),
            ("In 2 weeks",       lambda: _at9(now + timedelta(weeks=2))),
            ("In 1 month",       lambda: _at9(_add_months(now, 1))),
            ("In 2 months",      lambda: _at9(_add_months(now, 2))),
            ("In 3 months",      lambda: _at9(_add_months(now, 3))),
            ("In 6 months",      lambda: _at9(_add_months(now, 6))),
            ("In 1 year",        lambda: _at9(_add_months(now, 12))),
            ("In 2 years",       lambda: _at9(_add_months(now, 24))),
        ]

    grid = tk.Frame(top, bg=C_BG3)
    grid.pack(padx=16, pady=(10, 6), fill="x")

    def _pick(fn):
        result["dt"] = fn()
        top.destroy()

    for i, (label, fn) in enumerate(choices):
        b = tk.Button(grid, text=label, bg=C_BTN_STD, fg=C_BTN_FG,
                      font=("Segoe UI", 9), relief="flat", cursor="hand2",
                      padx=6, pady=4, command=lambda f=fn: _pick(f))
        b.grid(row=i // 2, column=i % 2, sticky="ew", padx=3, pady=3)
    grid.columnconfigure(0, weight=1)
    grid.columnconfigure(1, weight=1)

    tk.Frame(top, bg=C_SEP, height=1).pack(fill="x", padx=16, pady=(6, 0))

    if not is_send:
        # "In [N] [unit]" — any number of minutes … years.
        nrow = tk.Frame(top, bg=C_BG3)
        nrow.pack(fill="x", padx=16, pady=(10, 0))
        tk.Label(nrow, text="In:", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left")
        n_var = tk.StringVar(value="2")
        n_ent = tk.Entry(nrow, textvariable=n_var, width=5, bg=C_BG2,
                         fg=C_FG, relief="flat", font=("Segoe UI", 10),
                         insertbackground=C_ACCENT,
                         insertofftime=0, insertontime=9999999)
        no_blink(n_ent)
        n_ent.pack(side="left", padx=6, ipady=3)
        unit_var = tk.StringVar(value="months")
        units = ["minutes", "hours", "days", "weeks", "months", "years"]
        om = tk.OptionMenu(nrow, unit_var, *units)
        om.configure(bg=C_BTN_STD, fg=C_BTN_FG, relief="flat",
                     activebackground=C_BTN_STD, highlightthickness=0,
                     font=("Segoe UI", 9))
        om.pack(side="left")

        def _use_amount(event=None):
            try:
                n = int(n_var.get().strip())
                if n < 1:
                    raise ValueError
            except ValueError:
                err.configure(text="Type a whole number, 1 or more.")
                return
            u = unit_var.get()
            if u == "minutes":
                dt = now + timedelta(minutes=n)
            elif u == "hours":
                dt = now + timedelta(hours=n)
            elif u == "days":
                dt = _at9(now + timedelta(days=n))
            elif u == "weeks":
                dt = _at9(now + timedelta(weeks=n))
            elif u == "months":
                dt = _at9(_add_months(now, n))
            else:
                dt = _at9(_add_months(now, 12 * n))
            result["dt"] = dt
            top.destroy()

        tk.Button(nrow, text="Set", bg=C_BTN_NEW, fg=C_BTN_FG,
                  font=("Segoe UI", 9, "bold"), relief="flat",
                  cursor="hand2", padx=12, pady=3,
                  command=_use_amount).pack(side="left", padx=8)
        n_ent.bind("<Return>", _use_amount)
        tk.Label(top, text="(days and longer: at 09:00)", bg=C_BG3,
                 fg=C_FG_DIM, font=("Segoe UI", 8, "italic")
                 ).pack(anchor="w", padx=16)

    # Custom date+time — ENTER works, as everywhere else in this program.
    row = tk.Frame(top, bg=C_BG3)
    row.pack(fill="x", padx=16, pady=10)
    tk.Label(row, text="At:", bg=C_BG3, fg=C_FG_DIM,
             font=("Segoe UI", 9)).pack(side="left")
    e = tk.Entry(row, bg=C_BG2, fg=C_FG, relief="flat", font=("Segoe UI", 10),
                 insertbackground=C_ACCENT,
                 insertofftime=0, insertontime=9999999)
    no_blink(e)
    e.pack(side="left", fill="x", expand=True, padx=6, ipady=3)
    e.insert(0, (now + timedelta(hours=1)).strftime("%Y-%m-%d %H:%M"))

    err = tk.Label(top, text="", bg=C_BG3, fg="#ff9c9c",
                   font=("Segoe UI", 8))
    err.pack()

    def _use_custom(event=None):
        raw = e.get().strip()
        for fmt in ("%Y-%m-%d %H:%M", "%Y-%m-%d %H.%M", "%H:%M", "%Y-%m-%d"):
            try:
                dt = datetime.strptime(raw, fmt)
                if fmt == "%Y-%m-%d":          # a bare date = 09:00 that day
                    dt = dt.replace(hour=9, minute=0)
                if fmt == "%H:%M":
                    dt = now.replace(hour=dt.hour, minute=dt.minute,
                                     second=0, microsecond=0)
                    if dt <= now:
                        dt += timedelta(days=1)
                if dt <= now:
                    err.configure(text="That time has already passed.")
                    return
                result["dt"] = dt
                top.destroy()
                return
            except ValueError:
                continue
        err.configure(text="Use YYYY-MM-DD HH:MM  (or YYYY-MM-DD, or HH:MM)")

    e.bind("<Return>", _use_custom)

    btns = tk.Frame(top, bg=C_BG3)
    btns.pack(pady=(4, 14))
    tk.Button(btns, text=ok_text, bg=C_BTN_NEW, fg=C_BTN_FG,
              font=("Segoe UI", 9, "bold"), relief="flat", cursor="hand2",
              padx=14, pady=4, command=_use_custom).pack(side="left", padx=4)
    tk.Button(btns, text="Cancel", bg=C_BTN_STD, fg=C_BTN_FG,
              font=("Segoe UI", 9), relief="flat", cursor="hand2",
              padx=14, pady=4, command=top.destroy).pack(side="left", padx=4)

    e.focus_set()
    parent.wait_window(top)
    return result["dt"]


class UndoToast:
    """The little "Sending… [Cancel]" window shown after you press Send.

    Design rules from the request: it must be FAST and EASY to cancel — one
    click on a big button, no confirmation dialog, no hunting through menus.
    The countdown is optional (default off) because a ticking number is
    exactly the kind of thing that makes people stare at the screen."""

    def __init__(self, root, seconds, on_cancel, subject="",
                 countdown=False):
        self.root      = root
        self.on_cancel = on_cancel
        self.deadline  = datetime.now() + timedelta(seconds=seconds)
        self.countdown = countdown
        self._after_id = None
        self._done     = False

        w = tk.Toplevel(root)
        w.overrideredirect(True)
        w.configure(bg=C_TOAST_ACC)
        w.attributes("-topmost", True)
        _corner_stack(w, 330, 74)
        self.win = w

        inner = tk.Frame(w, bg=C_TOAST_BG)
        inner.pack(fill="both", expand=True, padx=(3, 0))

        left = tk.Frame(inner, bg=C_TOAST_BG)
        left.pack(side="left", fill="both", expand=True, padx=10, pady=8)

        self.lbl = tk.Label(left, text="Sending…", bg=C_TOAST_BG, fg=C_FG,
                            font=("Segoe UI", 10, "bold"), anchor="w")
        self.lbl.pack(fill="x")
        subj = (subject or "(no subject)")
        if len(subj) > 34:
            subj = subj[:33] + "…"
        tk.Label(left, text=subj, bg=C_TOAST_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 8), anchor="w").pack(fill="x")

        tk.Button(inner, text="Cancel", bg=C_BTN_UNDO, fg=C_BTN_FG,
                  font=("Segoe UI", 10, "bold"), relief="flat", cursor="hand2",
                  padx=14, pady=8, command=self._cancel).pack(side="right",
                                                              padx=10, pady=8)
        self._tick()

    def _tick(self):
        if self._done:
            return
        left = (self.deadline - datetime.now()).total_seconds()
        if left <= 0:
            self.close()
            return
        if self.countdown:
            if left >= 60:
                m, s = divmod(int(left), 60)
                self.lbl.configure(text=f"Sending in {m}:{s:02d}…")
            else:
                self.lbl.configure(text=f"Sending in {int(left) + 1} s…")
        try:
            self._after_id = self.win.after(250, self._tick)
        except Exception:
            pass

    def _cancel(self):
        if self._done:
            return
        self.close()
        try:
            self.on_cancel()
        except Exception as e:
            log.error("Undo-send cancel handler failed: %s", e)

    def close(self):
        self._done = True
        if self._after_id is not None:
            try:
                self.win.after_cancel(self._after_id)
            except Exception:
                pass
            self._after_id = None
        _corner_forget(self.win)
        try:
            if self.win.winfo_exists():
                self.win.destroy()
        except Exception:
            pass


class DeleteUndoToast:
    """The "Deleted N — Undo" bar shown after a delete (Issu 2026-08-01).

    Replaces the old Yes/No delete popup: the message goes at once, and this
    bar gives a big Undo button for a minute before the Gmail change is really
    made. Same look/feel as the send-undo toast. The APP owns the real commit
    timer; this window only shows the countdown and the button."""

    def __init__(self, root, seconds, count, on_undo):
        self.root     = root
        self.on_undo  = on_undo
        self.deadline = datetime.now() + timedelta(seconds=seconds)
        self._after_id = None
        self._done     = False

        w = tk.Toplevel(root)
        w.overrideredirect(True)
        w.configure(bg=C_TOAST_ACC)
        w.attributes("-topmost", True)
        _corner_stack(w, 330, 74)
        self.win = w

        inner = tk.Frame(w, bg=C_TOAST_BG)
        inner.pack(fill="both", expand=True, padx=(3, 0))

        left = tk.Frame(inner, bg=C_TOAST_BG)
        left.pack(side="left", fill="both", expand=True, padx=10, pady=8)

        self.lbl = tk.Label(
            left, text=f"Deleted {count} message(s)", bg=C_TOAST_BG, fg=C_FG,
            font=("Segoe UI", 10, "bold"), anchor="w")
        self.lbl.pack(fill="x")
        self.sub = tk.Label(left, text="", bg=C_TOAST_BG, fg=C_FG_DIM,
                            font=("Segoe UI", 8), anchor="w")
        self.sub.pack(fill="x")

        tk.Button(inner, text="↺ Undo", bg=C_BTN_UNDO, fg=C_BTN_FG,
                  font=("Segoe UI", 10, "bold"), relief="flat", cursor="hand2",
                  padx=14, pady=8, command=self._undo).pack(side="right",
                                                            padx=10, pady=8)
        self._tick()

    def _tick(self):
        if self._done:
            return
        left = (self.deadline - datetime.now()).total_seconds()
        if left <= 0:
            self.close()
            return
        self.sub.configure(text=f"Undo within {int(left) + 1} s")
        try:
            self._after_id = self.win.after(250, self._tick)
        except Exception:
            pass

    def _undo(self):
        if self._done:
            return
        self.close()
        try:
            self.on_undo()
        except Exception as e:
            log.error("Undo-delete handler failed: %s", e)

    def close(self):
        self._done = True
        if self._after_id is not None:
            try:
                self.win.after_cancel(self._after_id)
            except Exception:
                pass
            self._after_id = None
        _corner_forget(self.win)
        try:
            if self.win.winfo_exists():
                self.win.destroy()
        except Exception:
            pass


class NotifyToast:
    """Bottom-right "you have new mail" popup. Click it to jump to the
    message; it fades out on its own after a few seconds."""

    _open = []      # so several notifications stack instead of overlapping

    def __init__(self, root, title, lines, on_click=None, seconds=8):
        self.root     = root
        self.on_click = on_click

        w = tk.Toplevel(root)
        w.overrideredirect(True)
        w.configure(bg=C_TOAST_ACC)
        w.attributes("-topmost", True)
        height = 52 + 16 * min(len(lines), 3)
        # ONE shared corner stack for every kind of toast (_corner_stack): a
        # notification now steps over a send-undo or a delete-undo bar too, not
        # only over other notifications.
        #
        # NOTE: the stack sums REMEMBERED heights, not winfo_height(). A
        # Toplevel that has not been mapped yet reports a height of 1, so
        # asking Tk would stack every toast 9 pixels apart — they would still
        # sit on top of each other, which is the bug this code exists to
        # prevent.
        _corner_stack(w, 320, height)
        self.win = w
        NotifyToast._open.append(w)

        inner = tk.Frame(w, bg=C_TOAST_BG)
        inner.pack(fill="both", expand=True, padx=(3, 0))

        head = tk.Frame(inner, bg=C_TOAST_BG)
        head.pack(fill="x", padx=10, pady=(8, 2))
        tk.Label(head, text=title, bg=C_TOAST_BG, fg=C_ACCENT,
                 font=("Segoe UI", 10, "bold"), anchor="w").pack(side="left")
        close = tk.Label(head, text="✕", bg=C_TOAST_BG, fg=C_FG_DIM,
                         font=("Segoe UI", 9), cursor="hand2")
        close.pack(side="right")
        close.bind("<Button-1>", lambda e: self.close())

        for ln in lines[:3]:
            tk.Label(inner, text=ln, bg=C_TOAST_BG, fg=C_FG,
                     font=("Segoe UI", 9), anchor="w",
                     wraplength=290, justify="left").pack(fill="x", padx=10)

        if on_click is not None:
            for widget in (inner,) + tuple(inner.winfo_children()):
                widget.configure(cursor="hand2")
                widget.bind("<Button-1>", self._clicked)

        w.after(int(seconds * 1000), self.close)

    def _clicked(self, event=None):
        cb = self.on_click
        self.close()
        if cb:
            try:
                cb()
            except Exception as e:
                log.error("Notification click handler failed: %s", e)

    def close(self):
        _corner_forget(self.win)
        try:
            if self.win in NotifyToast._open:
                NotifyToast._open.remove(self.win)
        except Exception:
            pass
        try:
            if self.win.winfo_exists():
                self.win.destroy()
        except Exception:
            pass


# ******************************************************************************
# DEL 06d — CALENDAR WINDOW + EVENT EDITOR
# ******************************************************************************
#
# Three views, in the order you actually use them:
#   Month  — the overview; what does this month look like
#   Week   — one column per day, the working view
#   Agenda — a flat "what is coming" list, which is the one that answers
#            "do I have anything this week" fastest
#
# Deliberately built from Labels in a grid rather than a pixel-positioned time
# grid: a Thunderbird-style hour grid looks impressive and is miserable to
# read at 09:00 when three things overlap. A list per day always reads.

# Colours for the calendar (grouped here so the whole calendar can be
# restyled without hunting through the code).
C_CAL_TODAY   = "#1e3d6e"   # today's cell  — e.g. "#2e5d3e" for green
C_CAL_OTHER   = "#1f2130"   # days outside the shown month
C_CAL_CELL    = "#22253a"   # a normal day cell
C_CAL_SEL     = "#33374f"   # the selected day
C_CAL_WEEKEND = "#262436"   # Saturday/Sunday tint
C_HOLIDAY     = "#ff8a8a"   # public-holiday name  — e.g. "#7ad17a" for green

_MONTH_NAMES = ["January", "February", "March", "April", "May", "June",
                "July", "August", "September", "October", "November",
                "December"]
_DAY_NAMES   = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]


class EventEditor:
    """Create or edit one event. ENTER saves, ESC closes (house rule)."""

    def __init__(self, parent, store, event=None, on_saved=None, prefill=None):
        self.store    = store
        self.event    = event
        self.on_saved = on_saved
        self.is_new   = event is None

        top = tk.Toplevel(parent)
        top.title("New event" if self.is_new else "Edit event")
        top.configure(bg=C_BG3)
        _center_over(top, parent, 560, 640)
        top.transient(parent)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())
        self.top = top

        tk.Label(top, text="📅  " + ("New event" if self.is_new else "Edit event"),
                 bg=C_BG1, fg=C_ACCENT, font=("Segoe UI", 12, "bold"),
                 pady=8).pack(fill="x")

        # Scrollable body — the editor is taller than a small screen.
        outer = tk.Frame(top, bg=C_BG3)
        outer.pack(fill="both", expand=True)
        canvas = tk.Canvas(outer, bg=C_BG3, highlightthickness=0)
        sb = tk.Scrollbar(outer, command=canvas.yview, bg=C_BG3,
                          troughcolor=C_BG1)
        sb.pack(side="right", fill="y")
        canvas.pack(side="left", fill="both", expand=True)
        canvas.configure(yscrollcommand=sb.set)
        body = tk.Frame(canvas, bg=C_BG3)
        canvas.create_window((0, 0), window=body, anchor="nw", width=520)
        body.bind("<Configure>",
                  lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
        _bind_mousewheel(body, canvas)

        ev = event or {}
        start = _parse_iso(ev.get("start", "")) or (
            _parse_iso((prefill or {}).get("start", "")) or
            datetime.now().replace(minute=0, second=0, microsecond=0)
                    + timedelta(hours=1))
        end = _parse_iso(ev.get("end", "")) or (start + timedelta(hours=1))

        def _row(label):
            r = tk.Frame(body, bg=C_BG3)
            r.pack(fill="x", padx=16, pady=3)
            tk.Label(r, text=label, bg=C_BG3, fg=C_FG_DIM, width=11,
                     anchor="e", font=("Segoe UI", 9)).pack(side="left")
            return r

        def _entry(parent, value="", width=None):
            e = tk.Entry(parent, bg=C_BG2, fg=C_FG, relief="flat",
                         insertbackground=C_ACCENT, font=("Segoe UI", 10),
                         insertofftime=0, insertontime=9999999,
                         **({"width": width} if width else {}))
            no_blink(e)
            e.insert(0, value)
            return e

        # ── Title / location ─────────────────────────────────────────────────
        # The stored title may already have a ", Friday 10.00 (…)" tail baked in
        # (see the checkbox below); the editor always shows the CLEAN base so
        # editing never stacks the suffix twice.
        base_title = (ev.get("title_base")
                      or ev.get("title", "")
                      or (prefill or {}).get("title", ""))
        r = _row("Title:")
        self.e_title = _entry(r, base_title)
        self.e_title.pack(side="left", fill="x", expand=True, ipady=3)

        # Auto-append the date & time to the title (default ON for new events).
        r = _row("")
        self.v_title_dt = tk.BooleanVar(
            value=(True if self.is_new else bool(ev.get("title_datetime"))))
        tk.Checkbutton(r, text="Add date & time to the title", bg=C_BG3,
                       fg=C_FG, variable=self.v_title_dt, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9), highlightthickness=0).pack(side="left")
        self.v_title_fmt = tk.StringVar(
            value=ev.get("title_datetime_fmt", "name"))
        self._title_fmt_labels = {"Friday 10.00 (14 August)": "name",
                                  "14/08 (Friday) 10.00": "numeric"}
        fmt_cur = next((k for k, v in self._title_fmt_labels.items()
                        if v == self.v_title_fmt.get()),
                       "Friday 10.00 (14 August)")
        self.v_title_fmt_lbl = tk.StringVar(value=fmt_cur)
        om = tk.OptionMenu(r, self.v_title_fmt_lbl,
                           *self._title_fmt_labels.keys())
        om.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                     activeforeground=C_FG, highlightthickness=0,
                     relief="flat", font=("Segoe UI", 8))
        om["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                             activeforeground=C_FG)
        om.pack(side="left", padx=6)

        r = _row("Location:")
        self.e_loc = _entry(r, ev.get("location", "") or
                            (prefill or {}).get("location", ""))
        self.e_loc.pack(side="left", fill="x", expand=True, ipady=3)

        # ── When ─────────────────────────────────────────────────────────────
        def _cal_btn(parent, entry):
            return tk.Button(parent, text="📅", bg=C_BTN_STD, fg=C_BTN_FG,
                             font=("Segoe UI", 9), relief="flat", cursor="hand2",
                             padx=4, pady=0,
                             command=lambda e=entry: self._pick_date(e))

        r = _row("Date:")
        self.e_date = _entry(r, start.strftime("%Y-%m-%d"), width=12)
        self.e_date.pack(side="left", ipady=3)
        _cal_btn(r, self.e_date).pack(side="left", padx=(2, 0))
        tk.Label(r, text="  Start:", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left")
        self.e_start = _entry(r, start.strftime("%H:%M"), width=7)
        self.e_start.pack(side="left", ipady=3)
        tk.Label(r, text="  End:", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left")
        self.e_end = _entry(r, end.strftime("%H:%M"), width=7)
        self.e_end.pack(side="left", ipady=3)

        r = _row("")
        self.v_allday = tk.BooleanVar(value=bool(ev.get("all_day")))
        tk.Checkbutton(r, text="All day", variable=self.v_allday,
                       bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9), highlightthickness=0,
                       command=self._update_field_states).pack(side="left")
        # Optional end. OFF by default for a new event — most people only need
        # to know when a thing STARTS. Ticking it un-greys the end time / date.
        has_end_default = (False if self.is_new
                           else bool(ev.get("has_end", True)))
        self.v_has_end = tk.BooleanVar(value=has_end_default)
        tk.Checkbutton(r, text="Set an end", variable=self.v_has_end,
                       bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9), highlightthickness=0,
                       command=self._update_field_states).pack(side="left",
                                                               padx=(14, 0))
        r2 = _row("End date:")
        self.e_enddate = _entry(r2, end.strftime("%Y-%m-%d"), width=12)
        self.e_enddate.pack(side="left", ipady=3)
        self._end_cal_btn = _cal_btn(r2, self.e_enddate)
        self._end_cal_btn.pack(side="left", padx=(2, 0))
        tk.Label(r2, text="  (only for multi-day events)",
                 bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(side="left")

        # ── Repeat ───────────────────────────────────────────────────────────
        tk.Frame(body, bg=C_SEP, height=1).pack(fill="x", padx=16, pady=(10, 6))
        tk.Label(body, text="Repeat", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 10, "bold"),
                 anchor="w").pack(fill="x", padx=16)

        rule = _rrule_of(ev)
        r = _row("Repeats:")
        self.v_freq = tk.StringVar(value=(rule.get("freq") or "NONE").title()
                                   if rule else "Never")
        freq_labels = {"Never": "", "Daily": "DAILY", "Weekly": "WEEKLY",
                       "Monthly": "MONTHLY", "Yearly": "YEARLY"}
        self._freq_labels = freq_labels
        cur_freq = next((k for k, v in freq_labels.items()
                         if v == (rule.get("freq") if rule else "")), "Never")
        self.v_freq.set(cur_freq)
        om = tk.OptionMenu(r, self.v_freq, *freq_labels.keys())
        om.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                     activeforeground=C_FG, highlightthickness=0,
                     relief="flat", font=("Segoe UI", 9), width=8)
        om["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                             activeforeground=C_FG)
        om.pack(side="left")
        tk.Label(r, text="  every", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left")
        self.e_interval = _entry(r, str(rule.get("interval", 1) if rule else 1),
                                 width=4)
        self.e_interval.pack(side="left", ipady=3)
        tk.Label(r, text="(1 = every time, 2 = every other…)", bg=C_BG3,
                 fg=C_FG_DIM, font=("Segoe UI", 8)).pack(side="left", padx=4)

        r = _row("On days:")
        self.v_days = {}
        for code, name in zip(_WEEKDAY_CODES, _DAY_NAMES):
            v = tk.BooleanVar(value=code in (rule.get("byday", []) if rule else []))
            self.v_days[code] = v
            tk.Checkbutton(r, text=name, variable=v, bg=C_BG3, fg=C_FG,
                           selectcolor=C_BG2, activebackground=C_BG3,
                           activeforeground=C_FG, font=("Segoe UI", 8),
                           highlightthickness=0).pack(side="left")
        tk.Label(body, text="            (weekly only — leave empty to repeat "
                            "on the event's own weekday)",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8),
                 anchor="w").pack(fill="x", padx=16)

        r = _row("Ends:")
        self.v_end_mode = tk.StringVar(
            value="count" if (rule and rule.get("count")) else
                  ("until" if (rule and rule.get("until")) else "never"))
        for val, text in (("never", "never"), ("count", "after"),
                          ("until", "on date")):
            tk.Radiobutton(r, text=text, value=val, variable=self.v_end_mode,
                           bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                           activebackground=C_BG3, activeforeground=C_FG,
                           font=("Segoe UI", 9),
                           highlightthickness=0).pack(side="left")
        self.e_count = _entry(r, str(rule.get("count") or 10) if rule else "10",
                              width=4)
        self.e_count.pack(side="left", ipady=3)
        tk.Label(r, text="times  or", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(side="left", padx=2)
        until_dt = _parse_iso(rule.get("until", "")) if rule else None
        self.e_until = _entry(
            r, (until_dt or (start + timedelta(days=90))).strftime("%Y-%m-%d"),
            width=11)
        self.e_until.pack(side="left", ipady=3)

        # ── Reminders ────────────────────────────────────────────────────────
        # Adaptive builder (Issu 2026-08-13): instead of one flat list of
        # fixed offsets, you assemble an offset from Days/Hours/Minutes (the
        # day range is capped to the event's own lead time) or tap a "smart"
        # % button, and it is added to a chip list below. Several reminders
        # per event still work exactly as before — just added one at a time.
        tk.Frame(body, bg=C_SEP, height=1).pack(fill="x", padx=16, pady=(10, 6))
        tk.Label(body, text="Remind me", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 10, "bold"),
                 anchor="w").pack(fill="x", padx=16)
        tk.Label(body, text="A popup appears while F(re)email is running. "
                            "Add as many reminders as you like.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8),
                 anchor="w").pack(fill="x", padx=16)

        self._rem_list = sorted(set(int(m) for m in (ev.get("reminders") or [])))
        self._rem_chip_fr = tk.Frame(body, bg=C_BG3)
        self._rem_chip_fr.pack(fill="x", padx=22, pady=(4, 2))

        tk.Label(body, text="Add a reminder:", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8), anchor="w").pack(fill="x", padx=26,
                                                        pady=(4, 0))
        add_fr = tk.Frame(body, bg=C_BG3)
        add_fr.pack(fill="x", padx=26, pady=(2, 2))

        tk.Label(add_fr, text="Days", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(side="left")
        self.sp_days = tk.Spinbox(add_fr, from_=0, to=max(0, self._max_reminder_days()),
                                  width=3, bg=C_BG2, fg=C_FG, relief="flat",
                                  buttonbackground=C_BG4,
                                  font=("Segoe UI", 9))
        self.sp_days.delete(0, "end")
        self.sp_days.insert(0, "0")
        self.sp_days.pack(side="left", padx=(3, 10), ipady=1)

        tk.Label(add_fr, text="Hours", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(side="left")
        self.v_add_hours = tk.StringVar(value="0")
        om_h = tk.OptionMenu(add_fr, self.v_add_hours,
                             *[str(h) for h in REMINDER_HOUR_CHOICES])
        om_h.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                       activeforeground=C_FG, highlightthickness=0,
                       relief="flat", font=("Segoe UI", 8), width=2)
        om_h["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                               activeforeground=C_FG)
        om_h.pack(side="left", padx=(3, 10))

        tk.Label(add_fr, text="Min", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(side="left")
        self.v_add_mins = tk.StringVar(value="0")
        om_m = tk.OptionMenu(add_fr, self.v_add_mins,
                             *[str(m) for m in REMINDER_MINUTE_CHOICES])
        om_m.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                       activeforeground=C_FG, highlightthickness=0,
                       relief="flat", font=("Segoe UI", 8), width=2)
        om_m["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                               activeforeground=C_FG)
        om_m.pack(side="left", padx=(3, 10))

        tk.Button(add_fr, text="+ Add", bg=C_BTN_STD, fg=C_BTN_FG,
                 font=("Segoe UI", 8, "bold"), relief="flat", cursor="hand2",
                 padx=8, pady=2,
                 command=self._add_reminder_from_builder).pack(side="left")

        tk.Label(body, text="…or a smart pick (% of the time left):",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8),
                 anchor="w").pack(fill="x", padx=26, pady=(6, 0))
        smart_fr = tk.Frame(body, bg=C_BG3)
        smart_fr.pack(fill="x", padx=26, pady=(2, 4))
        for pct in REMINDER_SMART_PERCENTS:
            tk.Button(smart_fr, text=f"{pct}%", bg=C_BTN_STD, fg=C_BTN_FG,
                     font=("Segoe UI", 8), relief="flat", cursor="hand2",
                     padx=6, pady=2,
                     command=lambda p=pct: self._add_reminder_smart(p)
                     ).pack(side="left", padx=2)

        self._render_reminder_chips()

        # ── Repeating / accelerating reminders (DEL 04f2) ────────────────────
        ser = ev.get("reminder_series") or {}
        self.v_rep = tk.BooleanVar(value=bool(ser.get("enabled")))
        rep_fr = tk.Frame(body, bg=C_BG3)
        rep_fr.pack(fill="x", padx=26, pady=(2, 0))
        tk.Checkbutton(rep_fr, text="…and keep reminding me — starting",
                       variable=self.v_rep, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9), highlightthickness=0,
                       command=self._update_field_states).pack(side="left")

        self._lead_labels = {lbl: mins for mins, lbl in REMINDER_LEAD_CHOICES}
        cur_lead = next((lbl for mins, lbl in REMINDER_LEAD_CHOICES
                         if mins == int(ser.get("lead_min", 1440))),
                        "1 day before")
        self.v_lead = tk.StringVar(value=cur_lead)
        self._om_lead = tk.OptionMenu(rep_fr, self.v_lead,
                                      *self._lead_labels.keys())
        self._om_lead.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                                activeforeground=C_FG, highlightthickness=0,
                                relief="flat", font=("Segoe UI", 8))
        self._om_lead["menu"].configure(bg=C_BG2, fg=C_FG,
                                        activebackground=C_BG4,
                                        activeforeground=C_FG)
        self._om_lead.pack(side="left", padx=3)
        tk.Label(rep_fr, text="every", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left")
        self._every_labels = {lbl: mins for mins, lbl in REMINDER_EVERY_CHOICES}
        cur_every = next((lbl for mins, lbl in REMINDER_EVERY_CHOICES
                          if mins == int(ser.get("interval_min", 180))),
                         "3 hours")
        self.v_every = tk.StringVar(value=cur_every)
        self._om_every = tk.OptionMenu(rep_fr, self.v_every,
                                       *self._every_labels.keys())
        self._om_every.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                                 activeforeground=C_FG, highlightthickness=0,
                                 relief="flat", font=("Segoe UI", 8))
        self._om_every["menu"].configure(bg=C_BG2, fg=C_FG,
                                         activebackground=C_BG4,
                                         activeforeground=C_FG)
        self._om_every.pack(side="left", padx=3)

        rep2 = tk.Frame(body, bg=C_BG3)
        rep2.pack(fill="x", padx=44, pady=(0, 2))
        self.v_accel = tk.BooleanVar(value=bool(ser.get("accelerate")))
        self._chk_accel = tk.Checkbutton(
            rep2, text="getting more frequent as it approaches (snowball)",
            variable=self.v_accel, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
            activebackground=C_BG3, activeforeground=C_FG,
            font=("Segoe UI", 8), highlightthickness=0)
        self._chk_accel.pack(side="left")
        self._lbl_series = tk.Label(body, text="", bg=C_BG3, fg=C_FG_DIM,
                                    font=("Segoe UI", 7), anchor="w",
                                    wraplength=480, justify="left")
        self._lbl_series.pack(fill="x", padx=44)
        for _v in (self.v_lead, self.v_every, self.v_accel):
            _v.trace_add("write", lambda *a: self._update_series_preview())

        # ── Alert style (DEL 04f2) — how loud/insistent the reminder is ──────
        r = _row("Alert:")
        self._alert_labels = {lbl: code for code, lbl in ALERT_CHOICES}
        cur_alert = next((lbl for code, lbl in ALERT_CHOICES
                          if code == ev.get("alert", "sound")), "A sound")
        self.v_alert = tk.StringVar(value=cur_alert)
        om = tk.OptionMenu(r, self.v_alert, *self._alert_labels.keys())
        om.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                     activeforeground=C_FG, highlightthickness=0,
                     relief="flat", font=("Segoe UI", 9), width=24, anchor="w")
        om["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                             activeforeground=C_FG)
        om.pack(side="left")
        tk.Label(body, text="            'Insistent' beeps more (and repeats) the "
                            "closer the event gets.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 7),
                 anchor="w").pack(fill="x", padx=16)

        # ── Colour ───────────────────────────────────────────────────────────
        r = _row("Colour:")
        self.v_color = tk.StringVar(value=ev.get("color", EVENT_PALETTE[0]))
        for c in EVENT_PALETTE:
            b = tk.Label(r, text="   ", bg=c, cursor="hand2",
                         relief="raised", bd=1)
            b.pack(side="left", padx=2)
            b.bind("<Button-1>", lambda e, cc=c: self._set_color(cc))
        self.lbl_color = tk.Label(r, text="  ●", bg=C_BG3,
                                  fg=self.v_color.get(),
                                  font=("Segoe UI", 12))
        self.lbl_color.pack(side="left")

        # ── Notes ────────────────────────────────────────────────────────────
        tk.Label(body, text="Notes:", bg=C_BG3, fg=C_FG_DIM, anchor="w",
                 font=("Segoe UI", 9)).pack(fill="x", padx=16, pady=(8, 2))
        self.t_desc = tk.Text(body, bg=C_BG2, fg=C_FG, relief="flat", height=5,
                              wrap="word", font=("Segoe UI", 10), padx=8,
                              pady=6, insertbackground=C_ACCENT,
                              insertofftime=0, insertontime=9999999)
        no_blink(self.t_desc)
        self.t_desc.insert("1.0", ev.get("description", "") or
                           (prefill or {}).get("description", ""))
        self.t_desc.pack(fill="x", padx=16, pady=(0, 10))

        # ── Buttons ──────────────────────────────────────────────────────────
        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(fill="x", pady=8)
        tk.Button(btns, text="Save", bg=C_BTN_NEW, fg=C_BTN_FG,
                  font=("Segoe UI", 9, "bold"), relief="flat", cursor="hand2",
                  padx=18, pady=4, command=self._save).pack(side="left", padx=8)
        if not self.is_new:
            tk.Button(btns, text="Delete", bg=C_BTN_DEL, fg=C_BTN_FG,
                      font=("Segoe UI", 9), relief="flat", cursor="hand2",
                      padx=16, pady=4,
                      command=self._delete).pack(side="left", padx=4)
        tk.Button(btns, text="Cancel", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=16, pady=4, command=top.destroy).pack(side="right",
                                                             padx=8)
        top.bind("<Return>", lambda e: self._save())
        self._update_field_states()
        self.e_title.focus_set()

    def _set_color(self, c):
        self.v_color.set(c)
        self.lbl_color.configure(fg=c)

    # ── Adaptive reminders (Issu 2026-08-13) ────────────────────────────────
    def _minutes_until_event(self) -> int:
        """Minutes between now and the event's start, read live from the
        Date/Start/All-day fields (so it tracks edits made in this dialog).
        Never negative — an event already in the past just has 0 left."""
        try:
            day = datetime.strptime(self.e_date.get().strip(), "%Y-%m-%d")
        except (ValueError, AttributeError):
            return 0
        if self.v_allday.get():
            start_dt = day.replace(hour=0, minute=0)
        else:
            raw = self.e_start.get().strip().replace(".", ":")
            start_dt = None
            for fmt in ("%H:%M", "%H"):
                try:
                    t = datetime.strptime(raw, fmt)
                    start_dt = day.replace(hour=t.hour, minute=t.minute)
                    break
                except ValueError:
                    continue
            if start_dt is None:
                start_dt = day.replace(hour=9, minute=0)
        return max(0, int((start_dt - datetime.now()).total_seconds() // 60))

    def _max_reminder_days(self) -> int:
        """Upper bound for the Days spinner: whole days of lead time the
        event actually has, minus one day held back for the Hours/Minutes
        part of the same reminder — so a day value alone can never already be
        overdue the moment you add it. 0 (the default) is always allowed."""
        return max(0, (self._minutes_until_event() // 1440) - 1)

    def _add_reminder(self, mins):
        mins = max(0, int(mins))
        if mins not in self._rem_list:
            self._rem_list.append(mins)
            self._rem_list.sort()
        self._render_reminder_chips()

    def _remove_reminder(self, mins):
        if mins in self._rem_list:
            self._rem_list.remove(mins)
        self._render_reminder_chips()

    def _render_reminder_chips(self):
        """Redraw the chip list (3 per row) from self._rem_list, furthest-out
        reminder first, each with a small ✕ to remove it."""
        for w in self._rem_chip_fr.winfo_children():
            w.destroy()
        if not self._rem_list:
            tk.Label(self._rem_chip_fr, text="(no reminders set)",
                     bg=C_BG3, fg=C_FG_DIM,
                     font=("Segoe UI", 8, "italic")
                     ).grid(row=0, column=0, sticky="w", pady=2)
            return
        for i, mins in enumerate(sorted(self._rem_list, reverse=True)):
            chip = tk.Frame(self._rem_chip_fr, bg=C_BG2)
            chip.grid(row=i // 3, column=i % 3, sticky="w", padx=3, pady=2)
            tk.Label(chip, text=_format_reminder_label(mins), bg=C_BG2,
                     fg=C_FG, font=("Segoe UI", 8), padx=6, pady=2
                     ).pack(side="left")
            x = tk.Label(chip, text="✕", bg=C_BG2, fg=C_FG_DIM,
                        font=("Segoe UI", 8, "bold"), cursor="hand2", padx=4)
            x.pack(side="left")
            x.bind("<Button-1>", lambda e, m=mins: self._remove_reminder(m))

    def _add_reminder_from_builder(self):
        try:
            d = int(self.sp_days.get())
        except (ValueError, TypeError):
            d = 0
        try:
            h = int(self.v_add_hours.get())
        except (ValueError, TypeError):
            h = 0
        try:
            m = int(self.v_add_mins.get())
        except (ValueError, TypeError):
            m = 0
        mins = d * 1440 + h * 60 + m
        total = self._minutes_until_event()
        if total and mins > total:
            if not messagebox.askyesno(
                    "Reminder",
                    "That is more lead time than is left before the event — "
                    "the reminder would be due right away. Add it anyway?",
                    parent=self.top):
                return
        self._add_reminder(mins)

    def _add_reminder_smart(self, pct):
        total = self._minutes_until_event()
        if total <= 0:
            messagebox.showinfo("Reminder",
                                "There is no time left before this event to "
                                "base a percentage on.", parent=self.top)
            return
        self._add_reminder(int(round(total * pct / 100)))

    def _update_field_states(self):
        """Grey out the fields that don't apply right now: an all-day event has
        no clock; with no 'Set an end' there is no end time or end date; with no
        repeating reminder the lead/every/accelerate controls are inert."""
        all_day = self.v_allday.get()
        has_end = self.v_has_end.get()
        try:
            self.e_start.configure(state="disabled" if all_day else "normal")
        except Exception:
            pass
        try:
            self.e_end.configure(
                state="normal" if (has_end and not all_day) else "disabled")
        except Exception:
            pass
        for w in (self.e_enddate, getattr(self, "_end_cal_btn", None)):
            try:
                w.configure(state="normal" if has_end else "disabled")
            except Exception:
                pass
        on = self.v_rep.get()
        for w in (getattr(self, "_om_lead", None),
                  getattr(self, "_om_every", None),
                  getattr(self, "_chk_accel", None)):
            try:
                w.configure(state="normal" if on else "disabled")
            except Exception:
                pass
        self._update_series_preview()

    def _update_series_preview(self):
        """Spell out, in plain words, exactly when the repeating reminder would
        fire — so 'snowball' is concrete before you save it."""
        lbl = getattr(self, "_lbl_series", None)
        if lbl is None:
            return
        if not self.v_rep.get():
            lbl.configure(text="")
            return
        lead  = self._lead_labels.get(self.v_lead.get(), 1440)
        every = self._every_labels.get(self.v_every.get(), 180)
        offs  = _reminder_series_offsets(lead, every, self.v_accel.get())

        def _h(m):
            if m == 0:
                return "at start"
            if m % 1440 == 0:
                return f"{m // 1440} d"
            if m % 60 == 0:
                return f"{m // 60} h"
            return f"{m} min"
        desc = " · ".join(_h(m) for m in sorted(offs, reverse=True))
        lbl.configure(text=f"→ {len(offs)} reminders: {desc}  (before the event)")

    def _pick_date(self, entry):
        """A small month calendar (Issu asked for an almanac on the date
        fields). Clicking a day fills `entry` with YYYY-MM-DD."""
        import calendar as _calmod
        try:
            cur = datetime.strptime(entry.get().strip(), "%Y-%m-%d")
        except Exception:
            cur = datetime.now()
        win = tk.Toplevel(self.top)
        win.title("Pick a date")
        win.configure(bg=C_BG3)
        win.transient(self.top)
        win.grab_set()
        win.focus_force()
        win.bind("<Escape>", lambda e: win.destroy())
        state = {"y": cur.year, "m": cur.month}
        grid = tk.Frame(win, bg=C_BG3)
        grid.pack(padx=10, pady=10)

        def _choose(day):
            prev = str(entry.cget("state"))
            entry.configure(state="normal")
            entry.delete(0, "end")
            entry.insert(0, f"{state['y']:04d}-{state['m']:02d}-{day:02d}")
            if prev == "disabled":
                entry.configure(state="disabled")
            win.destroy()

        def _shift(delta):
            m = state["m"] - 1 + delta
            state["y"] += m // 12
            state["m"] = m % 12 + 1
            _draw()

        def _draw():
            for w in grid.winfo_children():
                w.destroy()
            hdr = tk.Frame(grid, bg=C_BG3)
            hdr.grid(row=0, column=0, columnspan=7, sticky="ew", pady=(0, 4))
            tk.Button(hdr, text="‹", bg=C_BTN_STD, fg=C_BTN_FG, relief="flat",
                      cursor="hand2", font=("Segoe UI", 9), width=2,
                      command=lambda: _shift(-1)).pack(side="left")
            tk.Label(hdr, text=f"{_FULL_MONTHS[state['m'] - 1]} {state['y']}",
                     bg=C_BG3, fg=C_ACCENT, font=("Segoe UI", 10, "bold"),
                     width=18).pack(side="left", expand=True)
            tk.Button(hdr, text="›", bg=C_BTN_STD, fg=C_BTN_FG, relief="flat",
                      cursor="hand2", font=("Segoe UI", 9), width=2,
                      command=lambda: _shift(1)).pack(side="left")
            for c, d in enumerate(("Mo", "Tu", "We", "Th", "Fr", "Sa", "Su")):
                tk.Label(grid, text=d, bg=C_BG3, fg=C_FG_DIM,
                         font=("Segoe UI", 8, "bold"), width=3).grid(row=1,
                                                                     column=c)
            today = datetime.now().date()
            week = 2
            for wk in _calmod.Calendar(firstweekday=0).monthdayscalendar(
                    state["y"], state["m"]):
                for c, day in enumerate(wk):
                    if day == 0:
                        continue
                    is_today = (day == today.day and state["m"] == today.month
                                and state["y"] == today.year)
                    tk.Button(grid, text=str(day),
                              bg=C_ACCENT if is_today else C_BG2,
                              fg=C_BTN_FG if is_today else C_FG, relief="flat",
                              cursor="hand2", font=("Segoe UI", 9), width=3,
                              command=lambda d=day: _choose(d)).grid(
                                  row=week, column=c, padx=1, pady=1)
                week += 1
        _draw()

    def _collect(self):
        """Read the form into an event dict, or None after complaining."""
        title = self.e_title.get().strip()
        if not title:
            messagebox.showwarning("Event", "Give the event a title.",
                                   parent=self.top)
            return None
        try:
            day = datetime.strptime(self.e_date.get().strip(), "%Y-%m-%d")
        except ValueError:
            messagebox.showwarning("Event", "Date must be YYYY-MM-DD.",
                                   parent=self.top)
            return None
        all_day = bool(self.v_allday.get())
        has_end = bool(self.v_has_end.get())
        if all_day:
            start = day.replace(hour=0, minute=0)
            if has_end:
                try:
                    end_day = datetime.strptime(self.e_enddate.get().strip(),
                                                "%Y-%m-%d")
                except ValueError:
                    end_day = day
                end = max(end_day, day) + timedelta(days=1)
            else:
                end = start + timedelta(days=1)     # a single all-day
        else:
            def _time(entry, fallback):
                raw = entry.get().strip().replace(".", ":")
                for fmt in ("%H:%M", "%H"):
                    try:
                        t = datetime.strptime(raw, fmt)
                        return t.hour, t.minute
                    except ValueError:
                        continue
                return fallback
            sh, sm = _time(self.e_start, (9, 0))
            start = day.replace(hour=sh, minute=sm)
            if has_end:
                eh, em = _time(self.e_end, (sh + 1, sm))
                try:
                    end_day = datetime.strptime(self.e_enddate.get().strip(),
                                                "%Y-%m-%d")
                except ValueError:
                    end_day = day
                end = end_day.replace(hour=eh, minute=em)
                if end <= start:
                    end = start + timedelta(hours=1)
            else:
                end = start + timedelta(hours=1)    # internal default; not shown

        freq = self._freq_labels.get(self.v_freq.get(), "")
        rrule = {}
        if freq:
            try:
                interval = max(1, int(self.e_interval.get().strip() or "1"))
            except ValueError:
                interval = 1
            rrule = {"freq": freq, "interval": interval}
            if freq == "WEEKLY":
                days = [c for c, v in self.v_days.items() if v.get()]
                if days:
                    rrule["byday"] = days
            mode = self.v_end_mode.get()
            if mode == "count":
                try:
                    rrule["count"] = max(1, int(self.e_count.get().strip()))
                except ValueError:
                    rrule["count"] = 10
            elif mode == "until":
                try:
                    u = datetime.strptime(self.e_until.get().strip(),
                                          "%Y-%m-%d")
                    rrule["until"] = u.replace(hour=23, minute=59
                                               ).isoformat(timespec="seconds")
                except ValueError:
                    messagebox.showwarning("Event",
                                           "End date must be YYYY-MM-DD.",
                                           parent=self.top)
                    return None

        # Optionally bake the date & time into the title (Issu: type just
        # "Doctor", store "Doctor, Friday 10.00 (14 August)"). The clean base is
        # kept separately so editing never stacks the suffix twice.
        base_title = title
        # Never bake a specific date into a REPEATING event's title — the one
        # stored title is shared by every occurrence, so "…(14 August)" would be
        # wrong for all the later ones. The clean base is what gets stored.
        show_dt = bool(self.v_title_dt.get()) and not rrule
        fmt = self._title_fmt_labels.get(self.v_title_fmt_lbl.get(), "name")
        final_title = (base_title + _event_title_suffix(start, all_day, fmt)
                       if show_dt else base_title)

        series = {
            "enabled":      bool(self.v_rep.get()),
            "lead_min":     int(self._lead_labels.get(self.v_lead.get(), 1440)),
            "interval_min": int(self._every_labels.get(self.v_every.get(), 180)),
            "accelerate":   bool(self.v_accel.get()),
        }

        old = self.event or {}
        return {
            "id":          old.get("id") or _new_id(),
            "title":       final_title,
            "title_base":  base_title,
            "title_datetime":     show_dt,
            "title_datetime_fmt": fmt,
            "location":    self.e_loc.get().strip(),
            "description": self.t_desc.get("1.0", "end-1c").strip(),
            "start":       start.isoformat(timespec="seconds"),
            "end":         end.isoformat(timespec="seconds"),
            "all_day":     all_day,
            "has_end":     has_end,
            "rrule":       rrule,
            "reminders":   sorted(self._rem_list),
            "reminder_series": series,
            "alert":       self._alert_labels.get(self.v_alert.get(), "sound"),
            "color":       self.v_color.get(),
            "uid":         old.get("uid", ""),
            "source":      old.get("source", "manual"),
            "created":     old.get("created") or _now_iso(),
        }

    def _save(self):
        rec = self._collect()
        if rec is None:
            return
        events = self.store.setdefault("events", [])
        for i, e in enumerate(events):
            if e.get("id") == rec["id"]:
                events[i] = rec
                break
        else:
            events.append(rec)
        _save_calendar(self.store)
        self.top.destroy()
        if self.on_saved:
            self.on_saved()

    def _delete(self):
        if not messagebox.askyesno(
                "Delete event",
                f"Delete “{(self.event or {}).get('title','')}”?\n\n"
                f"If it repeats, every occurrence goes.", parent=self.top):
            return
        eid = (self.event or {}).get("id")
        self.store["events"] = [e for e in self.store.get("events", [])
                                if e.get("id") != eid]
        _save_calendar(self.store)
        self.top.destroy()
        if self.on_saved:
            self.on_saved()


class CalendarWindow:
    """The calendar itself — month, week and agenda views over one store."""

    def __init__(self, app, root, cfg, store, focus_date=None):
        self.app   = app
        self.root  = root
        self.cfg   = cfg
        self.store = store
        self.cursor = focus_date or datetime.now().replace(
            hour=0, minute=0, second=0, microsecond=0)
        self.selected = self.cursor
        self.view = cfg.get("cal_view", "Month")

        top = tk.Toplevel(root)
        top.title("Calendar — F(re)email")
        top.configure(bg=C_BG1)
        top.minsize(760, 520)
        _center_over(top, root, int(cfg.get("cal_win_w", 1000)),
                     int(cfg.get("cal_win_h", 680)))
        # Not modal on purpose: reading mail while the calendar is open is
        # exactly what you want to do. Still focus_force + Escape per house
        # rule.
        top.focus_force()
        top.bind("<Escape>", lambda e: self._close())
        top.protocol("WM_DELETE_WINDOW", self._close)
        top.bind("<Left>",  lambda e: self._step(-1))
        top.bind("<Right>", lambda e: self._step(1))
        top.bind("<Configure>", self._on_configure)
        self.top = top

        self._build_toolbar()
        self.body = tk.Frame(top, bg=C_BG1)
        self.body.pack(fill="both", expand=True)
        self.render()

    # ── Chrome ────────────────────────────────────────────────────────────────
    def _build_toolbar(self):
        tb = tk.Frame(self.top, bg=C_BG1, pady=5)
        tb.pack(fill="x")

        def _btn(text, colour, cmd, side="left", width=None):
            b = tk.Button(tb, text=text, bg=colour, fg=C_BTN_FG,
                          font=("Segoe UI", 9), relief="flat", cursor="hand2",
                          padx=10, pady=3, command=cmd,
                          **({"width": width} if width else {}))
            b.pack(side=side, padx=3)
            return b

        _btn("◀", C_BTN_STD, lambda: self._step(-1), width=2)
        _btn("Today", C_BTN_STD, self._today)
        _btn("▶", C_BTN_STD, lambda: self._step(1), width=2)

        tk.Frame(tb, bg=C_SEP, width=1).pack(side="left", fill="y", padx=6)
        self.v_view = tk.StringVar(value=self.view)
        for name in ("Month", "Week", "Agenda"):
            tk.Radiobutton(tb, text=name, value=name, variable=self.v_view,
                           command=self._switch_view, bg=C_BG1, fg=C_FG,
                           selectcolor=C_BG2, activebackground=C_BG1,
                           activeforeground=C_FG, font=("Segoe UI", 9),
                           highlightthickness=0,
                           indicatoron=False, padx=10, pady=3,
                           relief="flat").pack(side="left", padx=2)

        tk.Frame(tb, bg=C_SEP, width=1).pack(side="left", fill="y", padx=6)
        _btn("＋ New event", C_BTN_NEW, self._new_event)
        _btn("📥 Import .ics", C_BTN_STD, self._import_ics)
        _btn("📤 Export .ics", C_BTN_STD, self._export_ics)
        _btn("Close", C_BTN_STD, self._close, side="right")

        self.lbl_period = tk.Label(tb, text="", bg=C_BG1, fg=C_ACCENT,
                                   font=("Segoe UI", 12, "bold"))
        self.lbl_period.pack(side="right", padx=16)

    def _on_configure(self, event):
        if event.widget is self.top:
            try:
                self.cfg["cal_win_w"] = self.top.winfo_width()
                self.cfg["cal_win_h"] = self.top.winfo_height()
            except Exception:
                pass

    def _close(self):
        self.cfg["cal_view"] = self.view
        # Same reason as FreemailApp._on_close: never write settings back over
        # a configuration that was just restored from a backup.
        if not getattr(self.app, "_settings_restored", False):
            _save_settings(self.cfg)
        if getattr(self.app, "_calendar_win", None) is self:
            self.app._calendar_win = None
        try:
            self.top.destroy()
        except Exception:
            pass

    # ── Navigation ────────────────────────────────────────────────────────────
    def _switch_view(self):
        self.view = self.v_view.get()
        self.render()

    def _today(self):
        self.cursor = datetime.now().replace(hour=0, minute=0, second=0,
                                             microsecond=0)
        self.selected = self.cursor
        self.render()

    def _step(self, direction):
        if self.view == "Month":
            self.cursor = _add_months(self.cursor.replace(day=1), direction)
        elif self.view == "Week":
            self.cursor = self.cursor + timedelta(weeks=direction)
        else:
            self.cursor = self.cursor + timedelta(days=30 * direction)
        self.render()

    # ── Rendering ─────────────────────────────────────────────────────────────
    def render(self):
        for w in self.body.winfo_children():
            w.destroy()
        if self.view == "Month":
            self._render_month()
        elif self.view == "Week":
            self._render_week()
        else:
            self._render_agenda()

    def _event_chip(self, parent, occ, ev, compact=True, day=None):
        """One clickable line representing an event occurrence.

        `day` is the cell this chip is being drawn in. On the second and later
        days of a multi-day event the start time would be a lie, so those days
        get a "→" continuation marker instead."""
        colour = ev.get("color") or EVENT_PALETTE[0]
        continued = day is not None and day.date() != occ.date()
        if continued:
            text = f"→  {ev.get('title','')}"
        else:
            text = (f"{'' if ev.get('all_day') else occ.strftime('%H:%M') + '  '}"
                    f"{ev.get('title','')}")
        if not compact and ev.get("location"):
            text += f"   · {ev['location']}"
        # A thin coloured strip on the left is how the colour reads best on a
        # dark background — a fully tinted row drowns the text.
        #
        # BUGFIX: the label MUST be a child of `wrap`. It used to be a child of
        # `parent` and merely packed `in_=wrap`; because `wrap` was created
        # after it, `wrap` sat on top in the sibling stacking order and hid the
        # text completely — the calendar showed only bare coloured bars ("bara
        # en ljusblå rad"). Parenting it to `wrap` puts the text back on top.
        wrap = tk.Frame(parent, bg=colour)
        wrap.pack(fill="x", pady=1, padx=2)
        lbl = tk.Label(wrap, text=" " + text, bg=C_BG3, fg=C_FG,
                       font=("Segoe UI", 8 if compact else 9), anchor="w",
                       cursor="hand2", padx=2)
        lbl.pack(fill="x", padx=(3, 0))
        for w in (wrap, lbl):
            w.bind("<Button-1>", lambda e, x=ev: self._edit_event(x))
            w.bind("<Enter>", lambda e, l=lbl: l.configure(bg=C_BG4))
            w.bind("<Leave>", lambda e, l=lbl: l.configure(bg=C_BG3))
        return wrap

    def _render_month(self):
        first = self.cursor.replace(day=1)
        self.lbl_period.configure(
            text=f"{_MONTH_NAMES[first.month - 1]} {first.year}")

        grid = tk.Frame(self.body, bg=C_SEP)
        grid.pack(fill="both", expand=True, padx=6, pady=6)
        # Column 0 is the week number; the seven days follow.
        grid.columnconfigure(0, weight=0, minsize=34)
        for c in range(1, 8):
            grid.columnconfigure(c, weight=1, uniform="day")

        tk.Label(grid, text="v.", bg=C_BG1, fg=C_FG_DIM,
                 font=("Segoe UI", 8, "bold"), pady=4
                 ).grid(row=0, column=0, sticky="nsew", padx=1, pady=1)
        for c, name in enumerate(_DAY_NAMES):
            tk.Label(grid, text=name, bg=C_BG1,
                     fg=C_ACCENT if c < 5 else C_FG_DIM,
                     font=("Segoe UI", 9, "bold"), pady=4
                     ).grid(row=0, column=c + 1, sticky="nsew", padx=1, pady=1)

        start_cell = first - timedelta(days=first.weekday())
        weeks = 6
        for r in range(weeks):
            grid.rowconfigure(r + 1, weight=1, uniform="week")
        win_start = start_cell
        win_end   = start_cell + timedelta(weeks=weeks)
        by_day = _events_by_day(self.store, win_start, win_end)

        today = datetime.now().date()
        for i in range(weeks * 7):
            day = start_cell + timedelta(days=i)
            r, c = i // 7 + 1, i % 7
            # Week number, once per row, in its own narrow column.
            if c == 0:
                tk.Label(grid, text=str(day.isocalendar()[1]), bg=C_BG1,
                         fg=C_FG_DIM, font=("Segoe UI", 8), pady=2
                         ).grid(row=r, column=0, sticky="nsew", padx=1, pady=1)

            holiday = _holiday_name(day)
            if day.date() == today:
                bg = C_CAL_TODAY
            elif day.month != first.month:
                bg = C_CAL_OTHER
            elif holiday or c >= 5:
                # A public holiday reads like a weekend, because it is one.
                bg = C_CAL_WEEKEND
            else:
                bg = C_CAL_CELL
            if day.date() == self.selected.date() and day.date() != today:
                bg = C_CAL_SEL

            cell = tk.Frame(grid, bg=bg)
            cell.grid(row=r, column=c + 1, sticky="nsew", padx=1, pady=1)
            head = tk.Label(cell,
                            text=str(day.day) + ("  ·  today"
                                                 if day.date() == today else ""),
                            bg=bg,
                            fg=(C_HOLIDAY if holiday and day.month == first.month
                                else C_FG if day.month == first.month
                                else C_FG_DIM),
                            font=("Segoe UI", 9,
                                  "bold" if day.date() == today else "normal"),
                            anchor="w", padx=4)
            head.pack(fill="x")
            if holiday and day.month == first.month:
                tk.Label(cell, text=holiday[:18], bg=bg, fg=C_HOLIDAY,
                         font=("Segoe UI", 7), anchor="w",
                         padx=4).pack(fill="x")

            items = by_day.get(day.date(), [])
            for occ, ev in items[:3]:
                self._event_chip(cell, occ, ev, day=day)
            if len(items) > 3:
                more = tk.Label(cell, text=f"  +{len(items) - 3} more", bg=bg,
                                fg=C_ACCENT, font=("Segoe UI", 8),
                                anchor="w", cursor="hand2")
                more.pack(fill="x")
                more.bind("<Button-1>",
                          lambda e, d=day: self._open_day(d))

            for w in (cell, head):
                w.bind("<Button-1>", lambda e, d=day: self._select_day(d))
                w.bind("<Double-Button-1>",
                       lambda e, d=day: self._new_event(d))

    def _render_week(self):
        start = self.cursor - timedelta(days=self.cursor.weekday())
        start = start.replace(hour=0, minute=0, second=0, microsecond=0)
        end   = start + timedelta(days=7)
        self.lbl_period.configure(
            text=f"{start.strftime('%d %b')} – "
                 f"{(end - timedelta(days=1)).strftime('%d %b %Y')}   "
                 f"(week {start.isocalendar()[1]})")

        cols = tk.Frame(self.body, bg=C_SEP)
        cols.pack(fill="both", expand=True, padx=6, pady=6)
        for c in range(7):
            cols.columnconfigure(c, weight=1, uniform="d")
        cols.rowconfigure(1, weight=1)

        by_day = _events_by_day(self.store, start, end)

        today = datetime.now().date()
        for i in range(7):
            day = start + timedelta(days=i)
            is_today = day.date() == today
            hdr_bg = C_CAL_TODAY if is_today else C_BG1
            hol = _holiday_name(day)
            tk.Label(cols,
                     text=f"{_DAY_NAMES[i]}  {day.day}"
                          f"{'  ·  today' if is_today else ''}"
                          + (f"\n{hol[:20]}" if hol else ""),
                     bg=hdr_bg,
                     fg=(C_ACCENT if is_today else
                         C_HOLIDAY if hol else C_FG),
                     font=("Segoe UI", 9, "bold"), pady=4
                     ).grid(row=0, column=i, sticky="nsew", padx=1, pady=1)

            cell = tk.Frame(cols, bg=C_CAL_CELL if i < 5 else C_CAL_WEEKEND)
            cell.grid(row=1, column=i, sticky="nsew", padx=1, pady=1)
            items = by_day.get(day.date(), [])
            for occ, ev in items:
                self._event_chip(cell, occ, ev, compact=False, day=day)
            if not items:
                tk.Label(cell, text="", bg=cell["bg"]).pack()
            cell.bind("<Double-Button-1>", lambda e, d=day: self._new_event(d))

    def _render_agenda(self):
        start = self.cursor.replace(hour=0, minute=0, second=0, microsecond=0)
        end   = start + timedelta(days=60)
        self.lbl_period.configure(
            text=f"Next 60 days from {start.strftime('%Y-%m-%d')}")

        outer = tk.Frame(self.body, bg=C_BG2)
        outer.pack(fill="both", expand=True, padx=6, pady=6)
        canvas = tk.Canvas(outer, bg=C_BG2, highlightthickness=0)
        sb = tk.Scrollbar(outer, command=canvas.yview, bg=C_BG3,
                          troughcolor=C_BG1)
        sb.pack(side="right", fill="y")
        canvas.pack(side="left", fill="both", expand=True)
        canvas.configure(yscrollcommand=sb.set)
        inner = tk.Frame(canvas, bg=C_BG2)
        win = canvas.create_window((0, 0), window=inner, anchor="nw")
        inner.bind("<Configure>",
                   lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
        canvas.bind("<Configure>",
                    lambda e: canvas.itemconfigure(win, width=e.width))
        _bind_mousewheel(inner, canvas)

        rows = _events_between(self.store, start, end)
        if not rows:
            tk.Label(inner, text="\n   Nothing planned in the next 60 days.",
                     bg=C_BG2, fg=C_FG_DIM, font=("Segoe UI", 11),
                     anchor="w").pack(fill="x")
            return

        today = datetime.now().date()
        last_date = None
        for occ, ev in rows:
            if occ.date() != last_date:
                last_date = occ.date()
                label = occ.strftime("%A  %d %B %Y")
                if occ.date() == today:
                    label += "   ·  today"
                elif occ.date() == today + timedelta(days=1):
                    label += "   ·  tomorrow"
                tk.Label(inner, text="  " + label, bg=C_BG1,
                         fg=C_ACCENT if occ.date() == today else C_FG_DIM,
                         font=("Segoe UI", 9, "bold"), anchor="w", pady=4
                         ).pack(fill="x", pady=(8, 2))

            row = tk.Frame(inner, bg=C_BG2)
            row.pack(fill="x", padx=10)
            tk.Frame(row, bg=ev.get("color") or EVENT_PALETTE[0],
                     width=4).pack(side="left", fill="y")
            txt = tk.Label(row,
                           text=f"  {_fmt_event_time(occ, ev):<14}"
                                f"{ev.get('title','')}"
                                f"{'   · ' + ev['location'] if ev.get('location') else ''}",
                           bg=C_BG2, fg=C_FG, font=("Segoe UI", 10),
                           anchor="w", cursor="hand2", pady=3)
            txt.pack(side="left", fill="x", expand=True)
            if ev.get("reminders"):
                tk.Label(row, text="🔔", bg=C_BG2, fg=C_FG_DIM,
                         font=("Segoe UI", 9)).pack(side="right", padx=6)
            if _rrule_of(ev):
                tk.Label(row, text="🔁", bg=C_BG2, fg=C_FG_DIM,
                         font=("Segoe UI", 9)).pack(side="right")
            txt.bind("<Button-1>", lambda e, x=ev: self._edit_event(x))
            txt.bind("<Enter>", lambda e, w=txt: w.configure(bg=C_BG4))
            txt.bind("<Leave>", lambda e, w=txt: w.configure(bg=C_BG2))

    # ── Day interaction ───────────────────────────────────────────────────────
    def _select_day(self, day):
        self.selected = day
        self.render()

    def _open_day(self, day):
        """Show one day's full list — used by "+N more" in the month view."""
        self.cursor = day
        self.selected = day
        self.view = "Week"
        self.v_view.set("Week")
        self.render()

    # ── Actions ───────────────────────────────────────────────────────────────
    def _new_event(self, day=None):
        day = day or self.selected or datetime.now()
        start = day.replace(hour=9, minute=0, second=0, microsecond=0)
        if start.date() == datetime.now().date():
            start = datetime.now().replace(minute=0, second=0,
                                           microsecond=0) + timedelta(hours=1)
        EventEditor(self.top, self.store,
                    prefill={"start": start.isoformat(timespec="seconds")},
                    on_saved=self.render)

    def _edit_event(self, ev):
        EventEditor(self.top, self.store, event=ev, on_saved=self.render)

    def _import_ics(self):
        from tkinter import filedialog
        path = filedialog.askopenfilename(
            parent=self.top, title="Import calendar file",
            filetypes=[("Calendar files", "*.ics"), ("All files", "*.*")])
        if not path:
            return
        try:
            with open(path, "r", encoding="utf-8", errors="replace") as f:
                events = _ics_parse(f.read())
        except Exception as e:
            log.error("ICS import failed: %s", e)
            messagebox.showerror("Import", f"Could not read that file:\n{e}",
                                 parent=self.top)
            return
        added = _merge_events(self.store, events)
        messagebox.showinfo(
            "Import",
            f"{added} event(s) imported"
            f"{f', {len(events) - added} already there' if len(events) != added else ''}.",
            parent=self.top)
        self.render()

    def _export_ics(self):
        from tkinter import filedialog
        events = self.store.get("events", [])
        if not events:
            messagebox.showinfo("Export", "There is nothing to export yet.",
                                parent=self.top)
            return
        path = filedialog.asksaveasfilename(
            parent=self.top, title="Export calendar",
            defaultextension=".ics", initialfile="Freemail_calendar.ics",
            filetypes=[("Calendar files", "*.ics"), ("All files", "*.*")])
        if not path:
            return
        try:
            with open(path, "w", encoding="utf-8", newline="") as f:
                f.write(_ics_export(events))
        except Exception as e:
            log.error("ICS export failed: %s", e)
            messagebox.showerror("Export", f"Could not write that file:\n{e}",
                                 parent=self.top)
            return
        messagebox.showinfo("Export",
                            f"{len(events)} event(s) written to:\n\n{path}",
                            parent=self.top)


def _merge_events(store: dict, events: list) -> int:
    """Add events, skipping ones already present. Returns how many were new.

    Identity is the iCalendar UID when there is one — re-importing the same
    invitation must not double it — falling back to title+start."""
    have_uid   = {e.get("uid") for e in store.get("events", []) if e.get("uid")}
    have_pairs = {(e.get("title"), e.get("start"))
                  for e in store.get("events", [])}
    added = 0
    for ev in events:
        if ev.get("uid") and ev["uid"] in have_uid:
            continue
        if (ev.get("title"), ev.get("start")) in have_pairs:
            continue
        store.setdefault("events", []).append(ev)
        have_uid.add(ev.get("uid"))
        have_pairs.add((ev.get("title"), ev.get("start")))
        added += 1
    if added:
        _save_calendar(store)
    return added


class ReminderPopup:
    """A calendar reminder. Non-modal, snoozeable, and it does not steal the
    keyboard — an alarm that interrupts your typing is worse than the thing
    it is reminding you about."""

    _open = []      # so two reminders due at once stack instead of overlapping

    def __init__(self, root, app, ev, occ, mins, key):
        self.app = app
        self.key = key
        self.ev  = ev
        self.occ = occ

        w = tk.Toplevel(root)
        w.overrideredirect(True)
        w.attributes("-topmost", True)
        w.configure(bg=ev.get("color") or EVENT_PALETTE[0])
        # Two meetings starting at the same minute is exactly when reminders
        # matter most, so they must not land on top of each other — nor on top
        # of a send/delete toast (_corner_stack owns the whole corner now).
        # Wider and a little taller than it was: the snooze offers are now
        # words like "2 days" rather than "5 min", and they carry a caption
        # line of their own (DEL 04f3).
        _corner_stack(w, 380, 186)
        ReminderPopup._open[:] = [t for t in ReminderPopup._open
                                  if t.winfo_exists()]
        ReminderPopup._open.append(w)
        self.win = w

        inner = tk.Frame(w, bg=C_TOAST_BG)
        inner.pack(fill="both", expand=True, padx=(4, 0))

        head = tk.Frame(inner, bg=C_TOAST_BG)
        head.pack(fill="x", padx=12, pady=(10, 0))
        tk.Label(head, text="🔔  Reminder", bg=C_TOAST_BG, fg=C_ACCENT,
                 font=("Segoe UI", 10, "bold")).pack(side="left")
        close = tk.Label(head, text="✕", bg=C_TOAST_BG, fg=C_FG_DIM,
                         font=("Segoe UI", 9), cursor="hand2")
        close.pack(side="right")
        close.bind("<Button-1>", lambda e: self._dismiss())

        tk.Label(inner, text=ev.get("title", ""), bg=C_TOAST_BG, fg=C_FG,
                 font=("Segoe UI", 11, "bold"), anchor="w", wraplength=340,
                 justify="left").pack(fill="x", padx=12, pady=(4, 0))

        when = ("all day" if ev.get("all_day")
                else occ.strftime("%A %d %b, %H:%M"))
        detail = when
        # Show the ACTUAL time left until the event, not the reminder's
        # configured offset — if you created the event after the "5 min before"
        # moment had passed, saying "in 5 min" would be a lie.
        left = 0
        if not ev.get("all_day"):
            left = int((occ - datetime.now()).total_seconds() // 60)
            if left > 0:
                detail += (f"   (in {left} min)" if left < 60
                           else f"   (in {left // 60} h {left % 60} min)")
            elif left == 0:
                detail += "   (now)"
            else:
                detail += f"   ({-left} min ago)"
        if ev.get("location"):
            detail += f"\n📍 {ev['location']}"
        tk.Label(inner, text=detail, bg=C_TOAST_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 9), anchor="w", justify="left",
                 wraplength=340).pack(fill="x", padx=12)

        # ── Snooze buttons sized to the time that is LEFT (DEL 04f3) ──────
        # See _snooze_choices: 24 h out offers 3 h / 8 h / 12 h, a week out
        # offers days, three hours out never offers "tomorrow", and nothing
        # offered can fire after the event itself.
        tk.Label(inner, text="Remind me again in…", bg=C_TOAST_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 8), anchor="w").pack(fill="x", padx=12,
                                                        pady=(8, 0))
        btns = tk.Frame(inner, bg=C_TOAST_BG)
        btns.pack(fill="x", padx=10, pady=(2, 8))
        for minutes in _snooze_choices(left):
            b = tk.Button(btns, text=_snooze_label(minutes), bg=C_BTN_STD,
                          fg=C_BTN_FG, font=("Segoe UI", 8), relief="flat",
                          cursor="hand2", padx=8, pady=3,
                          command=lambda m=minutes: self._snooze(m))
            b.pack(side="left", padx=2)
            add_tooltip(b, f"Show this reminder again in "
                           f"{_snooze_label(minutes)}"
                           + (f" — still {_snooze_label(left)} before it starts"
                              if left > 0 else ""))
        tk.Button(btns, text="Dismiss", bg=C_BTN_NEW, fg=C_BTN_FG,
                  font=("Segoe UI", 8, "bold"), relief="flat", cursor="hand2",
                  padx=10, pady=3,
                  command=self._dismiss).pack(side="right", padx=2)

    def _snooze(self, minutes):
        self.app._snooze_reminder(self, minutes)
        self.close()

    def _dismiss(self):
        self.app._dismiss_reminder(self)
        self.close()

    def close(self):
        _corner_forget(self.win)
        try:
            if self.win in ReminderPopup._open:
                ReminderPopup._open.remove(self.win)
        except Exception:
            pass
        try:
            if self.win.winfo_exists():
                self.win.destroy()
        except Exception:
            pass


# ******************************************************************************
# DEL 06e — FOLLOW-UP: setup dialog and the (very different) last reminder
# ******************************************************************************

# The final reminder gets its own colours so it cannot be mistaken for one of
# the ordinary ones. Change these to restyle it.
C_FINAL_EDGE = "#c86a12"   # border of the last reminder — e.g. "#b02020" red
C_FINAL_HEAD = "#ffcf8a"   # its heading text
C_FOLLOWUP   = "#c88a2a"   # the follow-up accent used elsewhere


class FollowUpDialog:
    """Set up "remind me about this mail until I have dealt with it"."""

    # (label, minutes) for the repeat rhythm
    _REPEATS = [("Only once — no repeat", 0),
                ("Every 30 minutes", 30),
                ("Every hour", 60),
                ("Every 3 hours", 180),
                ("Every day", 1440),
                ("Every 2 days", 2880),
                ("Every week", 10080)]

    def __init__(self, parent, app, msg, existing=None, on_saved=None):
        self.app      = app
        self.msg      = msg
        self.existing = existing
        self.on_saved = on_saved

        top = tk.Toplevel(parent)
        top.title("Remind me about this message")
        top.configure(bg=C_BG3)
        _center_over(top, parent, 560, 760)
        top.transient(parent)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())
        self.top = top

        tk.Label(top, text="🔔  Not finished with this message",
                 bg=C_BG1, fg=C_FOLLOWUP, font=("Segoe UI", 12, "bold"),
                 pady=8).pack(fill="x")
        tk.Label(top, text=(msg.get("subject") or "(no subject)")[:70],
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 10, "bold"),
                 wraplength=520).pack(pady=(10, 0), padx=16)
        tk.Label(top, text=f"from {msg.get('from_name') or msg.get('from','')}",
                 bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(padx=16)

        body = tk.Frame(top, bg=C_BG3)
        body.pack(fill="both", expand=True, padx=16, pady=8)

        # ── What is left to do ───────────────────────────────────────────────
        tk.Label(body, text="What is still to do?  (optional)", bg=C_BG3,
                 fg=C_FG_DIM, font=("Segoe UI", 9),
                 anchor="w").pack(fill="x", pady=(4, 2))
        self.e_note = tk.Entry(body, bg=C_BG2, fg=C_FG, relief="flat",
                               insertbackground=C_ACCENT,
                               font=("Segoe UI", 10),
                               insertofftime=0, insertontime=9999999)
        no_blink(self.e_note)
        self.e_note.pack(fill="x", ipady=3)
        if existing:
            self.e_note.insert(0, existing.get("note", ""))

        tk.Frame(body, bg=C_SEP, height=1).pack(fill="x", pady=10)

        # ── First reminder ───────────────────────────────────────────────────
        tk.Label(body, text="Remind me the first time:", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 10, "bold"), anchor="w").pack(fill="x")
        now = datetime.now()
        self._first_choices = [
            ("In 1 hour",        now + timedelta(hours=1)),
            ("In 3 hours",       now + timedelta(hours=3)),
            ("Tomorrow 09:00",   (now + timedelta(days=1)).replace(
                hour=9, minute=0, second=0, microsecond=0)),
            ("In 3 days",        now + timedelta(days=3)),
            ("In a week",        now + timedelta(weeks=1)),
            ("In 1 month",       _add_months(now, 1).replace(
                hour=9, minute=0, second=0, microsecond=0)),
            ("In 2 months",      _add_months(now, 2).replace(
                hour=9, minute=0, second=0, microsecond=0)),
            ("In 3 months",      _add_months(now, 3).replace(
                hour=9, minute=0, second=0, microsecond=0)),
        ]
        self.v_first = tk.StringVar(value=self._first_choices[0][0])
        grid = tk.Frame(body, bg=C_BG3)
        grid.pack(fill="x", pady=4)
        for i, (label, _dt) in enumerate(self._first_choices):
            tk.Radiobutton(grid, text=label, value=label,
                           variable=self.v_first, bg=C_BG3, fg=C_FG,
                           selectcolor=C_BG2, activebackground=C_BG3,
                           activeforeground=C_FG, font=("Segoe UI", 9),
                           highlightthickness=0, anchor="w"
                           ).grid(row=i // 3, column=i % 3, sticky="w", padx=4)
        for _c in range(3):
            grid.columnconfigure(_c, weight=1)

        row = tk.Frame(body, bg=C_BG3)
        row.pack(fill="x", pady=(4, 0))
        tk.Radiobutton(row, text="At:", value="custom", variable=self.v_first,
                       bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9),
                       highlightthickness=0).pack(side="left")
        self.e_first = tk.Entry(row, bg=C_BG2, fg=C_FG, relief="flat",
                                width=18, insertbackground=C_ACCENT,
                                font=("Segoe UI", 10),
                                insertofftime=0, insertontime=9999999)
        no_blink(self.e_first)
        self.e_first.pack(side="left", ipady=3, padx=6)
        first_dt = (_parse_iso(existing.get("first_at", "")) if existing
                    else None) or (now + timedelta(hours=1))
        self.e_first.insert(0, first_dt.strftime("%Y-%m-%d %H:%M"))

        tk.Frame(body, bg=C_SEP, height=1).pack(fill="x", pady=10)

        # ── Then how often ───────────────────────────────────────────────────
        tk.Label(body, text="And after that, remind me again:", bg=C_BG3,
                 fg=C_FG, font=("Segoe UI", 10, "bold"),
                 anchor="w").pack(fill="x")
        tk.Label(body,
                 text="The wait before the FIRST reminder and the rhythm "
                      "afterwards are set separately — e.g. first in 3 hours, "
                      "then once a day.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w",
                 justify="left", wraplength=500).pack(fill="x")
        cur_repeat = int(existing.get("repeat_min", 0)) if existing else 1440
        self.v_repeat = tk.IntVar(value=cur_repeat)
        rgrid = tk.Frame(body, bg=C_BG3)
        rgrid.pack(fill="x", pady=4)
        for i, (label, mins) in enumerate(self._REPEATS):
            tk.Radiobutton(rgrid, text=label, value=mins,
                           variable=self.v_repeat, bg=C_BG3, fg=C_FG,
                           selectcolor=C_BG2, activebackground=C_BG3,
                           activeforeground=C_FG, font=("Segoe UI", 9),
                           highlightthickness=0, anchor="w"
                           ).grid(row=i // 2, column=i % 2, sticky="w", padx=4)
        rgrid.columnconfigure(0, weight=1)
        rgrid.columnconfigure(1, weight=1)

        tk.Frame(body, bg=C_SEP, height=1).pack(fill="x", pady=10)

        # ── When does it stop ────────────────────────────────────────────────
        tk.Label(body, text="Keep reminding me:", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 10, "bold"), anchor="w").pack(fill="x")
        mode = "stop"
        if existing:
            if int(existing.get("max_count") or 0):
                mode = "count"
            elif existing.get("until"):
                mode = "until"
        self.v_end = tk.StringVar(value=mode)

        r1 = tk.Frame(body, bg=C_BG3); r1.pack(fill="x", pady=2)
        tk.Radiobutton(r1, text="until I press “Stop reminding”",
                       value="stop", variable=self.v_end, bg=C_BG3, fg=C_FG,
                       selectcolor=C_BG2, activebackground=C_BG3,
                       activeforeground=C_FG, font=("Segoe UI", 9),
                       highlightthickness=0).pack(side="left")

        r2 = tk.Frame(body, bg=C_BG3); r2.pack(fill="x", pady=2)
        tk.Radiobutton(r2, text="only", value="count", variable=self.v_end,
                       bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9),
                       highlightthickness=0).pack(side="left")
        self.e_count = tk.Entry(r2, bg=C_BG2, fg=C_FG, relief="flat", width=4,
                                insertbackground=C_ACCENT,
                                font=("Segoe UI", 10),
                                insertofftime=0, insertontime=9999999)
        no_blink(self.e_count)
        self.e_count.pack(side="left", ipady=2, padx=4)
        self.e_count.insert(0, str(int(existing.get("max_count") or 3))
                            if existing else "3")
        tk.Label(r2, text="times in total", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left")

        r3 = tk.Frame(body, bg=C_BG3); r3.pack(fill="x", pady=2)
        tk.Radiobutton(r3, text="never after", value="until",
                       variable=self.v_end, bg=C_BG3, fg=C_FG,
                       selectcolor=C_BG2, activebackground=C_BG3,
                       activeforeground=C_FG, font=("Segoe UI", 9),
                       highlightthickness=0).pack(side="left")
        self.e_until = tk.Entry(r3, bg=C_BG2, fg=C_FG, relief="flat", width=12,
                                insertbackground=C_ACCENT,
                                font=("Segoe UI", 10),
                                insertofftime=0, insertontime=9999999)
        no_blink(self.e_until)
        self.e_until.pack(side="left", ipady=2, padx=4)
        until_dt = (_parse_iso(existing.get("until", "")) if existing
                    else None) or (now + timedelta(days=30))
        self.e_until.insert(0, until_dt.strftime("%Y-%m-%d"))

        tk.Label(body,
                 text="The very last reminder is shown differently, so you "
                      "know it is the final one.",
                 bg=C_BG3, fg=C_FOLLOWUP, font=("Segoe UI", 8, "italic"),
                 anchor="w").pack(fill="x", pady=(6, 0))

        # ── Lift the mail itself (2026-11-23) ────────────────────────────────
        tk.Frame(body, bg=C_SEP, height=1).pack(fill="x", pady=10)
        self.v_float = tk.BooleanVar(
            value=(bool(existing.get("float")) if existing else True))
        tk.Checkbutton(body,
                       text="When the time comes: mark the mail UNREAD and "
                            "lift it to the TOP of its folder",
                       variable=self.v_float, bg=C_BG3, fg=C_FG,
                       selectcolor=C_BG2, activebackground=C_BG3,
                       activeforeground=C_FG, font=("Segoe UI", 9, "bold"),
                       highlightthickness=0, anchor="w", justify="left",
                       wraplength=500).pack(fill="x")
        tk.Label(body,
                 text="It stays there until you press ✔ Done or set a new "
                      "reminder on it.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w",
                 justify="left", wraplength=500).pack(fill="x", padx=22)

        self.err = tk.Label(top, text="", bg=C_BG3, fg="#ff9c9c",
                            font=("Segoe UI", 8))
        self.err.pack()

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(pady=10)
        tk.Button(btns, text="Save", bg=C_BTN_NEW, fg=C_BTN_FG,
                  font=("Segoe UI", 9, "bold"), relief="flat", cursor="hand2",
                  padx=18, pady=4, command=self._save).pack(side="left", padx=5)
        if existing:
            tk.Button(btns, text="Remove", bg=C_BTN_DEL, fg=C_BTN_FG,
                      font=("Segoe UI", 9), relief="flat", cursor="hand2",
                      padx=14, pady=4,
                      command=self._remove).pack(side="left", padx=5)
        tk.Button(btns, text="Cancel", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=18, pady=4, command=top.destroy).pack(side="left", padx=5)
        top.bind("<Return>", lambda e: self._save())
        self.e_note.focus_set()
        # As tall as the content needs (the extra choices made it taller than
        # the old fixed 620 - Save was cut off), but never taller than the screen.
        top.update_idletasks()
        _center_over(top, parent, 560,
                     min(top.winfo_reqheight() + 8,
                         top.winfo_screenheight() - 80))

    def _first_datetime(self):
        choice = self.v_first.get()
        if choice != "custom":
            for label, dt in self._first_choices:
                if label == choice:
                    return dt
        raw = self.e_first.get().strip().replace(".", ":")
        for fmt in ("%Y-%m-%d %H:%M", "%Y-%m-%d", "%H:%M"):
            try:
                dt = datetime.strptime(raw, fmt)
                now = datetime.now()
                if fmt == "%H:%M":
                    dt = now.replace(hour=dt.hour, minute=dt.minute,
                                     second=0, microsecond=0)
                    if dt <= now:
                        dt += timedelta(days=1)
                elif fmt == "%Y-%m-%d":
                    dt = dt.replace(hour=9)
                return dt
            except ValueError:
                continue
        return None

    def _save(self):
        first = self._first_datetime()
        if first is None:
            self.err.configure(text="First reminder: use YYYY-MM-DD HH:MM")
            return
        if first <= datetime.now():
            self.err.configure(text="That time has already passed.")
            return
        repeat = int(self.v_repeat.get())
        mode   = self.v_end.get()
        max_count, until = 0, None
        if mode == "count":
            try:
                max_count = max(1, int(self.e_count.get().strip()))
            except ValueError:
                self.err.configure(text="“only N times” must be a number.")
                return
        elif mode == "until":
            try:
                until = datetime.strptime(self.e_until.get().strip(),
                                          "%Y-%m-%d").replace(hour=23,
                                                              minute=59)
            except ValueError:
                self.err.configure(text="End date: use YYYY-MM-DD")
                return
            if until <= first:
                self.err.configure(text="The end date is before the first "
                                        "reminder.")
                return

        store = self.app._followup_store
        if self.existing:
            _followup_remove(store, self.existing.get("id", ""))
        item = _followup_new(self.msg, first, repeat_min=repeat,
                             max_count=max_count, until=until,
                             note=self.e_note.get().strip(),
                             float_up=bool(self.v_float.get()))
        store.setdefault("items", []).append(item)
        _save_followups(store)
        self.top.destroy()
        self.app._flash("Reminder set: " + _followup_describe(item))
        if self.on_saved:
            self.on_saved()

    def _remove(self):
        _followup_remove(self.app._followup_store,
                         self.existing.get("id", ""))
        self.top.destroy()
        self.app._flash("Reminder removed")
        if self.on_saved:
            self.on_saved()


class FollowUpReminder:
    """The nag itself. The LAST one looks deliberately unlike the others."""

    _open = []

    def __init__(self, root, app, item, is_final):
        self.app  = app
        self.item = item
        self.final = is_final

        w = tk.Toplevel(root)
        w.overrideredirect(True)
        w.attributes("-topmost", True)
        w.configure(bg=C_FINAL_EDGE if is_final else C_FOLLOWUP)
        height = 200 if is_final else 168
        _corner_stack(w, 380, height)       # shared corner stack, see DEL 03
        FollowUpReminder._open[:] = [t for t in FollowUpReminder._open
                                     if t.winfo_exists()]
        FollowUpReminder._open.append(w)
        self.win = w

        # A thicker border on the final one, so it reads differently even out
        # of the corner of your eye.
        pad = 6 if is_final else 3
        inner = tk.Frame(w, bg=C_TOAST_BG)
        inner.pack(fill="both", expand=True, padx=(pad, 0), pady=(pad, pad)
                   if is_final else 0)

        self.snooze = (item.get("kind") == "snooze")
        head = tk.Frame(inner, bg=C_TOAST_BG)
        head.pack(fill="x", padx=12, pady=(10, 0))
        tk.Label(head,
                 text=("⏰  Time to deal with this mail" if self.snooze
                       else "⚠  LAST REMINDER" if is_final
                       else "🔔  Still to do"),
                 bg=C_TOAST_BG,
                 fg=(C_FOLLOWUP if self.snooze
                     else C_FINAL_HEAD if is_final else C_FOLLOWUP),
                 font=("Segoe UI", 11 if is_final else 10, "bold")
                 ).pack(side="left")
        close = tk.Label(head, text="✕", bg=C_TOAST_BG, fg=C_FG_DIM,
                         font=("Segoe UI", 9), cursor="hand2")
        close.pack(side="right")
        close.bind("<Button-1>", lambda e: self.close())

        tk.Label(inner, text=(item.get("subject") or "(no subject)")[:60],
                 bg=C_TOAST_BG, fg=C_FG, font=("Segoe UI", 10, "bold"),
                 anchor="w", wraplength=340, justify="left"
                 ).pack(fill="x", padx=12, pady=(4, 0))
        tk.Label(inner, text=f"from {item.get('from_name', '')}"[:60],
                 bg=C_TOAST_BG, fg=C_FG_DIM, font=("Segoe UI", 8),
                 anchor="w").pack(fill="x", padx=12)
        if item.get("note"):
            tk.Label(inner, text="→ " + item["note"][:80], bg=C_TOAST_BG,
                     fg=C_ACCENT, font=("Segoe UI", 9), anchor="w",
                     wraplength=340, justify="left").pack(fill="x", padx=12,
                                                          pady=(4, 0))
        if self.snooze:
            due_txt = (item.get("first_at") or "")[:16].replace("T", " ")
            tk.Label(inner,
                     text=f"The reminder you set for {due_txt}. The mail "
                          f"itself is where it always was.",
                     bg=C_TOAST_BG, fg=C_FG_DIM, font=("Segoe UI", 8),
                     anchor="w", justify="left", wraplength=340
                     ).pack(fill="x", padx=12, pady=(4, 0))
        elif is_final:
            tk.Label(inner,
                     text=("This is the FINAL pop-up — the mail now stays "
                           "at the top of its folder until you press Done."
                           if item.get("float") else
                           "This is the FINAL reminder — you will not be "
                           "reminded about this message again."),
                     bg=C_TOAST_BG, fg=C_FINAL_HEAD,
                     font=("Segoe UI", 8, "bold"), anchor="w", justify="left",
                     wraplength=340).pack(fill="x", padx=12, pady=(6, 0))
        else:
            shown = int(item.get("fired_count") or 0) + 1
            mx    = int(item.get("max_count") or 0)
            tail  = f" of {mx}" if mx else ""
            tk.Label(inner,
                     text=f"reminder {shown}{tail}  ·  "
                          f"{_fmt_interval(item.get('repeat_min'))}",
                     bg=C_TOAST_BG, fg=C_FG_DIM, font=("Segoe UI", 8),
                     anchor="w").pack(fill="x", padx=12, pady=(4, 0))

        flt = bool(item.get("float"))      # a floating mail ends with Done
        btns = tk.Frame(inner, bg=C_TOAST_BG)
        btns.pack(fill="x", padx=10, pady=8)
        tk.Button(btns, text="Open", bg=C_BTN_NEW, fg=C_BTN_FG,
                  font=("Segoe UI", 8, "bold"), relief="flat", cursor="hand2",
                  padx=10, pady=3, command=self._open_msg).pack(side="left",
                                                                padx=2)
        if self.snooze:
            tk.Button(btns, text="Remind me again…", bg=C_BTN_LATER,
                      fg=C_BTN_FG, font=("Segoe UI", 8), relief="flat",
                      cursor="hand2", padx=10, pady=3,
                      command=self._again).pack(side="left", padx=2)
            tk.Button(btns, text="Done", bg=C_BTN_STD, fg=C_BTN_FG,
                      font=("Segoe UI", 8), relief="flat", cursor="hand2",
                      padx=10, pady=3, command=self.close
                      ).pack(side="right", padx=2)
        elif is_final:
            # On the last one, "stop" is meaningless — it is stopping anyway.
            # What you might actually want is to NOT let it end.
            tk.Button(btns, text="Keep reminding me", bg=C_BTN_LATER,
                      fg=C_BTN_FG, font=("Segoe UI", 8), relief="flat",
                      cursor="hand2", padx=10, pady=3,
                      command=self._keep_going).pack(side="left", padx=2)
            tk.Button(btns, text="✔ Done" if flt else "Done",
                      bg=C_BTN_NEW if flt else C_BTN_STD, fg=C_BTN_FG,
                      font=("Segoe UI", 8, "bold" if flt else "normal"),
                      relief="flat", cursor="hand2", padx=10, pady=3,
                      command=self._resolve if flt else self.close
                      ).pack(side="right", padx=2)
        else:
            tk.Button(btns, text="✔ Done" if flt else "Stop reminding",
                      bg=C_BTN_NEW if flt else C_BTN_DEL, fg=C_BTN_FG,
                      font=("Segoe UI", 8, "bold"), relief="flat",
                      cursor="hand2", padx=10, pady=3,
                      command=self._resolve if flt else self._stop
                      ).pack(side="right", padx=2)
            tk.Button(btns, text="Later", bg=C_BTN_STD, fg=C_BTN_FG,
                      font=("Segoe UI", 8), relief="flat", cursor="hand2",
                      padx=10, pady=3, command=self.close).pack(side="right",
                                                                padx=2)

    def _open_msg(self):
        self.app._open_followup_message(self.item)
        self.close()

    def _again(self):
        """Pick a new time for the same mail (e.g. "not yet - 2 weeks more")."""
        when = _ask_send_time(self.app.root, self.app.root, purpose="snooze")
        if when is None:
            return
        it = self.item
        self.app._snooze_message(
            {"account_email": it.get("account", ""),
             "_folder": it.get("folder", "") or "Inbox",
             "uid": it.get("uid") or "", "subject": it.get("subject", ""),
             "from": it.get("from", ""), "from_name": it.get("from_name", ""),
             "_key_override": it.get("key", "")}, when)
        self.close()

    def _stop(self):
        _followup_stop(self.app._followup_store, self.item.get("id", ""))
        self.app._flash("Stopped reminding about that message")
        self.close()

    def _keep_going(self):
        """Undo the ending: clear the limit and carry on until stopped."""
        self.app._followup_keep_going(self.item)
        self.close()

    def _resolve(self):
        """Done: no more reminders and the mail goes back to its place."""
        self.app._followup_resolve(self.item)
        self.close()

    def close(self):
        try:
            _corner_forget(self.win)
            if self.win in FollowUpReminder._open:
                FollowUpReminder._open.remove(self.win)
        except Exception:
            pass
        try:
            if self.win.winfo_exists():
                self.win.destroy()
        except Exception:
            pass


# ******************************************************************************
# DEL 06f — SEARCH WINDOW  (its own window, results as a folder tree)
# ******************************************************************************
#
# Issu 2026-08-08:
#
#   "Search mail… kanske bättre som fristående popup… som, i stället för att
#    lista alla mail i en katalog, där jag inte ser var de ligger, så en slags
#    kopia av mitt egentliga folder/account-system, men visar bara de kataloger
#    (och struktur) där det finns mail som matchar. Den kan vara så fristående
#    att jag kan jobba med huvudprogrammet i bakgrunden, samtidigt."
#
# So: a window of its own, never modal, and the results are not a flat list —
# they are YOUR folder tree with everything that has no hits left out. You see
# WHERE things are, which is usually the actual question ("where did that
# receipt end up?"), not merely that they exist somewhere.
#
# The rest of his list, all here:
#   • which parts to search — Subject / Sender / To-Cc / Message text, any
#     combination at once, each with its own colour, shown as chips on every
#     hit so you can see WHAT matched WHERE;
#   • exclude a hit (or a whole folder's worth) from the result — "lyx att
#     kunna exkludera funna Searched från funnenhet";
#   • Move, for when a search turns up something filed in the wrong place;
#   • Protect the folder you moved it INTO, so nothing automatic moves it out
#     again.
#
# Folders are searched one at a time and the tree fills in as each answers, so
# a five-account search shows its first results immediately rather than after
# everything has finished.

# ==============================================================================
# DEL 04e2 — THE MINI-MINI WEB VIEW  (Issu 2026-08-29)
# ==============================================================================
#
# "Ju smidigare desto bättre; kanske att det inte ens behöver öppna min
# webläsare utan Freemail kan ha en mini-mini-webläsare som bara öppnas för att
# gå till avregistrerasidor e.d."
#
# The window. The machinery it stands on (_web_fetch, _page_forms,
# _form_request) is up in DEL 04e; what is here is the part you look at:
#
#   • The address is on screen the whole time, host first and in its own
#     colour, because "is this really the shop's own domain?" is the one
#     question that matters on a page you reached from an e-mail.
#   • Every redirect hop is listed. An unsubscribe link is nearly always a
#     tracking URL that bounces somewhere else, and where it LANDS is what you
#     are actually talking to.
#   • Forms become real Tk widgets. Nothing is filled in for you except the
#     address the newsletter was sent to, which is offered — visibly, in the
#     field, editable and clearable — because every unsubscribe page on earth
#     asks for it and typing it again is the friction this window exists to
#     remove.
#   • Nothing is ever sent until you press a button, and "Show exactly what
#     will be sent" prints the literal name=value pairs first.
#   • Fetching happens on a worker thread; the window stays alive, and a slow
#     or hung site is closed with Escape like anything else.

class MiniWebWindow(tk.Toplevel):
    """A throwaway browser just big enough to finish an unsubscribe."""

    def __init__(self, app, url, title="Unsubscribe page", msg=None,
                 prefill_email="", on_done=None):
        super().__init__(app.root)
        self.app  = app
        self.msg  = msg or {}
        self.on_done = on_done
        self.prefill_email = (prefill_email
                              or self.msg.get("account_email", "") or "")
        # One jar, one opener, one redirect log — created here and thrown away
        # with the window, so nothing this page sets can follow you anywhere.
        self.opener, self.jar, self._red = _web_opener()
        self.history = []
        self.cur = {}
        self._busy = False
        self._result = None       # the worker thread drops the page here

        self.title(f"{title} — F(re)email  (mini view)")
        self.configure(bg=C_BG3)
        _center_over(self, app.root, 860, 680)
        self.transient(app.root)
        self.bind("<Escape>", lambda e: self.destroy())

        # ── Address bar ──────────────────────────────────────────────────
        bar = tk.Frame(self, bg=C_BG1, padx=8, pady=5)
        bar.pack(fill="x")
        self.b_back = tk.Button(bar, text="◀", bg=C_BTN_STD, fg=C_BTN_FG,
                                relief="flat", cursor="hand2", padx=8,
                                font=("Segoe UI", 9), state="disabled",
                                command=self._back)
        self.b_back.pack(side="left")
        self.lbl_host = tk.Label(bar, text="", bg=C_BG1, fg=C_ACCENT,
                                 font=("Segoe UI", 10, "bold"), anchor="w")
        self.lbl_host.pack(side="left", padx=(8, 0))
        tk.Button(bar, text="🌐 Open in my real browser", bg=C_BTN_STD,
                  fg=C_BTN_FG, relief="flat", cursor="hand2", padx=10,
                  font=("Segoe UI", 8), command=self._open_real
                  ).pack(side="right")
        tk.Button(bar, text="📋 Copy address", bg=C_BTN_STD, fg=C_BTN_FG,
                  relief="flat", cursor="hand2", padx=10,
                  font=("Segoe UI", 8),
                  command=lambda: self.app._copy_to_clipboard(
                      self.cur.get("url", ""), "Address copied")
                  ).pack(side="right", padx=(0, 6))

        # pady goes on the PACK call, never on the widget: a (0, 6) tuple is
        # fine for pack/grid and a TclError as a widget option.
        urlbar = tk.Frame(self, bg=C_BG1, padx=8)
        urlbar.pack(fill="x", pady=(0, 6))
        self.e_url = tk.Entry(urlbar, bg=C_BG2, fg=C_FG_DIM, relief="flat",
                              font=("Consolas", 8), insertofftime=0,
                              insertontime=9999999)
        no_blink(self.e_url)
        self.e_url.pack(fill="x", ipady=2)
        add_tooltip(self.e_url, "The address this window is actually showing, "
                                "after every redirect. Selectable — you can "
                                "copy it.")

        self.lbl_status = tk.Label(self, text="", bg=C_BG3, fg=C_FG_DIM,
                                   font=("Segoe UI", 8), anchor="w", padx=10)
        self.lbl_status.pack(fill="x")

        # ── Page ─────────────────────────────────────────────────────────
        wrap = tk.Frame(self, bg=C_BG2)
        wrap.pack(fill="both", expand=True, padx=10, pady=(4, 0))
        # Scrollbar packed BEFORE the expanding canvas, or it renders 1px wide.
        sb = tk.Scrollbar(wrap, bg=C_BG3, troughcolor=C_BG1)
        sb.pack(side="right", fill="y")
        self.canvas = tk.Canvas(wrap, bg=C_BG2, highlightthickness=0)
        self.canvas.pack(side="left", fill="both", expand=True)
        sb.configure(command=self.canvas.yview)
        self.canvas.configure(yscrollcommand=sb.set)
        self.inner = tk.Frame(self.canvas, bg=C_BG2)
        self._win = self.canvas.create_window((0, 0), window=self.inner,
                                              anchor="nw")
        self.inner.bind("<Configure>", lambda e: self.canvas.configure(
            scrollregion=self.canvas.bbox("all")))
        self.canvas.bind("<Configure>", lambda e: self.canvas.itemconfig(
            self._win, width=e.width))
        _bind_mousewheel(self.inner, self.canvas)

        foot = tk.Frame(self, bg=C_BG3, pady=8)
        foot.pack(fill="x")
        tk.Label(foot,
                 text="No JavaScript, no images, no cookies kept — this window "
                      "sends nothing until you press one of the page's own "
                      "buttons.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 padx=10).pack(side="left")
        tk.Button(foot, text="Close", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=16, pady=3, command=self.destroy).pack(side="right",
                                                              padx=10)
        self.b_done = tk.Button(foot, text="✔ Done — I am unsubscribed",
                                bg=C_BTN_NEW, fg=C_BTN_FG,
                                font=("Segoe UI", 9, "bold"), relief="flat",
                                cursor="hand2", padx=14, pady=3,
                                command=self._mark_done)
        self.b_done.pack(side="right")
        add_tooltip(self.b_done,
                    "Writes this down in the unsubscribe log, so a rule never "
                    "offers to unsubscribe from this list again.")

        self.go(url)

    # ── navigation ───────────────────────────────────────────────────────
    def go(self, url, data=None, method=None, push=True):
        if self._busy:
            return
        if push and self.cur.get("url"):
            self.history.append(self.cur["url"])
            self.b_back.configure(state="normal")
        self._busy = True
        self._set_status("Loading…  " + (url or "")[:90])
        self._clear()
        tk.Label(self.inner, text="⏳  Loading…", bg=C_BG2, fg=C_FG_DIM,
                 font=("Segoe UI", 10), pady=20).pack()

        # The worker hands the page back through a plain attribute and the
        # MAIN thread picks it up on a timer — deliberately not the
        # `self.after(0, …)`-from-the-worker shape used elsewhere in this
        # program. That shape only works while the main thread is inside
        # mainloop(); anywhere else Tk raises "main thread is not in main
        # loop", and the except-clause you would wrap it in swallows the one
        # symptom, leaving a window that says "Loading…" for ever with nothing
        # in the log. Polling cannot fail that way, costs one 80 ms timer, and
        # is what makes this window drivable by a test.
        self._result = None

        def _work():
            res = _web_fetch(url, opener=self.opener, data=data, method=method)
            self._result = res

        threading.Thread(target=_work, daemon=True).start()
        self._poll()

    def _poll(self):
        if not self.winfo_exists():
            return
        res, self._result = self._result, None
        if res is not None:
            self._show(res)
            return
        self.after(80, self._poll)

    def _back(self):
        if not self.history:
            return
        url = self.history.pop()
        if not self.history:
            self.b_back.configure(state="disabled")
        self.go(url, push=False)

    def _open_real(self):
        u = self.cur.get("url") or ""
        if u:
            self.app._open_url(u, msg=self.msg)

    def _set_status(self, text, warn=False):
        try:
            self.lbl_status.configure(text=text,
                                      fg=("#ffb0b0" if warn else C_FG_DIM))
        except Exception:
            pass

    def _clear(self):
        for w in self.inner.winfo_children():
            w.destroy()

    # ── rendering ────────────────────────────────────────────────────────
    def _show(self, res):
        self._busy = False
        if not self.winfo_exists():
            return
        self.cur = res
        url = res.get("url") or ""
        parts = _urlparse.urlsplit(url)
        host, scheme = parts.netloc or "?", parts.scheme
        self.lbl_host.configure(
            text=("🔒  " if scheme == "https" else "⚠ not encrypted  ") + host,
            fg=(C_ACCENT if scheme == "https" else "#ffb0b0"))
        self.e_url.configure(state="normal")
        self.e_url.delete(0, "end")
        self.e_url.insert(0, url)
        self.e_url.configure(state="readonly", readonlybackground=C_BG2)
        self._clear()

        if res.get("error"):
            self._set_status(res["error"], warn=True)
        else:
            self._set_status(f"HTTP {res.get('status', 0)}   ·   "
                             f"{len(res.get('text') or '')} characters of text")

        # Where it actually went. A tracking hop is normal; a hop to a domain
        # that has nothing to do with the sender is worth seeing.
        hops = res.get("hops") or []
        if hops:
            box = tk.Frame(self.inner, bg=C_BG3, padx=10, pady=6)
            box.pack(fill="x", pady=(6, 4), padx=6)
            tk.Label(box, text=f"↪  followed {len(hops)} redirect"
                               f"{'s' if len(hops) > 1 else ''} to get here:",
                     bg=C_BG3, fg="#ffd08a", font=("Segoe UI", 8, "bold"),
                     anchor="w").pack(fill="x")
            for h in hops:
                tk.Label(box, text="     " + h[:110]
                                   + ("…" if len(h) > 110 else ""),
                         bg=C_BG3, fg=C_FG_DIM, font=("Consolas", 7),
                         anchor="w", justify="left").pack(fill="x")

        if res.get("error") and not (res.get("text") or "").strip():
            self._render_dead_end(res)
            return

        # ── the page's own words ─────────────────────────────────────────
        text = (res.get("text") or "").strip() or "(this page has no text)"
        t = tk.Text(self.inner, bg=C_BG2, fg=C_FG, relief="flat", wrap="word",
                    font=("Segoe UI", 10), padx=12, pady=10,
                    height=max(4, min(22, text.count("\n") + 3)),
                    insertofftime=0, insertontime=9999999)
        no_blink(t)
        t.insert("1.0", text)
        t.configure(state="disabled")
        t.pack(fill="x")

        forms, links = _page_forms(res.get("html") or "", url)
        for i, f in enumerate(forms):
            self._render_form(f, i)

        if not forms:
            self._render_no_form(links)
        else:
            self._render_links(links, compact=True)

    def _render_dead_end(self, res):
        box = tk.Frame(self.inner, bg=C_BG2, padx=14, pady=14)
        box.pack(fill="x")
        tk.Label(box, text="This page could not be shown here.",
                 bg=C_BG2, fg=C_FG, font=("Segoe UI", 11, "bold"),
                 anchor="w").pack(fill="x")
        tk.Label(box, text=res.get("error", ""), bg=C_BG2, fg=C_FG_DIM,
                 font=("Segoe UI", 9), anchor="w", justify="left",
                 wraplength=760).pack(fill="x", pady=(4, 10))
        tk.Label(box,
                 text="A page that needs JavaScript, or a site that refuses "
                      "anything but a full browser, is exactly what the button "
                      "below is for. Nothing has been sent.",
                 bg=C_BG2, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 anchor="w", justify="left", wraplength=760).pack(fill="x")
        tk.Button(box, text="🌐  Open this address in my real browser",
                  bg=C_BTN_NEW, fg=C_BTN_FG, font=("Segoe UI", 9, "bold"),
                  relief="flat", cursor="hand2", padx=14, pady=5,
                  command=self._open_real).pack(anchor="w", pady=(10, 0))

    def _render_no_form(self, links):
        """No form on the page. Either it is already done, or the button is
        JavaScript — say which is which instead of leaving a blank."""
        box = tk.Frame(self.inner, bg=C_BG3, padx=14, pady=10)
        box.pack(fill="x", pady=(8, 4), padx=6)
        tk.Label(box, text="There is no form on this page to fill in.",
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 9, "bold"),
                 anchor="w").pack(fill="x")
        tk.Label(box,
                 text="If the text above says you have been unsubscribed, you "
                      "are done — press “Done” below. If it shows a button "
                      "that is not here, that button is JavaScript and needs "
                      "the real browser.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w",
                 justify="left", wraplength=760).pack(fill="x", pady=(2, 0))
        self._render_links(links, compact=False)

    def _render_links(self, links, compact):
        if not links:
            return
        interesting = [(u, t) for u, t in links
                       if _UNSUB_URL_RE.search(
                           _urlparse.urlsplit(u).path + "?"
                           + (_urlparse.urlsplit(u).query or ""))
                       or _UNSUB_WORD_RE.search(t or "")]
        show = interesting if (compact and interesting) else links[:20]
        if not show:
            return
        box = tk.Frame(self.inner, bg=C_BG2, padx=12, pady=8)
        box.pack(fill="x")
        tk.Label(box,
                 text=("Unsubscribe-looking links on this page:"
                       if (interesting and compact) else "Links on this page:"),
                 bg=C_BG2, fg=C_FG_DIM, font=("Segoe UI", 8, "bold"),
                 anchor="w").pack(fill="x")
        for u, txt in show[:20]:
            row = tk.Frame(box, bg=C_BG2)
            row.pack(fill="x")
            lnk = tk.Label(row, text="  ▸ " + (txt or u)[:70], bg=C_BG2,
                           fg=C_ACCENT, font=("Segoe UI", 9, "underline"),
                           cursor="hand2", anchor="w")
            lnk.pack(side="left")
            lnk.bind("<Button-1>", lambda e, x=u: self.go(x))
            tk.Label(row, text="  " + u[:60] + ("…" if len(u) > 60 else ""),
                     bg=C_BG2, fg=C_FG_DIM, font=("Consolas", 7),
                     anchor="w").pack(side="left")

    def _render_form(self, form, idx):
        """One <form> as real widgets. Hidden fields are carried but listed."""
        box = tk.Frame(self.inner, bg=C_BG3, padx=14, pady=10)
        box.pack(fill="x", pady=(10, 4), padx=6)
        tk.Label(box,
                 text=f"📝  Form {idx + 1}   ({form['method'].upper()} → "
                      f"{_urlparse.urlsplit(form['action']).netloc})",
                 bg=C_BG3, fg=C_ACCENT, font=("Segoe UI", 9, "bold"),
                 anchor="w").pack(fill="x")

        getters = {}          # field index → callable returning value or None
        radios  = {}          # radio group name → StringVar
        hidden  = []
        shown   = 0
        for i, fld in enumerate(form["fields"]):
            kind = fld["kind"]
            if kind == "hidden":
                hidden.append(fld)
                getters[i] = (lambda f=fld: f.get("value", ""))
                continue
            if shown >= _FORM_MAX_FIELDS:
                continue
            shown += 1
            row = tk.Frame(box, bg=C_BG3)
            row.pack(fill="x", pady=2)
            cap = (fld.get("label") or fld.get("name") or "")[:46]

            if kind == "checkbox":
                var = tk.BooleanVar(value=fld.get("checked", False))
                tk.Checkbutton(row, text=cap or fld.get("name", ""),
                               variable=var, bg=C_BG3, fg=C_FG,
                               selectcolor=C_BG2, activebackground=C_BG3,
                               activeforeground=C_FG, font=("Segoe UI", 9),
                               highlightthickness=0, anchor="w",
                               wraplength=700, justify="left").pack(fill="x")
                getters[i] = (lambda v=var, f=fld:
                              (f.get("value") or "on") if v.get() else None)
            elif kind == "radio":
                name = fld.get("name", "")
                if name not in radios:
                    radios[name] = tk.StringVar(value="")
                var = radios[name]
                if fld.get("checked"):
                    var.set(fld.get("value", ""))
                tk.Radiobutton(row, text=cap or fld.get("value", ""),
                               value=fld.get("value", ""), variable=var,
                               bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                               activebackground=C_BG3, activeforeground=C_FG,
                               font=("Segoe UI", 9), highlightthickness=0,
                               anchor="w", wraplength=700,
                               justify="left").pack(fill="x")
                getters[i] = (lambda v=var, f=fld:
                              f.get("value", "")
                              if v.get() == f.get("value", "") else None)
            elif kind == "select":
                tk.Label(row, text=cap + ":", bg=C_BG3, fg=C_FG_DIM,
                         font=("Segoe UI", 9), anchor="w",
                         width=22).pack(side="left")
                labels = [(o[1] or o[0] or "")[:60] for o in fld["options"]] \
                    or ["(no choices)"]
                var = tk.StringVar(value=labels[0])
                for o, lb in zip(fld["options"], labels):
                    if o[2]:
                        var.set(lb)
                om = tk.OptionMenu(row, var, *labels)
                om.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                             activeforeground=C_FG, highlightthickness=0,
                             relief="flat", font=("Segoe UI", 9), anchor="w")
                om["menu"].configure(bg=C_BG2, fg=C_FG,
                                     activebackground=C_BG4,
                                     activeforeground=C_FG)
                om.pack(side="left", fill="x", expand=True)
                pairs = list(zip(labels, [o[0] for o in fld["options"]]))
                getters[i] = (lambda v=var, p=pairs:
                              next((val for lb, val in p if lb == v.get()), ""))
            elif kind == "textarea":
                tk.Label(row, text=cap + ":", bg=C_BG3, fg=C_FG_DIM,
                         font=("Segoe UI", 9), anchor="w").pack(fill="x")
                tw = tk.Text(row, bg=C_BG2, fg=C_FG, relief="flat", height=3,
                             font=("Segoe UI", 9), insertbackground=C_ACCENT,
                             insertofftime=0, insertontime=9999999)
                no_blink(tw)
                tw.insert("1.0", (fld.get("value") or "").strip())
                tw.pack(fill="x")
                getters[i] = (lambda w=tw: w.get("1.0", "end-1c"))
            elif kind == "password":
                # A PASSWORD IS NEVER TYPED IN THIS WINDOW. An unsubscribe page
                # has no business asking for one, and a hand-written form
                # renderer with no certificate UI, no password manager and no
                # phishing protection is the last place to put one. The field
                # is shown so you can see what the page asked for, and it is
                # dead: nothing can be typed into it and nothing is submitted
                # for it. Signing in is a job for the real browser.
                shown -= 1        # not a field you can fill in
                tk.Label(row, text=cap + ":", bg=C_BG3, fg="#ffb0b0",
                         font=("Segoe UI", 9), anchor="e",
                         width=22).pack(side="left")
                dead = tk.Entry(row, bg=C_BG1, fg=C_FG_DIM, relief="flat",
                                font=("Segoe UI", 10), show="*")
                dead.insert(0, "not available here")
                dead.configure(state="disabled")
                dead.pack(side="left", fill="x", expand=True, ipady=2)
                tk.Label(box,
                         text="   ⚠  This form asks for a PASSWORD, so it is "
                              "not an unsubscribe page — it is a sign-in. "
                              "F(re)email will not take a password: open the "
                              "site in your real browser if you mean to log "
                              "in, and be sure it is really the sender's own "
                              "domain first.",
                         bg=C_BG3, fg="#ffb0b0", font=("Segoe UI", 8, "bold"),
                         anchor="w", justify="left",
                         wraplength=740).pack(fill="x")
                getters[i] = (lambda: None)     # never submitted
                continue
            else:
                tk.Label(row, text=cap + ":", bg=C_BG3, fg=C_FG_DIM,
                         font=("Segoe UI", 9), anchor="e",
                         width=22).pack(side="left")
                e = tk.Entry(row, bg=C_BG2, fg=C_FG, relief="flat",
                             font=("Segoe UI", 10), insertbackground=C_ACCENT,
                             insertofftime=0, insertontime=9999999)
                no_blink(e)
                e.pack(side="left", fill="x", expand=True, ipady=2)
                val = fld.get("value", "")
                # The ONE thing filled in for you: the address this newsletter
                # was sent to, in an empty field that is asking for an address.
                # Visible and editable — nothing is typed in behind your back,
                # and a password field is never touched.
                if (not val and self.prefill_email
                        and self._looks_like_email_field(fld)):
                    val = self.prefill_email
                    e.configure(fg="#a8e6a8")
                    add_tooltip(e, "Filled in for you: the address this "
                                   "newsletter was sent to. Change or clear "
                                   "it if it is wrong.")
                e.insert(0, val)
                getters[i] = (lambda w=e: w.get())

        if hidden:
            tk.Label(box, text=f"   + {len(hidden)} hidden field"
                              f"{'s' if len(hidden) > 1 else ''} the page "
                              f"filled in itself (a token, usually) — listed "
                              f"under “what will be sent”",
                     bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 7, "italic"),
                     anchor="w", justify="left",
                     wraplength=740).pack(fill="x", pady=(4, 0))

        # ── the buttons, and the "show me first" line ────────────────────
        brow = tk.Frame(box, bg=C_BG3)
        brow.pack(fill="x", pady=(8, 0))
        for sub in form["submits"][:4]:
            tk.Button(brow, text="▶  " + (sub.get("label") or "Send")[:34],
                      bg=C_BTN_NEW, fg=C_BTN_FG,
                      font=("Segoe UI", 9, "bold"), relief="flat",
                      cursor="hand2", padx=14, pady=4,
                      command=lambda s=sub, f=form, g=getters:
                          self._submit(f, g, s)).pack(side="left", padx=(0, 6))
        peek = tk.Label(brow, text="🔍 Show exactly what will be sent",
                        bg=C_BG3, fg=C_ACCENT, cursor="hand2",
                        font=("Segoe UI", 8, "underline"))
        peek.pack(side="left", padx=(10, 0))
        peek.bind("<Button-1>",
                  lambda e, f=form, g=getters: self._peek(f, g))

    @staticmethod
    def _looks_like_email_field(fld) -> bool:
        if (fld.get("kind") or "") == "email":
            return True
        hay = ((fld.get("name") or "") + " " + (fld.get("label") or "")).lower()
        return bool(_re.search(r"e-?mail|e-?post|adress|address", hay))

    def _values(self, form, getters):
        vals = {}
        for i in range(len(form["fields"])):
            g = getters.get(i)
            if g is None:
                continue
            try:
                vals[i] = g()
            except Exception:
                vals[i] = form["fields"][i].get("value", "")
        return vals

    def _peek(self, form, getters):
        url, _data, pairs = _form_request(form, self._values(form, getters),
                                          form["submits"][0])
        lines = "\n".join(f"   {k} = {v}" for k, v in pairs) or "   (nothing)"
        messagebox.showinfo(
            "What this form will send",
            f"{form['method'].upper()}  {url}\n\n{lines}\n\n"
            f"Nothing has been sent — this is only a preview.", parent=self)

    def _submit(self, form, getters, submit):
        vals = self._values(form, getters)
        missing = [f.get("label") or f.get("name")
                   for i, f in enumerate(form["fields"])
                   if f.get("required") and not (vals.get(i) or "")
                   and f["kind"] not in ("checkbox", "radio", "hidden")]
        if missing and not messagebox.askyesno(
                "Send anyway?",
                "The page marks these as required and they are empty:\n\n  "
                + "\n  ".join(str(x) for x in missing[:6])
                + "\n\nSend it anyway?", parent=self):
            return
        url, data, _pairs = _form_request(form, vals, submit)
        self.go(url, data=data, method=("POST" if data is not None else None))

    def _mark_done(self):
        """Write this unsubscribe into the log and close."""
        try:
            self.app._record_unsubscribe(
                self.msg, route="mini-browser",
                url=self.cur.get("url", ""), result="confirmed by hand")
        except Exception as e:
            log.warning("could not record the unsubscribe: %s", e)
        cb = self.on_done
        self.destroy()
        if cb:
            try:
                cb()
            except Exception:
                pass


class SearchWindow:
    """Search across every folder of every account, shown as a folder tree."""

    def __init__(self, app):
        self.app  = app
        self.root = app.root
        self.cfg  = app.cfg
        self._hits = {}          # (account, folder) -> [msg, …]
        self._excluded = set()   # _reply_key of hits the user set aside
        self._open = set()       # (account, folder) rows expanded
        self._token = None       # identity of the running search
        self._running = False

        top = tk.Toplevel(self.root)
        top.title("Search mail — F(re)email")
        top.configure(bg=C_BG3)
        top.minsize(760, 520)
        _center_over(top, self.root, 1000, 720)
        # NOT modal and NOT transient — the whole point is being able to work
        # in the main window while this stands open beside it.
        top.focus_force()
        top.bind("<Escape>", lambda e: self._to_background())
        top.protocol("WM_DELETE_WINDOW", self.close)
        self.top = top
        self._build(top)

    # ── Layout ───────────────────────────────────────────────────────────────
    def _build(self, top):
        bar = tk.Frame(top, bg=C_BG1, pady=6)
        bar.pack(fill="x")
        tk.Label(bar, text="🔍", bg=C_BG1, fg=C_ACCENT,
                 font=("Segoe UI", 13)).pack(side="left", padx=(10, 4))
        self.e_query = tk.Entry(bar, bg=C_BG2, fg=C_FG, relief="flat",
                                insertbackground=C_ACCENT,
                                font=("Segoe UI", 11),
                                insertofftime=0, insertontime=9999999)
        no_blink(self.e_query)
        self.e_query.pack(side="left", fill="x", expand=True, ipady=4, padx=4)
        self.e_query.bind("<Return>", lambda e: self.run())
        self.b_go = tk.Button(bar, text="Search", bg=C_BTN_NEW, fg=C_BTN_FG,
                              font=("Segoe UI", 9, "bold"), relief="flat",
                              cursor="hand2", padx=14, pady=3,
                              command=self.run)
        self.b_go.pack(side="left", padx=4)
        self.b_stop = tk.Button(bar, text="Stop", bg=C_BTN_STD, fg=C_BTN_FG,
                                font=("Segoe UI", 9), relief="flat",
                                cursor="hand2", padx=10, pady=3,
                                command=self.stop)
        self.b_stop.pack(side="left", padx=(0, 10))

        # ── Which parts of a message to look in ──────────────────────────────
        where = tk.Frame(top, bg=C_BG3, padx=10, pady=4)
        where.pack(fill="x")
        tk.Label(where, text="Look in:", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left", padx=(0, 6))
        saved = self.cfg.get("search_fields") or ["subject", "from", "body"]
        self._field_vars = {}
        for f in _SEARCH_FIELDS:
            v = tk.BooleanVar(value=(f in saved))
            self._field_vars[f] = v
            cb = tk.Checkbutton(
                where, text=_SEARCH_FIELD_LABELS[f], variable=v,
                bg=C_BG3, fg=_SEARCH_FIELD_COLOURS[f], selectcolor=C_BG2,
                activebackground=C_BG3,
                activeforeground=_SEARCH_FIELD_COLOURS[f],
                font=("Segoe UI", 9, "bold"), highlightthickness=0,
                relief="flat", anchor="w")
            cb.pack(side="left", padx=4)
            add_tooltip(cb, f"Search the {_SEARCH_FIELD_LABELS[f].lower()}. "
                            f"Hits found there are marked in this colour, so "
                            f"you can see at a glance what matched where. "
                            f"Tick as many as you like.")
        tk.Label(where, text="│", bg=C_BG3, fg=C_SEP).pack(side="left", padx=6)
        self._scope_all = tk.BooleanVar(
            value=bool(self.cfg.get("search_all_accounts", True)))
        cb2 = tk.Checkbutton(where, text="Every account", variable=self._scope_all,
                             bg=C_BG3, fg=C_FG_DIM, selectcolor=C_BG2,
                             activebackground=C_BG3, activeforeground=C_FG,
                             font=("Segoe UI", 9), highlightthickness=0,
                             relief="flat")
        cb2.pack(side="left")
        add_tooltip(cb2, "Off: only the account you are looking at in the main "
                         "window.")
        self._inc_trash = tk.BooleanVar(
            value=bool(self.cfg.get("search_include_trash", True)))
        cb3 = tk.Checkbutton(where, text="Trash & Spam too",
                             variable=self._inc_trash,
                             bg=C_BG3, fg=C_FG_DIM, selectcolor=C_BG2,
                             activebackground=C_BG3, activeforeground=C_FG,
                             font=("Segoe UI", 9), highlightthickness=0,
                             relief="flat")
        cb3.pack(side="left", padx=8)
        # The same leave-out list the "All except…" scope uses (Issu
        # 2026-08-17). On by default and free while the list is empty; the
        # button next to it is how you fill it in without hunting for the menu.
        self._skip_excluded = tk.BooleanVar(
            value=bool(self.cfg.get("search_window_skip_excluded", True)))
        cb4 = tk.Checkbutton(where, text="Skip what I left out",
                             variable=self._skip_excluded,
                             bg=C_BG3, fg=C_FG_DIM, selectcolor=C_BG2,
                             activebackground=C_BG3, activeforeground=C_FG,
                             font=("Segoe UI", 9), highlightthickness=0,
                             relief="flat")
        cb4.pack(side="left")
        add_tooltip(cb4, "Leave out the folders and accounts named in "
                         "“Search: what to leave out…” — the same list the "
                         "“All except…” scope uses. Untick to search "
                         "absolutely everything this once.")
        b_ex = tk.Button(where, text="⚙ Choose…", bg=C_BTN_STD, fg=C_BTN_FG,
                         font=("Segoe UI", 8), relief="flat", cursor="hand2",
                         padx=6, pady=1,
                         command=lambda: self.app._search_exclude_dialog(
                             parent=self.top))
        b_ex.pack(side="left", padx=(4, 0))
        add_tooltip(b_ex, "Pick the folders — or whole accounts — that "
                          "searching should leave alone.")

        self.lbl_status = tk.Label(top, text="", bg=C_BG3, fg=C_FG_DIM,
                                   font=("Segoe UI", 8, "italic"),
                                   anchor="w", padx=12, pady=3)
        self.lbl_status.pack(fill="x")

        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x")

        # ── The tree of hits ─────────────────────────────────────────────────
        body = tk.Frame(top, bg=C_BG2)
        body.pack(fill="both", expand=True)
        sb = tk.Scrollbar(body, orient="vertical", bg=C_BG3, troughcolor=C_BG1)
        sb.pack(side="right", fill="y")          # BEFORE the canvas — a
        self.canvas = tk.Canvas(body, bg=C_BG2, highlightthickness=0,
                                yscrollcommand=sb.set)
        self.canvas.pack(fill="both", expand=True)
        sb.configure(command=self.canvas.yview)
        self.inner = tk.Frame(self.canvas, bg=C_BG2)
        self._cwin = self.canvas.create_window((0, 0), window=self.inner,
                                               anchor="nw")
        self.inner.bind("<Configure>",
                        lambda e: self.canvas.configure(
                            scrollregion=self.canvas.bbox("all")))
        self.canvas.bind("<Configure>",
                         lambda e: self.canvas.itemconfig(self._cwin,
                                                          width=e.width))
        _bind_mousewheel(self.inner, self.canvas)

        # ── Buttons for whatever is selected ─────────────────────────────────
        btm = tk.Frame(top, bg=C_BG1, pady=5)
        btm.pack(fill="x")
        self._sel = None            # the message row currently picked
        self._sel_key = None
        self.lbl_sel = tk.Label(btm, text="Nothing picked", bg=C_BG1,
                                fg=C_FG_DIM, font=("Segoe UI", 8),
                                anchor="w")
        self.lbl_sel.pack(side="left", padx=10, fill="x", expand=True)
        for text, colour, cmd, tip in (
                ("📂 Open it", C_BTN_NEW, self._open_selected,
                 "Show this message in the main window, in the folder it "
                 "actually lives in."),
                ("📁 Move to…", "#3a6a8a", self._move_selected,
                 "Move it to another folder — for when a search turns up "
                 "something filed in the wrong place."),
                ("🔒 Protect that folder", C_BTN_STD, self._protect_selected,
                 "Protect the folder this message is in, so no rule can move "
                 "it out again."),
                ("✕ Exclude", C_BTN_STD, self._exclude_selected,
                 "Take this hit out of the results. It is not touched in any "
                 "way — it just stops cluttering what you are looking at."),
                ("↺ Bring back all", C_BTN_STD, self._unexclude_all,
                 "Put every excluded hit back into the results."),
                ("Close", C_BTN_STD, self.close, None)):
            b = tk.Button(btm, text=text, bg=colour, fg=C_BTN_FG,
                          font=("Segoe UI", 8), relief="flat", cursor="hand2",
                          padx=8, pady=3, command=cmd)
            b.pack(side="left", padx=3)
            if tip:
                add_tooltip(b, tip)

        self.e_query.focus_set()
        self._render()

    # ── Running a search ─────────────────────────────────────────────────────
    def _chosen_fields(self):
        return [f for f in _SEARCH_FIELDS if self._field_vars[f].get()]

    def run(self):
        query = self.e_query.get().strip()
        if not query:
            return
        fields = self._chosen_fields()
        if not fields:
            messagebox.showinfo("Search",
                                "Tick at least one thing to look in "
                                "(Subject, Sender, To/Cc, Message text).",
                                parent=self.top)
            return
        # Remember the choices — they are a preference, not a one-off.
        self.cfg["search_fields"] = fields
        self.cfg["search_all_accounts"] = bool(self._scope_all.get())
        self.cfg["search_include_trash"] = bool(self._inc_trash.get())
        self.cfg["search_window_skip_excluded"] = bool(
            self._skip_excluded.get())
        try:
            _save_settings(self.cfg)
        except Exception:
            pass

        if self.app._demo_mode:
            messagebox.showinfo("Search",
                                "No account is set up yet, so there is nothing "
                                "to search.", parent=self.top)
            return

        self._hits = {}
        self._excluded = set()
        self._sel = None
        self._sel_key = None
        token = object()
        self._token = token
        self._running = True
        self._render()

        accounts = [a for a in self.app._accounts if not a.get("virtual")]
        if not self._scope_all.get():
            cur = self.app._current_acct
            accounts = [a for a in accounts if a.get("email") == cur] or accounts
        # Read every Tk variable on the main thread (see the note further down)
        # — this one also decides which accounts exist at all.
        skip_excluded = bool(self._skip_excluded.get())
        if skip_excluded:
            kept = [a for a in accounts
                    if not _search_account_skipped(self.cfg,
                                                   a.get("email", ""))]
            if not kept:
                messagebox.showinfo(
                    "Search",
                    "Every account you asked for is on the leave-out list, so "
                    "there is nothing to search.\n\nUntick “Skip what I left "
                    "out”, or change the list with ⚙ Choose….",
                    parent=self.top)
                self._running = False
                self._render()
                return
            accounts = kept

        def stop():
            return self._token is not token or not self._running

        # Read every Tk variable HERE, on the main thread, and pass plain
        # Python values into the workers.
        #
        # A Tk variable read from another thread raises "main thread is not in
        # main loop" — and because the worker's own try/except swallows it, the
        # search would simply come back empty with nothing to show why. Caught
        # by the test rather than by Issu, which is the whole point of having
        # one.
        include_trash = bool(self._inc_trash.get())

        def folders_for(email):
            std = ["Inbox", "Sent", "Drafts", "Starred"]
            if include_trash:
                std += ["Spam", "Trash"]
            customs = [uf["mailbox"]
                       for uf in self.app._user_folders.get(email, [])]
            folders = std + customs
            if skip_excluded:
                folders = _search_keep_folders(self.cfg, email, folders)
            return folders

        total = {"folders": 0, "done": 0}
        for a in accounts:
            total["folders"] += len(folders_for(a["email"]))

        def one_account(a):
            email = a["email"]
            pwd = self.app._secret_for(email)
            if not pwd:
                return

            def on_folder(folder, msgs):
                def apply():
                    if stop():
                        return
                    total["done"] += 1
                    if msgs:
                        self._hits[(email, folder)] = msgs
                        # A folder that answers gets opened, so new results are
                        # visible rather than hidden behind a twisty.
                        self._open.add((email, folder))
                    self._render()
                try:
                    self.root.after(0, apply)
                except Exception:
                    pass

            try:
                _search_account_by_field(
                    email, pwd, query, fields, folders_for(email),
                    on_folder=on_folder, stop=stop)
            except Exception as e:
                log.warning("Search failed for %s: %s", email, e)

        def worker():
            threads = [threading.Thread(target=one_account, args=(a,),
                                        daemon=True) for a in accounts]
            for t in threads:
                t.start()
            for t in threads:
                t.join(timeout=300)

            def finished():
                if self._token is token:
                    self._running = False
                    self._render()
            try:
                self.root.after(0, finished)
            except Exception:
                pass

        self._total = total
        self._query = query
        threading.Thread(target=worker, daemon=True).start()

    def stop(self):
        """Give up on a search that is taking too long. What has been found so
        far stays on screen — it is still perfectly good."""
        if self._running:
            self._running = False
            self._render()

    # ── Drawing the tree ─────────────────────────────────────────────────────
    @staticmethod
    def _hit_key(msg):
        """Identity of ONE ROW in this tree.

        Deliberately account + folder + message, not the message alone: on
        Gmail one message carries several labels, so the same mail legitimately
        appears under Inbox and under a label. Excluding the row you clicked
        should hide THAT row — hiding it everywhere at once, from a click on
        one of them, is the kind of surprise that makes you stop trusting a
        button. "✕ exclude these" on a folder handles the bulk case."""
        return (msg.get("account_email", ""), msg.get("_folder", ""),
                _reply_key(msg))

    def _visible(self, key):
        """The hits of one folder that have not been excluded."""
        return [m for m in self._hits.get(key, [])
                if self._hit_key(m) not in self._excluded]

    def _render(self):
        for w in self.inner.winfo_children():
            w.destroy()

        live = {k: self._visible(k) for k in self._hits}
        live = {k: v for k, v in live.items() if v}
        n_msgs = sum(len(v) for v in live.values())
        n_fold = len(live)

        if self._running:
            done = getattr(self, "_total", {}).get("done", 0)
            tot  = getattr(self, "_total", {}).get("folders", 0)
            self.lbl_status.configure(
                text=f"Searching…  {done} of {tot} folders looked at  ·  "
                     f"{n_msgs} match(es) in {n_fold} folder(s) so far"
                     + (f"  ·  {len(self._excluded)} excluded"
                        if self._excluded else ""),
                fg=C_ACCENT)
        elif self._hits:
            self.lbl_status.configure(
                text=f"{n_msgs} match(es) in {n_fold} folder(s)"
                     + (f"  ·  {len(self._excluded)} excluded"
                        if self._excluded else "")
                     + "  ·  only folders that contain a match are shown",
                fg=C_FG_DIM)
        else:
            self.lbl_status.configure(
                text="Type what you are looking for, tick where to look, and "
                     "press Enter. Results appear as your own folder tree — "
                     "only the folders that actually contain a match.",
                fg=C_FG_DIM)

        try:
            self.b_stop.configure(state=("normal" if self._running
                                         else "disabled"))
            self.b_go.configure(text=("Searching…" if self._running
                                      else "Search"))
        except Exception:
            pass

        if not live:
            if self._hits and not self._running:
                tk.Label(self.inner,
                         text="   Every match has been excluded — "
                              "“↺ Bring back all” restores them.",
                         bg=C_BG2, fg=C_FG_DIM,
                         font=("Segoe UI", 9, "italic"),
                         anchor="w", pady=16).pack(fill="x")
            elif not self._running:
                tk.Label(self.inner, text="   Nothing found.",
                         bg=C_BG2, fg=C_FG_DIM,
                         font=("Segoe UI", 9, "italic"),
                         anchor="w", pady=16).pack(fill="x")
            return

        # Group by account, then folder — the same shape as the sidebar, so
        # what you see here maps onto what you already know.
        by_acct = {}
        for (email, folder), msgs in live.items():
            by_acct.setdefault(email, []).append((folder, msgs))

        for email in sorted(by_acct):
            colour = self.app._acct_colors.get(email, C_ACCENT) \
                if hasattr(self.app, "_acct_colors") else C_ACCENT
            head = tk.Frame(self.inner, bg=C_BG1)
            head.pack(fill="x", pady=(8, 0))
            tk.Frame(head, bg=colour, width=4).pack(side="left", fill="y")
            tot = sum(len(m) for _f, m in by_acct[email])
            tk.Label(head, text=f"  {email}   ({tot})", bg=C_BG1, fg=colour,
                     font=("Segoe UI", 10, "bold"), anchor="w",
                     pady=3).pack(side="left", fill="x", expand=True)

            for folder, msgs in sorted(by_acct[email],
                                       key=lambda p: p[0].lower()):
                self._render_folder(email, folder, msgs)

    def _render_folder(self, email, folder, msgs):
        key = (email, folder)
        opened = key in self._open
        row = tk.Frame(self.inner, bg=C_BG3)
        row.pack(fill="x", padx=(14, 0), pady=(2, 0))
        tw = tk.Label(row, text=("▾" if opened else "▸"), bg=C_BG3,
                      fg=C_FG_DIM, font=("Segoe UI", 9), cursor="hand2",
                      padx=4)
        tw.pack(side="left")
        disp = self.app._folder_display_name(folder)
        prot = " 🔒" if self.app._is_protected(email, folder) else ""
        name = tk.Label(row, text=f"📁  {disp}   ({len(msgs)}){prot}",
                        bg=C_BG3, fg=C_FG, font=("Segoe UI", 9, "bold"),
                        anchor="w", cursor="hand2")
        name.pack(side="left", fill="x", expand=True, pady=2)
        for w in (tw, name, row):
            w.bind("<Button-1>", lambda e, k=key: self._toggle(k))
        # Excluding a whole folder's worth in one go — handy when a search
        # keeps turning up the same archive you are not interested in.
        x = tk.Label(row, text="✕ exclude these", bg=C_BG3, fg=C_FG_DIM,
                     font=("Segoe UI", 8, "underline"), cursor="hand2",
                     padx=8)
        x.pack(side="right")
        x.bind("<Button-1>", lambda e, k=key: self._exclude_folder(k))

        if not opened:
            return
        for m in msgs:
            self._render_hit(email, folder, m)

    def _render_hit(self, email, folder, m):
        k = self._hit_key(m)
        sel = (self._sel_key == k)
        bg = C_BG4 if sel else C_BG2
        r = tk.Frame(self.inner, bg=bg, cursor="hand2")
        r.pack(fill="x", padx=(40, 8), pady=1)

        # One coloured chip per field that matched — the "different colours
        # showing what I found where" Issu asked for.
        chips = tk.Frame(r, bg=bg)
        chips.pack(side="left", padx=(4, 8))
        for f in (m.get("_match_fields") or []):
            tk.Label(chips, text=" ", bg=_SEARCH_FIELD_COLOURS.get(f, C_ACCENT),
                     width=1).pack(side="left", padx=1)

        who = (m.get("from_name") or m.get("from") or "")[:26]
        txt = tk.Label(r, text=f"{m.get('subject','(no subject)')[:64]}",
                       bg=bg, fg=(C_ACCENT if sel else C_FG),
                       font=("Segoe UI", 9), anchor="w")
        txt.pack(side="left", fill="x", expand=True)
        meta = tk.Label(r, text=f"{who}   {m.get('date','')[:16]}",
                        bg=bg, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="e")
        meta.pack(side="right", padx=6)
        for w in (r, txt, meta, chips):
            w.bind("<Button-1>",
                   lambda e, mm=m, kk=k: self._pick(mm, kk))
            w.bind("<Double-Button-1>",
                   lambda e, mm=m, kk=k: (self._pick(mm, kk),
                                          self._open_selected()))

    def _toggle(self, key):
        if key in self._open:
            self._open.discard(key)
        else:
            self._open.add(key)
        self._render()

    def _pick(self, msg, key):
        self._sel = msg
        self._sel_key = key
        which = ", ".join(_SEARCH_FIELD_LABELS[f].lower()
                          for f in (msg.get("_match_fields") or []))
        self.lbl_sel.configure(
            text=f"“{msg.get('subject','')[:48]}”  —  found in {which}"
                 f"  ·  {self.app._folder_display_name(msg.get('_folder',''))}")
        self._render()

    # ── What the buttons do ──────────────────────────────────────────────────
    def _open_selected(self):
        """Show the message in the MAIN window, in the folder it lives in."""
        if self._sel is None:
            return
        m = self._sel
        self.app.open_message_from_search(m)

    def _move_selected(self):
        if self._sel is None:
            return
        target = self.app._pick_target_folder("Move this message to…")
        if not target:
            return
        self.app._move_selected_to([self._sel], target)
        # It is not where the search found it any more.
        self._excluded.add(self._hit_key(self._sel))
        self._render()

    def _protect_selected(self):
        if self._sel is None:
            return
        email  = self._sel.get("account_email", "")
        folder = self._sel.get("_folder", "")
        if self.app._is_protected(email, folder):
            self.app._flash("That folder is already protected")
            return
        self.app._toggle_protect(email, folder,
                                 self.app._folder_display_name(folder))
        self._render()

    def _exclude_selected(self):
        if self._sel_key is None:
            return
        self._excluded.add(self._sel_key)
        self._sel = None
        self._sel_key = None
        self.lbl_sel.configure(text="Nothing picked")
        self._render()

    def _exclude_folder(self, key):
        for m in self._hits.get(key, []):
            self._excluded.add(self._hit_key(m))
        self._render()

    def _unexclude_all(self):
        self._excluded = set()
        self._render()

    def _to_background(self):
        try:
            self.root.focus_force()
            self.root.lift()
        except Exception:
            pass

    def close(self):
        self._running = False
        self._token = None
        try:
            self.top.destroy()
        except Exception:
            pass


# ******************************************************************************
# DEL 07 — ABOUT DIALOG
# ******************************************************************************

def _build_stamp() -> str:
    """Which file is running, and when it was last written.

    Deliberately taken from the FILE ON DISK rather than a version constant
    somebody has to remember to bump: a stale constant is exactly as
    misleading as no constant at all, and the question this answers is "is
    this the copy I just updated?". Frozen into an .exe there is no source
    file, so the executable's own date is used instead."""
    try:
        if getattr(sys, "frozen", False):
            path = sys.executable
            what = "exe"
        else:
            path = os.path.abspath(__file__)
            what = "py"
        st = os.stat(path)
        when = datetime.fromtimestamp(st.st_mtime).strftime("%Y-%m-%d %H:%M")
        return f"{what} · {when} · {st.st_size:,} bytes"
    except Exception:
        return "build unknown"


def _show_about(root):
    import webbrowser

    top = tk.Toplevel(root)
    top.title("About F(re)email")
    top.configure(bg=C_BG3)
    top.resizable(False, False)
    top.transient(root)
    top.grab_set()
    top.focus_force()
    top.bind("<Escape>", lambda e: top.destroy())

    # Header
    hdr = tk.Frame(top, bg=C_BG3)
    hdr.pack(fill="x")
    tk.Label(hdr, text="✉", bg=C_BG3, fg=C_ACCENT,
             font=("Segoe UI", 40)).pack(pady=(18, 0))
    tk.Label(hdr, text="F(re)email",
             bg=C_BG3, fg=C_ACCENT,
             font=("Segoe UI", 22, "bold")).pack()
    tk.Label(hdr, text="Your personal Gmail frontend",
             bg=C_BG3, fg=C_FG_DIM,
             font=("Segoe UI", 9, "italic")).pack(pady=(2, 10))

    # ── WHICH BUILD AM I ACTUALLY RUNNING? (Issu 2026-08-16) ────────────────
    # Twice in one day a new feature "did not work" and the answer both times
    # was that the updated file had not been copied over the one being run —
    # there was nothing in the program itself that could tell you. The source
    # file's own date and size settle it in a glance, and the same line goes
    # into the log at startup so it is in the record of every session.
    tk.Label(hdr, text=_build_stamp(), bg=C_BG3, fg=C_FG_DIM,
             font=("Consolas", 8)).pack(pady=(0, 10))

    tk.Frame(top, bg=C_SEP, height=1).pack(fill="x", padx=20)

    tk.Label(top, text='Created by  Lars "Issu" Olsson',
             bg=C_BG3, fg=C_FG,
             font=("Segoe UI", 10, "bold")).pack(pady=(14, 0))

    DOC_URL = (
        "https://docs.google.com/document/d/"
        "1B6y3CP-DafUKoXF9Apg4BpEl2m1j0kghRgD7lweF41s/edit?usp=sharing")

    doc_lbl = tk.Label(top, text="📄  View documentation",
                       bg=C_BG3, fg=C_ACCENT,
                       font=("Segoe UI", 9, "underline"),
                       cursor="hand2")
    doc_lbl.pack(pady=(6, 2))
    doc_lbl.bind("<Button-1>", lambda e: open_url(DOC_URL))
    doc_lbl.bind("<Enter>",    lambda e: doc_lbl.configure(fg="#b4d4ff"))
    doc_lbl.bind("<Leave>",    lambda e: doc_lbl.configure(fg=C_ACCENT))

    tk.Frame(top, bg=C_SEP, height=1).pack(fill="x", padx=20, pady=(14, 0))

    tk.Label(top, text="☕  If you enjoy F(re)email, a small gift is always welcome!",
             bg=C_BG3, fg=C_FG_DIM,
             font=("Segoe UI", 8, "italic"),
             wraplength=300, justify="center").pack(pady=(10, 6))

    donate_frame = tk.Frame(top, bg="#252535", padx=16, pady=10)
    donate_frame.pack(fill="x", padx=20, pady=(0, 16))

    REVOLUT_URL = "https://revolut.me/lars72oeh"
    PAYPAL_URL  = "https://paypal.me/issusbarn"
    WISE_URL    = "https://wise.com/pay/me/larsdenniso"

    for icon, label, url in [
        ("💳", "Revolut",  REVOLUT_URL),
        ("🅿",  "PayPal",   PAYPAL_URL),
        ("🌐", "Wise",     WISE_URL),
    ]:
        lbl = tk.Label(donate_frame, text=f"{icon}  {label}",
                       bg="#252535", fg=C_ACCENT,
                       font=("Segoe UI", 9, "underline"),
                       cursor="hand2")
        lbl.pack(anchor="w")
        lbl.bind("<Button-1>", lambda e, u=url: open_url(u))
        lbl.bind("<Enter>",    lambda e, l=lbl: l.configure(fg="#b4d4ff"))
        lbl.bind("<Leave>",    lambda e, l=lbl: l.configure(fg=C_ACCENT))

    tk.Button(top, text="Close", bg=C_BTN_STD, fg=C_BTN_FG,
              relief="flat", padx=20, pady=4,
              command=top.destroy).pack(pady=(0, 16))

    # This dialog has no fixed geometry() — it auto-sizes to its content
    # — so its real width/height are only known once everything above is
    # laid out. update_idletasks() forces that layout pass now so we can
    # read the actual size and centre using it.
    top.update_idletasks()
    _center_over(top, root, top.winfo_width(), top.winfo_height())


# ******************************************************************************
# DEL 08 — HELP DIALOG
# ******************************************************************************

_HELP_TEXT = """
F(re)email — Help & User Guide
==============================

F(re)email is a clean, Thunderbird-inspired Gmail frontend.
It connects to your Gmail account(s) with an app password
over IMAP/SMTP and lets you read and write email with a fast,
distraction-free interface.

DELETING ON GMAIL (Tools → Server changes)
------------------------------------------
  Out of the box, Delete only hides a message from this
  program's view — it stays on Gmail and returns on Refresh.

  If you want what Thunderbird does ("delete here, delete on
  Google too"), switch it on in Tools → Server changes. Then:
    • Delete MOVES the message to the Gmail Trash, where Gmail
      keeps it for 30 days and you can restore it from any mail
      program. Nothing is ever erased permanently, and the
      Trash is never emptied by F(re)email.
    • Before anything happens you are shown what will be lost,
      including every Gmail LABEL the message would disappear
      from. On Gmail one message can sit in Inbox, Sent and
      several labels at once, and trashing it removes it from
      all of them — so they are listed by name.
    • A message you sent to yourself gets an extra warning,
      because there the Inbox copy and the Sent copy are the
      same message.
    • If the local archive is on, the message is archived
      before it is deleted, so you keep a copy you own.
    • It never happens by itself. No rule, filter or timer in
      this program can delete anything on the server — only you,
      clicking Delete and confirming, one message at a time.

  Sensible order: turn on File → Local archive first, let it run
  once, and then switch deletion on.

SAFETY — PHASE 1 IS READ-ONLY BY DEFAULT
----------------------------------------
  F(re)email currently opens your mailboxes in READ-ONLY mode,
  so it CANNOT delete, move or change anything on Gmail — your
  mail is safe. "Delete" only hides a message from the current
  view; it stays on Gmail and returns when you press Refresh.
  Sending new mail / replies works normally (that only adds a
  message, it never removes one). Server-side changes (real
  delete, move, labels) are a later, opt-in Phase 2.

GETTING STARTED — ADD AN ACCOUNT
--------------------------------
  Accounts menu → Add Gmail account.
   1. Turn on 2-Step Verification for your Google account.
   2. Create a 16-character "app password" (the dialog has a
      direct link to Google's app-password page, and the same
      address as copy-paste text with a Copy button — the link
      usually shows a sign-in box first, so pasting the address
      after signing in is the reliable way in):
         https://myaccount.google.com/apppasswords
   3. Enter your name, Gmail address and the app password.
  Your app password is stored ENCRYPTED on this PC (Windows
  DPAPI) — it cannot be read by another user or another machine.
  Until you add an account, the program shows harmless DEMO mail.

"KEEP ON THE SERVER? DELETE AFTER N DAYS?" (File → Local archive)
------------------------------------------------------------------
  If you have used POP3 you will be looking for a setting like
  "leave a copy on the server, remove it after 14 days". It is
  not here, because it cannot mean anything here.

  POP3 DOWNLOADS your mail to the computer, so the copy left on
  the server is a leftover you have to decide about. IMAP — what
  this program and Gmail use — works the other way round: the
  mailbox on the server IS your mail, and this program shows you
  a view of it. There is no second copy for such a setting to
  govern.

  What people actually want from that setting is OWNERSHIP: a
  copy that stays mine whatever happens to the account. That is
  File → Local archive:
    • Writes .eml copies into account / folder / month folders
      you can browse in Explorer, years from now, with this
      program uninstalled.
    • The copy is the ORIGINAL message, byte for byte as the
      server sent it — every header and attachment intact.
    • "Keep a copy of every message automatically" is OFF by
      default: it uses your disk, so it is your decision.
    • The same message is only ever written once, however many
      times it is fetched.
    • It only ADDS. Nothing is removed from Gmail, ever.

  There is deliberately NO "delete from the server after N
  days". A timer that deletes mail while you are not watching is
  how mail is lost for good — and on Gmail one message carries
  several labels, so a rule aimed at Sent would also strip it
  out of the Inbox and All Mail. Keep your copies here; delete
  over at Google by hand, seeing exactly what goes.

MAIL FILTERS (Tools → Mail filters, or right-click a message)
-------------------------------------------------------------
  The little number box on the Match row is the whole choice:
      1  all of the following   (the default)
      2  any of the following
      3  all messages
  The three buttons beside it say the same thing — change either
  one and the other follows. Add as many conditions as you like
  with the + / − buttons; each picks a field (From, Account,
  Subject, Body, Folder), how it must match (contains, is,
  begins with…) and the text.

MAKING A RULE WAIT  ("⏳ Wait before acting" in the editor)
-----------------------------------------------------------
  Normally a rule acts the moment it sees a matching message.
  Set a wait and it leaves the message alone until it is that
  old, then files it on the next check — the exception, not the
  rule, so every rule you already have keeps acting at once.

  What it is for: a buyer's "I'm interested in…" from
  BoardGameGeek should stay in the Inbox while it is fresh, and
  take itself off to Temporär/Köpare a day later. Set the wait
  to 26 hours and that is exactly what happens.

  How it works, and why it is reliable:
    · The wait is counted from the MESSAGE'S OWN date, not from
      when this program first saw it — "26 hours" means 26 hours
      after the buyer wrote, whether or not the program was
      running in between.
    · NOTHING IS QUEUED. The rule simply does not match a
      message that is too young, and is judged again from
      scratch on the next check. So if you read, move, answer or
      delete the mail yourself in the meantime, there is no
      pending job left over to fire at the wrong thing later.
    · Closed the program for a week? Everything now overdue is
      filed on the next check.
    · A message with no readable date is acted on at once, and
      that is written to the log rather than passed over in
      silence.

  "…and anything unread STAYS unread when it is filed" (on by
  default for a waiting rule) is the other half: the rule's own
  "mark read" is refused — here and on Gmail — and the
  destination's "mail that lands here reads itself" is overridden
  for the mail this rule moves, so a filed message keeps standing
  out until YOU open it. It never makes already-read mail unread
  again. If the destination is an auto-read folder, saving the
  rule offers to take it off that list, so the two settings can
  never quietly contradict each other.

  While a rule is counting down, "Run filters now" says how many
  messages are waiting and when the next one is due, instead of
  the flatly untrue "nothing matched" — and "Why didn't my rule
  fire?" shows it as ⏳ WAITING with the exact time it will act.

WHY DIDN'T MY RULE FIRE?  (Tools, or the 🔍 button in the editor)
-----------------------------------------------------------------
  A rule that does nothing normally tells you nothing. This
  window is the answer: it shows the LAST filter run in full.

    · which rules exist, and which of them RAN for that run
      (a rule can be switched off, be set to "only when I run
      filters", or be limited to folders the message is not in)
    · ✔ FULL MATCH — matched in full, and what it did
    · ~ near miss  — some conditions matched but not enough for
      this match mode. Every condition is listed with ✔ or ✖ AND
      the text the message actually had, so you can see at once
      that the rule wanted "Frakthandling" and the subject said
      "Frakthandlingar".
    · ✖ no match, and – skipped

  Two warnings appear on their own when they apply, because they
  explain nearly every "my rules do not move anything":
    · a rule with NO action set — matching and acting are two
      separate things here, so fill in "Move to folder:";
    · Server changes switched OFF — moving and trashing happen on
      Gmail, so with that off those rules do nothing at all (the
      mail neither moves nor hides).

  The same text goes to Freemail.log. Tools → "Explain every
  filter run in the log" controls whether background runs are
  written too; a run you START yourself is always explained.

RULES THAT COULD BE MERGED (🔀 in the filter editor)
----------------------------------------------------
  Offers to fold several rules into one. Only rules set to "any
  of the following" (2) with the same actions, the same triggers
  and the same folder scope are offered — two of those become one
  rule holding both lists of conditions, meaning exactly what the
  pair meant. Rules set to "all of the following" (1) are never
  merged: ANDing two of them together makes a third, stricter
  rule that matches less than either did. It also warns when the
  same sender is named in more than one rule, since those fire in
  list order and can fight each other.

MOVING MAIL — FAVOURITES AND A FOLDING TREE
--------------------------------------------
  The folder picker (right-click → Move to folder…, or Browse…
  in a rule) has three ways in:
    ★ Favourites — five slots. The first four are PERMANENT:
      the first four folders you move mail to claim them and
      stay until you press ✕. The fifth is rolling — always
      whatever you used last. ★ on any row, or the ★ Pin
      button, puts a folder in a permanent slot by hand.
    📂 The tree — ▸ folds a branch away and it STAYS folded next
      time; "Collapse all" / "Expand all" for the whole lot.
    Find — type a few letters for a flat list of every match.
  A name that does not exist yet is created when you move.

  Actions are LOCAL (mark read, star, hide, colour, tag, snooze,
  notify) and — when Server changes is on — on Gmail itself:
  move to a folder/label, delete to the Trash (recoverable, a
  hidden local copy is kept), mark read on Gmail, star on Gmail.
  Auto-delete never touches mail you sent to yourself, and it can
  only go to the Trash — permanent erase stays manual.

  SAVE stores the rule and then offers to run the filters over
  the mail already loaded — right for a new rule, or one whose
  conditions you changed. UPDATE just stores it and stops: that
  is the one for renaming a rule or merging two, where nothing
  about WHICH mail matches has changed and the question would be
  pure noise.

  "Run now (loaded mail)" applies every rule (including "only
  manual" ones) to what's downloaded — about forty messages per
  folder. "Filter log…" shows what they've done. Reorder rules
  with ⤒ ↑ ↓ ⤓ — they run top to bottom.

  You can also move a message by hand: right-click it → "Move to
  folder…". A collapsed conversation row is acted on as a whole
  conversation — expand it with + first if you want to move one
  message out of a thread (see MOVING MAIL WITHOUT DRAG-AND-DROP).

⤴  THE RELOCATOR (Tools → Relocator — move mail by rule…)
-----------------------------------------------------------
  The same thing File_manager's ⤴ Relocator does for files.
  Type in a set of "this mail belongs THERE" rules, tick the
  ones you want, and press ▶ on one or ▶▶ on the lot.

  It is NOT the filter engine, on purpose:
    • filters run on every fetch; the Relocator runs ONLY when
      you press the button — never by itself, never on a timer;
    • filters see the ~40 messages already downloaded; the
      Relocator asks Gmail itself, so it reaches years of mail;
    • filters are one set, all or nothing; here you tick one
      rule, five, or none;
    • filters do many things; a Relocator rule does one — move
      it there (optionally marking it read on the way).

  A rule says: which mail, where to look (Inbox, Spam, All
  Mail, Sent, and any label you pick), which accounts (none
  ticked = all of them), and what happens to it.

  CONDITIONS work like the filters': add as many rows as you
  need, each on From / Subject / Body / Account / Folder, and
  mark each row either
     MUST          — it has to be true, and
     any one of    — an alternative; at least one has to hold.
  Three subjects as "any one of" plus one From as MUST reads:
  that sender, with any of those three subjects. The dialog
  writes the logic out in plain English as you type, and each
  alternative becomes its own search on the server.

  A new row starts as "any one of" + Subject, because one
  more subject line for the same sender is the row you add
  most. Change either dropdown and it stays changed.

  AGE is in HOURS or DAYS — "older than 6 hours", "older than
  3 days". IMAP can only search whole days, so the search is
  deliberately a little generous and the exact hour is checked
  here; nothing is ever missed.

  WHAT HAPPENS is either
     ⤴ Move it to…            a folder, optionally on another
                              account, optionally marking it
                              read on the way; or
     🗑 Delete it             everything the rule matches goes
                              to the Gmail Trash in one press.
  Name that second kind "Delete old receipts" and it is a
  delete button for one kind of mail — "everything from this
  sender older than two days", gone, whenever you say so.

  AN APOSTROPHE in a condition is handled for you. Gmail's
  search index folds it away ("I'm" becomes "im"), so asking
  the server for "I'm interested in" matches nothing at all.
  The program therefore asks for the longest apostrophe-free
  part of your phrase ("interested in") and then checks the
  WHOLE phrase itself, so you get exactly what you typed.
  The Log names the phrase it really sent.

  Pressing ▶ SEARCHES first and shows you the count, the
  folders and the destination before anything moves. 🔍 Count
  them all fills in the numbers without moving anything at all.

  Safeguards, the same ones the sweep has: read-only until you
  confirm; Server changes must be on; a 🔒 protected folder is
  never emptied — by a move OR a delete; a message already in
  the destination is left alone. A rule that says nothing
  about WHICH mail is refused rather than run — it would take
  a whole folder. A delete asks its own question, with the
  real number in it, and says where the mail goes (the Gmail
  Trash, 30 days, nothing erased).

  Sending mail to a DIFFERENT account uploads it there (the
  original sender is kept) and then removes it here. That path
  will not upload a header-only copy and will not deliver the
  same message twice.

CLEAN THE WHOLE MAILBOX (Tools → Clean the whole mailbox…)
-----------------------------------------------------------
  For the other job: not "tidy what is on screen" but "get rid
  of every message this sender has ever sent me". A normal
  filter run only sees the mail already downloaded; this one
  asks GMAIL for everything one rule matches, across whole
  folders, however many years back it goes.

  It works in two clearly separated steps:
    1. 🔍 Find matches — a read-only search. Only the headers
       are downloaded, so even a couple of thousand hits take
       seconds, and the list shows you exactly what would go.
    2. 🗑 Move all to Trash — asks once, with the real number
       and the folders in front of you, then moves the lot to
       the Gmail Trash in batches. 30 days to change your mind,
       from any mail program. Nothing is erased.

  Pick which folders to look in (Inbox and Spam by default) and
  which account — or all of them. "Inbox only" / "Inbox + Spam" /
  "Everything" set the tick-boxes in one click. Step 2 needs
  Tools → Server changes to be on; it offers to turn it on.

  HOW FAR BACK limits the search by DATE, on the server:
    everything          — no date limit
    only the last N days   — a quick tidy of what just arrived
    only older than N days — the opposite, and the one you want
                             for "clear out three years of this"
  Both are real IMAP terms (SINCE / BEFORE) against the date the
  server stored, so they narrow the search itself instead of
  downloading everything and throwing most of it away.

WHY DID MY MAIL "NOT MOVE"?  (it probably did)
-----------------------------------------------
  Two different things look identical from the outside.

  1. The list REFILLS. It shows the newest ~40 messages per
     folder, so moving twenty out lets twenty older ones slide up
     — the inbox looks exactly as full as before. The toast
     ("Filters moved N message(s) on Gmail: N → …") is the honest
     count.

  2. The destination was FOLDED AWAY. Freemail mirrors your whole
     Gmail label tree, but only the top level is unfolded to
     begin with. A destination two levels down — Inbox →
     Temporär → 0---Frakt & Kvitto — therefore sat inside a
     closed parent: the mail left the Inbox and appeared nowhere
     you could see. Filing mail there now unfolds the path to it
     automatically, and you can always click the ▸ arrows
     yourself.

  If a rule really moved nothing, "Why didn't my rule fire?" says
  which condition stopped it.

FILING MAIL FROM ALL YOUR ACCOUNTS INTO ONE FOLDER
--------------------------------------------------
  A rule's "Move to folder" can name ANOTHER account: set "Move
  to account" and every matching message — whichever account it
  arrives on — is filed into that one folder. This is how all
  your shipping and receipt mail ends up in one place.

  How it works, and the promises it keeps:

    • The WHOLE message is delivered. A folder listing only
      downloads headers, so before anything is uploaded the body
      is checked and, if it is missing, fetched. If the body
      cannot be got, NOTHING is copied and the original is left
      exactly where it is — you never end up with an empty copy
      and no original. It is tried again on the next check.
    • It is delivered ONCE. Every delivery is written down (see
      "Cross-account delivery log…" below) and the target account
      is searched in full before a copy is made, so filing a
      receipt on into a month folder can never cause a second one
      to be sent.
    • The copy keeps its own DATE and read state, so it sorts
      where it belongs instead of pretending to be new mail.
    • The original is moved to the source account's Trash only
      after the copy has genuinely arrived.

  Rules run on EVERY account on every scheduled check, not only
  on the account you happen to be looking at — set the intervals
  in Tools → Auto-check for new mail…

  A rule scoped with "for this account only" is the deliberate
  exception and stays on that one account.

MAIL WITH NO BODY  (Tools → Mail with no body…)
------------------------------------------------
  Finds messages whose envelope arrived but whose CONTENTS did
  not — subject and sender right, the tracking number and the
  label simply not there. An older version of the cross-account
  move could upload a message before its body had been
  downloaded, and this cleans up after it.

  It does not guess from the size: it fetches the first bytes of
  each message's body and sees whether there are any.

  🩹 Repair looks for the intact original — in this account, then
  in the account the copy came from — uploads it into the same
  folder with its real date, and moves the empty one to the
  Trash. It checks that the good copy really landed before
  removing anything, so a repair can never turn into a deletion.
  Anything that cannot be repaired is listed and left alone: an
  empty receipt is still better than no receipt.

HIDING BOILERPLATE  (Tools → Hide boilerplate in messages…)
------------------------------------------------------------
  Some senders put the same paragraph in every single message —
  BoardGameGeek's GeekMarket instructions, Tradera's footer,
  legal notes. A rule folds that away on sight, everywhere,
  for good.

  It only changes what is SHOWN. The message is untouched, a
  reply still quotes the full original, and nothing on the
  server is ever altered. That matters: Tradera's footer
  contains "Behåll detta i mailet när du svarar [[id:…]]" —
  hidden from your eyes, still present in your reply.

  Every folded block leaves a small marker saying which rule
  hid it and how many lines it took. Click it to see that block
  again in this message (the rule stays on); right-click it to
  jump straight to the rule that hid it.

  FIVE KINDS of rule:
    whole lines   fold every line containing your text. The
                  safe one, and what all the built-ins use.
    a block       from a matching line down to the "ends with"
                  line.
    to the end    everything from the match onwards. Careful —
                  real content often follows boilerplate (BGG
                  puts the seller's own notes AFTER its
                  standard paragraph).
    just the text remove only what matches and keep the rest of
                  the line. Used for markup like [geekurl=…].
                  These vanish silently, with no marker, since
                  a stray tag is noise rather than content.
    nothing       fold the matching line ONLY when every line
    under it      below it is empty. This is the one for
                  "On 27/02/2026 11:23, Lars Olsson wrote:"
                  followed by an empty quote: the same line is
                  left alone whenever the quote it introduces
                  actually arrived.

  A LINK IS NEVER FOLDED BY ACCIDENT. A rule whose own patterns
  say nothing about links may not hide a line that carries one,
  so a footer can fold away around an address without taking the
  address with it — this is what keeps BoardGameGeek's "Link to
  the original message" on screen. A rule that names its URLs
  (Tradera's navigation rule does) is trusted to mean it. Switch
  the whole guard off in Tools → Reading if you want to.

  THE FASTEST WAY TO ADD ONE: right-click the line you are tired
  of → "Never show this line again…". One small window asks how
  far it should reach — only this sender, everyone at their
  domain, or every sender — and shows you what it would hide in
  the message in front of you before you keep it. Numbers in the
  line can be treated as "any number", so a rule made from a line
  carrying a date or an order number still matches tomorrow's.
  Selecting several lines first and choosing "Always hide text
  like this" does the same for a whole paragraph.

  The editor has a live preview of the message you have open,
  so you can see what a rule takes before you keep it.

  Rules ship for BoardGameGeek and Tradera. Edit, disable or
  delete them like any other — they are not special.

MAIL THAT ARRIVES AS RAW HTML
------------------------------
  Some senders (DHL's parcel mails among them) label a part as
  plain text and then put a whole HTML document in it, so the
  reading pane showed hundreds of lines of markup. Such a part
  is now detected and rendered as text automatically, with link
  targets kept — so the parcel's own tracking link is visible
  and clickable instead of buried in an href. No rule needed,
  and it works for any sender that does this.

  Such mail also arrives full of empty lines, because that is
  what an HTML table turns into — one Tradera message held 410
  of them. A run of blank lines is drawn as ONE blank line;
  switch it off in Tools → Reading if you would rather not.
  Like every other kind of hiding here, it changes only what is
  drawn: the message keeps every line, and so does your reply.

CROSS-ACCOUNT DELIVERY LOG  (Tools → Cross-account delivery log…)
------------------------------------------------------------------
  Every message a rule has copied from one account into another,
  and when. This list is what guarantees the same message is
  never delivered twice — even after a restart, and even while
  the original sits in the source account's Trash matching its
  rule on every check.

  "Forget selected" only forgets that it happened; no mail is
  touched anywhere. Use it when you have deleted a delivered copy
  on purpose and want the rule to bring it again.

RIGHT-CLICK A FOLDER
--------------------
  · Show only when the account is collapsed (per account)
  · Mark everything in this folder as read — every unread message
    in it, on Gmail and here. Additive only: it adds "read", it
    never makes anything unread again.
  · Delete the folder — offered for YOUR OWN labels only, never
    for Inbox / Sent / Trash / Spam or the local folders.
    An EMPTY folder goes without a single question.
    A folder that still holds mail asks once and tells you the
    truth: on Gmail a folder IS a label, so deleting it takes the
    label off — the messages are NOT deleted, they stay in All
    Mail. A folder with sub-folders inside it is refused until
    you remove those first (IMAP will not delete a parent).
    Gmail's folder list can lag a minute behind, so the deleted
    folder is hidden here until the server agrees it is gone.

EMPTYING THE TRASH
------------------
  "🔥 Empty Trash" appears in the button row only while the Trash
  is the folder you are looking at (it is the one irreversible
  button in the program); it is also in the Tools menu. It erases
  the WHOLE Gmail Trash, not just the messages loaded here — it
  counts the real total on the server first, shows it, and asks
  twice. Gmail does not put this back.

  WHICH account? Only the one selected in the left sidebar. It
  clears every account ONLY when you are in the All Accounts
  view, and both questions say which it is. If it cannot tell
  which account you mean, it does nothing and says so — a
  destructive action must never widen its own scope.

  Messages you deleted THROUGH Freemail also have a hidden local
  copy in the Deleted folder for 30 days, so those are still
  recoverable. Mail that reached the Trash any other way is not.

  "☑ All" next to the quick filters ticks every message shown
  (the same as Ctrl+A); Escape or "Clear" unticks them.

MOVING MAIL WITHOUT DRAG-AND-DROP
---------------------------------
  Gmail's IMAP has no drag-and-drop and its "folders" are really
  labels, so you move mail by ticking it and pressing
  "📁 Move to…" on the bulk bar. It opens the same folder picker
  as a rule — Inbox and its sub-folders, expand the ones you
  want, favourites at the top, or type a new name. The chosen
  mail is moved on Gmail in one batch. (Right-click one message
  → Move to folder… does the same for a single message.)

  A COLLAPSED CONVERSATION IS TREATED AS ONE THING.
  A closed thread row shows the NEWEST message and a count —
  "Re: the boiler   (5)". That row IS the conversation, so
  every action on it takes all five:

      Move to folder…      Move to another account…
      Mark read / unread   Star / Remove star
      Save to Notes        Archive
      Mark as spam         Not spam
      Restore from Trash   Delete

  It used to take only the newest. An older one then slid up
  into the row, which looked exactly like nothing had happened
  — that is the bug this rule replaces.

  WANT TO SINGLE ONE OUT? EXPAND THE ROW.
  Press the + twisty (or View → Expand all). Every message then
  has its own row, and an action on one of those touches only
  that one. That is the ONLY way to act on part of a thread,
  and it is deliberate: nothing has to be ticked half-right.

  Nothing happens silently. The right-click menu says the real
  number before you click ("Delete this conversation (5
  messages)…"), the folder picker repeats it, and a delete is
  still held by the 60-second Undo bar.

  Two things deliberately do NOT follow the rule, because the
  whole conversation is the wrong answer for them:
    • Reply / Reply all / Forward / Open / Snooze — these are
      about ONE message, the one the row is showing;
    • "🚫 Junk filter…" — it builds a rule out of SENDER
      addresses, and a conversation contains the other party
      AND you. Junking your own address would be a trap.

MARK A WHOLE FOLDER READ
------------------------
  "✓ Read all" next to the quick filters marks EVERY unread
  message in the folder you are looking at as read — the whole
  folder on Gmail, not just the ~40 loaded. In the All Accounts
  view it does every account's copy. It only ADDS "read", it
  never makes anything unread again. (Right-click a folder in
  the sidebar has the same command.)

MUTING A FOLDER'S UNREAD COUNT
------------------------------
  A folder that collects filtered mail — receipts, shipping
  labels — does not need a running "(4)" nagging at you. Right-
  click the folder → "Don't show an unread count for this
  folder". Its mail still shows as unread (bold) when you open
  it; the folder just stops adding a number to the sidebar and
  to the taskbar total. A small 🔕 marks a muted folder. Right-
  click again to bring the count back. This is per folder and
  per account.

  Some rules cannot be swept, and say so with the reason: one
  that matches EVERY message (that would be the whole mailbox),
  and one whose only test is what a message does NOT contain —
  no search can list what is absent. Give the rule something to
  look FOR (From / Subject / Body) and it can be swept.

  Messages you sent to yourself are always skipped: on Gmail
  that is ONE message wearing both the Inbox and the Sent label,
  so trashing it would take it out of both.

  The quickest route: select the junk in the list → "🚫 Junk
  filter…" → "🧹 Create & clean whole mailbox…".

RULES PANEL (top of every opened message)
------------------------------------------
  Every message you open now starts with a small panel that
  tells you which rules are acting on it, in two columns:
    • For THIS message — the tags, follow-up reminder, snooze,
      applied filters and any hidden parts of THIS one mail.
    • For THIS sender  — the standing rules that hit every mail
      this address sends (save-the-attachment rules, filters,
      spam / trusted / blocked). Its "Edit sender rules…" button
      opens the full editor.
  Click the ▾ / ▸ arrow to fold the panel away; it stays the way
  you leave it. Everything it lists is local to this computer —
  none of it changes anything on Gmail.

LINKS IN A MESSAGE
------------------
  Web links (http / https) in the message text are clickable —
  just click one and it opens in your browser (using this
  account's browser profile, if you set one up). The "🌐 Open
  link…" button still lists every link if you prefer to pick.

  IF CLICKING A LINK USED TO TAKE SECONDS  (fixed 2026-08-08)
  It was not the address lookup. Handing the link to Windows —
  or launching the browser command — starts a WHOLE SECOND
  browser process whose only job is to tell the window you
  already have open to show a page, and then quit. For WhyBrowse
  that means loading Chromium first every single time.
  The link is now written straight into the browser that is
  already running, so the tab appears at once and nothing is
  launched. Accounts → "Browser profiles…" → Speed has the
  switch, plus a "⚡ Check the connection" button that tells you
  in milliseconds whether it is working.
  One catch worth knowing: F(re)email and the browser must run
  the same way. If one of them was started as administrator and
  the other was not, Windows will not let them talk, and the
  check button says so — links still open, just the slow way.

HIDE PART OF A MESSAGE (reading pane)
-------------------------------------
  Long mail with only one line left to answer? Select the part
  you have already dealt with and press "✂ Hide selection" —
  it folds away, leaving a small "⟨hidden — click to show⟩"
  marker in its place. Click the marker, or "↺ Show all hidden",
  to bring it back. This is purely visual and completely
  reversible: the text on Gmail is never touched and nothing is
  deleted. What you fold is remembered per message, so it stays
  folded the next time you open it.

ATTACHMENTS (in an opened message)
----------------------------------
  • Left-click an attachment to open it — pictures show in a
    quick in-app preview, everything else opens in the program
    Windows normally uses.
  • "💾 Save all…" (next to the attachment list) writes every
    file to a folder you choose. It never overwrites — a name
    already there gets " (2)", " (3)" and so on.
  • Right-click an attachment for: Save as…, Save all…, and
    "Open with…". "Open with…" lets you pick any program (an
    .exe, or one of your own .py tools). Your choice is
    remembered for that file type, so next time a .png, say,
    offers "Open with QR-code-text" as a one-click item.
    "Forget the programs for this type" clears the list.

SHIPPING RECEIPTS — WHICH PARCEL IS THIS?
-----------------------------------------
  Tradera, PostNord and DHL all send receipts that look the
  same: one subject, one sender, a QR code called
  QrCode-3505190755.png. The town it is going to and the
  title of the game are not in the mail at all — they are
  inside the attached Kvitto.pdf and Fraktsedel.pdf, so the
  program reads them out.

  • The message-list row shows the parcel instead of the
    subject:  "📦 Tyskland · Tärning, svaga siffror".
  • The opened message gets a green strip at the top with
    the town/country, the title, the buyer, the carrier, the
    amount and the tracking number.
  • Right-click the QR code (or any attachment) →
    "📦 Save as 00-DSV---Tyskland---Tärning, svaga siffror---
    QrCode-3505190755.png". The "00-" keeps the parcels you
    still have to hand in at the top of the folder. There is
    a one-click button for it on the green strip too, and
    "Save all of them with that prefix…" for the whole set.

  The CARRIER comes first, because it is the errand: DSV goes
  to ICA Kvantum, DHL goes to Pressbyrån, so sorting the
  folder by name puts one trip's parcels together. PostNord
  is written "Post", and DB Schenker is written "DSV" — DSV
  bought them, so the older receipts and the newer ones mean
  the same counter. Then the place, then the title.

  The rule for the place is: the TOWN when the parcel stays
  in Sweden, the COUNTRY when it leaves. When the country
  cannot be established the town is used — never a guess.

  A bare drop-off receipt (a DHL or PostNord "inlämnings-
  kvitto", which is a QR code and nothing else) still gets
  "00-DHL---" in front of it, so it lands with the rest.

TAGS — YOUR OWN MARKS (View → Tags, or keys 1-9)
-------------------------------------------------
  Select a message and press 1-9 to put a tag on it, or use
  🏷 Tags… in the reading pane. Nine are set up to start with:
  Important, Work, Personal, To do, Later, Bill, Shipping,
  Keep and Junk — rename them, recolour them, change the icon,
  or add your own in View → Tags.

  The icons appear in front of the subject in the message list,
  and the first tag's colour tints the whole row. A tag you
  applied by hand beats a colour set by a filter rule.

  Not to be confused with what was already there:
    • contact colours — colour by SENDER
    • filter colours  — colour by RULE
    • star / ! / ⚠    — three fixed flags
  A tag is the one you put on a single message by hand.
  Tags are stored on this computer, not on Gmail.

AUTOMATIC DATED FOLDERS (Accounts → Automatic folders)
-------------------------------------------------------
  For the monthly chore: "on the 3rd of every month, create
  08-Augusti inside my Frakt folder, and move last month's
  shipping labels into it".

  A plan has:
    • the folder to work in
    • the name to create, from tokens: {MM} {M} {YYYY} {YY}
      {MonthName} {Q} {DD} — e.g. "{MM}-{MonthName}"
    • which day of the month, and every how many months
    • optionally: move files in — last month's, this month's,
      or an exact date range
    • month names in your own language, if you want folders
      called Augusti rather than August

  A file's date is taken from a date in its NAME first — your
  attachment prefix rules put one there — and only then from
  its timestamp, because copying files rewrites timestamps but
  the name is what you meant.

  Preview shows exactly what would happen before anything does.
  Files are never overwritten, sub-folders are never moved, and
  a plan runs once per period — if the computer was off on the
  3rd it runs on the 4th instead of skipping the month.

  This works on FILES ON YOUR DISK. For mail, the one thing that
  happens on its own is FOLDER AGEING, below — and only on the
  folders you switch it on for.

FOLDER AGEING — "delete later" that means it
---------------------------------------------
  Right-click a folder → ⏳ Age the mail in "…".

  A filter rule asks WHO sent it and fires once, on arrival.
  This asks only HOW OLD it is, and keeps asking — every message
  in the folder is looked at again about every quarter of an
  hour, for as long as it sits there.

  A rule is a ladder of steps, which is the whole point:

        "Delete later"   after 24 h  →  mark it as read
                         after 48 h  →  move it to the Trash

  Each message gets the LAST step whose time has come, so a
  three-day-old mail goes straight to the Trash instead of being
  marked read today and binned tomorrow. A step can be:
    • mark it as read
    • move it to a folder you pick
    • move it to the Trash

  Age is when the mail ARRIVED (the server's own timestamp), not
  the date the sender wrote in it.

  The safety rails, all of them on by default:
    • Nothing is ever ERASED. "Delete" means the Trash, where
      Gmail keeps it for 30 days. Emptying the Trash is still
      something you do yourself.
    • A STARRED message is never touched. A star is you saying
      "not this one", and no clock outvotes that.
    • A step can say "…but only if I have already read it", so
      nothing you have not seen is thrown away.
    • A PROTECTED folder (right-click → 🔒) is never aged.
    • It stops and asks before touching more than 50 messages in
      one run — the number is yours to change. Typing 2 where
      you meant 200 is a real mistake and this is what makes it
      survivable.
    • It is a server change, so it needs the "Server changes"
      switch like every other one. With that off, an ageing rule
      does nothing at all.

  Press 👁 "Show me what it would do now" before switching a rule
  on. It is read-only and lists every message, its age and what
  would happen to it. ▶ "Run now" does it this second instead of
  waiting for the next pass.

  Accounts → Folder ageing… is the same thing as a list, when you
  want to see every folder that ages its mail at once.

FOLLOW-UPS — "I AM NOT FINISHED WITH THIS MAIL"
------------------------------------------------
  Not the calendar, and not snooze. The calendar is for things
  that happen at a time; snooze HIDES a message until later.
  A follow-up leaves the message where it is and keeps coming
  back to remind you that something in it is still undone.

  In the reading pane, click 🔔 Remind me… and set:
    • a note — what is actually left to do (optional)
    • WHEN THE FIRST reminder comes: in 1 hour, 3 hours,
      tomorrow 09:00, in 3 days, in a week, in 1 / 2 / 3 months
      (09:00), or an exact time
    • HOW OFTEN afterwards: only once, every 30 minutes, hour,
      3 hours, day, 2 days or week. This is set separately from
      the first wait — "first in 3 hours, then once a day" is a
      normal thing to want.
    • WHEN IT STOPS: after N reminders, never after a given
      date, or not at all — in which case it keeps reminding
      until you press "Stop reminding" in the popup.

  THE LAST REMINDER LOOKS DIFFERENT ON PURPOSE: another colour,
  a thicker border, "⚠ LAST REMINDER" and a plain sentence that
  you will not be reminded again. It also offers "Keep reminding
  me", which throws away the ending and carries on until you
  stop it yourself.

  LIFT THE MAIL TO THE TOP (the tick box at the bottom of the
  window, on by default): when the time comes the mail itself
  turns UNREAD, gets a 🔔 and moves to the TOP of its folder,
  whatever the list is sorted by. It stays there — even if you
  open it — until you press "✔ Done" (reading pane, the popup,
  the Follow-ups folder, or right-click the mail), or set a NEW
  reminder on it with 🔔 Remind me… (the new reminder replaces
  the old one and the mail goes back to its place). Typical use:
  "ask them again in 2 months if they have not come back".
  "Unread" is only on this PC — Gmail is never told.

  The "Follow-ups" folder in the sidebar lists everything you
  are not finished with, soonest first, and the ones about to
  run out are starred. Messages with a live follow-up show a 🔔
  in the ordinary message list too.

  If the program was closed when a reminder was due, you get it
  once when you start up again — not one for every interval that
  passed while you were away.

NOTES — TWO KINDS, AND THEY ARE DIFFERENT JOBS
-----------------------------------------------
  📌 Notes (Ctrl+Shift+T) is the POST-IT BOARD: small coloured
  notes for "milk, eggs, ring the dentist". Pick one on the
  left, write on the right, and it saves itself — there is no
  Save button and nothing you must fill in first. Leave the
  title empty and the first line you typed becomes it. Five
  colours; right-click a card to pin it to the top, copy it,
  or delete it. 📌 pinned notes stay above the rest, and the
  rest are ordered by whichever you touched last.

  The whole board is ONE plain text file —
  Helpfiles/Freemail/Notes/postit.txt — so you can read and
  edit it in Notepad, and back it up by copying one file.
  "📁 Open the file" in the board shows it to you.

  The LONG note below is the other kind, and is unchanged.

NOTES — MAIL TO YOURSELF, WITHOUT A SERVER
------------------------------------------
  Long note (Ctrl+T) opens the same editor as a normal
  message, but "Save note" writes a file instead of sending
  anything. No recipient is needed and nothing leaves your
  computer. The notes appear in the "Notes" folder in the
  sidebar and behave like any other mail: sort, search, open
  attachments, save as PDF.

  "🗒 Save to Notes" in the reading pane copies a message you
  have RECEIVED — attachments included — into the same folder.
  That covers "forward this to my own pile", except nothing is
  forwarded anywhere: the copy is written straight to disk and
  is yours from then on, whatever happens to the original.

  Notes are ordinary .eml files, so they outlive this program:
  open them in Thunderbird or Outlook, copy them to a backup,
  or read them in Notepad. Choose where they live with
  File → Change the Notes folder, and File → Open the Notes
  folder shows them in Explorer. The folder IS the list — drop
  an .eml in there and it appears; delete one and it is gone.

WHY NOT JUST MAIL YOURSELF? (an important Gmail trap)
------------------------------------------------------
  Gmail does not really have folders. It stores ONE message
  and hangs labels on it. A mail you send to yourself is
  therefore a SINGLE message wearing both the "Inbox" and the
  "Sent" label — not two copies. Delete it "from Sent" and it
  vanishes from the Inbox as well, because there was only ever
  one of it. Thunderbird shows it in both places, which makes
  this look like a bug in the mail program. It is not; it is
  how Gmail works.

  F(re)email cannot do this to you today: Phase 1 is read-only,
  and Delete here only hides a message from the current view.
  When a message you sent to yourself is opened, the reading
  pane says so plainly. And when server-side deletion is
  eventually unlocked in Phase 2, a self-addressed message will
  require its own explicit confirmation listing everywhere it
  would disappear from — never a silent "move to Trash".

  For anything you want to KEEP, use Notes. A note has no
  labels, no sync and no server: nothing can quietly remove it.

CONVERSATIONS (View menu)
-------------------------
  By default the list shows ONE row per conversation: the newest
  message in it, with the number of messages in brackets, e.g.
  "Project Phoenix — deadline  (3)". Click the + to open the
  rest underneath, marked with ↳ and listed oldest first.
    View → Threaded view      — turn grouping off to get one row
                                per message instead
    View → Expand all         — open every conversation
    View → Collapse all       — close them again
  In the reading pane, "Show full thread history" decides whether
  you see the whole exchange or only the latest round.

MAIN LAYOUT
-----------
  Left panel    — Account list and folders (Inbox, Sent, etc.)
  Centre panel  — Message list for the selected folder
  Message popup — Click any message to open it in its own window

TOOLBAR BUTTONS
---------------
  New Message  — Open the compose window to write a new email
  Reply        — Reply to the currently selected message
  Smart Reply  — Answer point-by-point under each paragraph
  Forward      — Forward the message to someone else
  Delete       — Hide from the current view (Phase 1: local only)
  Contacts     — Your address book (right here, not buried in a
                 menu): named contacts, groups, everyone you have
                 written to
  Refresh      — Reload messages from Gmail (read-only)
  Log          — What has happened to your mail lately (see
                 "THE ACTIVITY LOG" below)
  Search box   — Filter the loaded folder by sender/subject/text

WHY MAIL OPENS QUICKLY (and what to do if it doesn't)
-----------------------------------------------------
  The message LIST is fetched first and the messages themselves
  come down behind it — that is what makes changing folder
  quick. So that opening one is not then a wait, two things
  happen automatically:

    • READ AHEAD. Right after the list arrives, the newest
      messages are quietly downloaded in the background. By the
      time you click one it is already on your own disk and
      opens with nothing to wait for. Tools → Reading sets how
      many (12 by default), or turns it off.

    • A SEPARATE LINE FOR YOU. Checking for new mail, counting
      unread and reading ahead all share one connection per
      account. Anything YOU click gets its own, so it never
      queues behind the automatic work. That was the whole of
      the old "Loading… " half-minute: not a slow server, a
      queue.

  If a message ever does sit on "Loading", it is not stuck —
  the panel that appears explains what went wrong and offers
  Try again. The commonest reason is that one of your own rules
  moved the message; the program follows it and opens it from
  wherever it now lives.

A REPLY WINDOW NO LONGER LOCKS THE PROGRAM
------------------------------------------
  Compose and Smart Reply are ordinary windows: while one is
  open you can still change folder, open another message, search
  — everything. They used to freeze the main window, so clicking
  a folder did nothing at all.

  Escape does NOT throw a half-written message away. It steps
  back to the mailbox and leaves the window open behind it; its
  taskbar button brings it back. Closing one that has text in it
  still asks what to do with it.

THE ACTIVITY LOG (the 🧾 Log button)
------------------------------------
  Your phone says "new mail". By the time you open the program a
  rule has already read it, moved it or binned it, and nothing on
  screen says where it went. This is the answer.

  One line per event, newest first, KEPT when you close the
  program:

    14:32  FILTERED  →  issusbarn@gmail.com
           From shipping.noreply@tradera.com · rule "Frakt Tradera"
           "Frakthandlingar och kvitto"
           moved to INBOX/Temporär/0---Frakt & Kvitto

  Sends, failed sends, deletes and messages a rule moved while
  you had them open are all recorded. Filter it by kind, or type
  in the Find box to search it.

  A message that leaves the folder while you are reading it now
  says so on the spot, naming the rule that moved it — and if you
  open a message a rule has already moved, the program FOLLOWS it
  and opens it from wherever it now lives instead of sitting on
  "Loading" for ever.

WRITING A MESSAGE (Compose and Smart Reply)
-------------------------------------------
  Both windows have the same three recipient rows — To:, Cc:
  and Bcc: — each with a 📖 button that opens the address-book
  picker (★ Favorites first, filter box, multi-select).

  "🔒 Send to me only" is the group-mail privacy switch: tick
  it and everyone you listed is moved into Bcc while the message
  is addressed to you, so no recipient sees any other address.
  (With five or more visible recipients you are offered the same
  thing automatically.)

  A CC LIST THAT DOES NOT EAT THE WINDOW. Reply All on a
  circular hands you thirty addresses, and thirty chips wrap onto
  row after row until the message itself is off the screen. Above
  three, a To:/Cc:/Bcc: field therefore shows ONE row — as many
  as fit — and then a "+24 more ▾" pill. Click the pill, or the
  small "▾ 28" that appears beside the caption, to see them all;
  "▴ fewer" folds them back.

  This is display only. Every address is still in the field and
  every one of them is sent — folded and open send exactly the
  same message. The count stays visible beside the caption even
  when the addresses do not, because "how many else got this" and
  "who else got this" are different questions and only the second
  one is in your way. (The reading pane folds long recipient
  lists the same way; see recipients_max under SETTINGS.)

  Addresses are protected in three places, because something
  was slipping stray characters into them ("…@♣gmail.com"):
    • As you TYPE (and when you paste) the To:/Cc:/Bcc: fields
      refuse characters that cannot be in an address — control
      and invisible characters, and symbols like ♣ ★ ☺. Letters
      of any language still work, so a display name may be
      "Ärna Öberg" as usual. Pasting an address that contains
      one keeps the address and drops the character.
    • On SEND the fields are cleaned again and you are asked
      about anything still odd — chiefly a domain that merely
      LOOKS like gmail.com ("ugmail.com").
    • In the OUTBOX, every message is cleaned once more, so mail
      sent by a filter, an unsubscribe or a bounce retry is
      covered too.
  Each of those writes the offending character to Freemail.log
  with its Unicode number and name, so if it ever happens again
  the log says exactly what it was and where it came from.
  Contacts are cleaned on the way into the address book as well,
  and "🩺 Check addresses" there mends ones already stored.

  TEXT AT A SIZE YOU CAN READ — two sizes, not one. Each pane
  has its own, and each half of the strip sits over the pane it
  sizes. In Reply, directly above the two panes:

   ☑ Quote original on send  🔍 Original: A− 9pt A+     ⟵ theirs
                Often-used text: ➕ ➕ ➕  🔍 Answer: A− 10pt A+
                  [↺ Default] [★ Favourite] [📌 Pin]    ⟵ yours

  One row, as long as the window is wide enough for both halves
  (about 1150 px — which is what the shipped size gives you).
  Make it narrower and the answer half drops to a second row of
  its own rather than having its last buttons cut off; widen it
  again and the two fold back together. Nothing is lost either
  way, and you never have to think about it.

  Smart Reply splits top and bottom instead of left and right,
  so it keeps both groups on one row above the paragraphs.

  The ➕ "often-used text" buttons moved in front of the answer
  group on purpose: they type into YOUR box, not the sender's.

  From the keyboard: Ctrl + / Ctrl − / Ctrl 0 size your own text,
  which is where the cursor is; add Shift for theirs. Simplest of
  all, hold Ctrl and turn the mouse wheel over whichever of the
  two you are pointing at.

  THREE THINGS ARE REMEMBERED, and they are not the same thing:

    • LAST. Both sizes and the splitter (how far you dragged the
      divider between their text and yours) are saved when you
      close the window and are exactly as you left them next
      time. So is the window's size and position, as before.

    • DEFAULT. ↺ Default puts both sizes, the splitter AND the
      window size back to what the program ships with. It is the
      way out when the remembered layout has ended up somewhere
      unusable — dragged off a second monitor, say.

    • FAVOURITE. 📌 Pin saves exactly what you are looking at —
      both sizes, the splitter and the window size — as YOUR
      layout, written to disk straight away. ★ Favourite brings
      it back, in this window and in every one you open later.

  New message, Forward and Note have no original to read, so
  they show the answer half of the strip only — the size you
  pick there is the same one your replies use.

  Reply and Smart Reply keep separate settings for all of this,
  because they are read at different sizes.

SMART REPLY — answer point by point
-----------------------------------
  The sender's message is split into paragraphs, shown top to
  bottom. Click a paragraph (or Ctrl+↑ / Ctrl+↓) to answer it;
  your writing box is DOCKED at the bottom and never scrolls
  away. A ● marks the paragraphs you have answered, and a
  preview of your answer shows on each. Switching paragraphs
  never loses text.

  YOU choose what a paragraph is. Blank lines split it for you;
  a message with none is split line by line so it is never one
  giant block. On the docked box, "✂ Split into lines" breaks
  the selected block into one paragraph per line, and "⬆ Merge
  up" joins it with the one above — between them you can shape
  any paragraphing you want. Answers are kept through both.

  FINISHING IT LATER. A long mail does not have to be answered
  in one sitting. Everything you have typed is saved against that
  message the moment you close the window — and against the
  Message-ID, so it survives the mail being moved to another
  folder or account by one of your rules. Open Smart Reply on it
  again and your answers are back, with the cursor already on the
  first paragraph you have NOT answered. A green line at the top
  says how many answers came back.

  SETTING A PARAGRAPH ASIDE. Each paragraph has "⊘ set aside".
  A set-aside paragraph is struck through here and left out of
  the sent message COMPLETELY — use it for greetings, footers and
  anything you have no intention of answering. Click "↩ bring
  back" to undo it. "⊘ Set aside the answered ones" clears
  everything you have already dealt with out of the way in one
  click, leaving only what still needs writing; your answers are
  untouched and still go out. "↩ Bring all back" reverses it.
  The line above the paragraphs keeps the score: "3 of 11
  paragraphs answered · 2 set aside · 6 still open".

  Every Smart Reply arrives in TWO parts:
    • My reply         — just your answers, clean, nothing of
                         the sender's text.
    • The full message — the original text with your answers
                         placed exactly where you wrote them.
  The "My answers at the top" tick-box (default on) puts the
  clean answers first; untick it and the full version leads.

  The message STARTS with content — no heading, no "you will
  find my reply first" note over the top of it. The single
  sentence explaining why the same conversation appears twice
  sits BETWEEN the two copies, where a reader actually needs it,
  together with the line number the second copy starts on.

  JUMPING ABOUT. Every paragraph is numbered, and in the HTML
  copy each answer links to the paragraph it answers and each
  paragraph links back to its answer — so a long point-by-point
  reply can be followed in either direction, one click at a time.
  Plain text carries the same [1] [2] … markers, so the
  navigation still works in a mail program that shows no HTML.

  "Indent theirs: 0 / 5 / 10" pushes every line the SENDER wrote
  that many spaces to the right, in both the plain and the HTML
  copy. With 5 or 10 their words and yours stand in two separate
  columns and it is obvious at a glance who is saying what.
  0 (the default) leaves the text as it was. The same setting
  also indents the quoted original of a normal reply.

  "Their text:" chooses how the sender's OLD text looks in the
  full part — grey, italic, bold, a quote bar, or plain. (Plain
  text always marks it with "> "; the styling is in the HTML
  copy, which every modern mail program shows.) The message is
  sent as both plain and HTML, so a text-only client still gets
  the whole thing. Only the latest round is ever sent — never a
  nested quote chain.

ATTACHMENTS
-----------
  • Messages with files show a 📎 in the list.
  • In the reading pane, click an attachment name to open it in
    your system's default viewer (a separate popup window) —
    PDFs and documents never open inside F(re)email itself.
  • When composing, use 📎 Attach to add files to your message.

AUTO-SAVE ATTACHMENTS (Accounts → Attachment auto-save rules)
-------------------------------------------------------------
  Save attachments from chosen senders automatically on every
  fetch. Set a default folder, then add rules:
    • Sender contains — match part of the sender (e.g. "GELF").
    • Receiving acct  — limit to one of your accounts, or any.
    • Save into       — the default folder, or a per-sender
                        sub-folder of it.
    • Filename prefix — what every saved file is called before
                        its own name. Example:
                        GELF---Sandtorp 32---{YYYY-MM}---
                        giving  GELF---Sandtorp 32---2026-09---kvitto.pdf

  THE DATE — PICK IT, DON'T TYPE IT
    Under the prefix box there is a "Date in the name:" dropdown
    and a first / last choice:

        no date  ·  2026-09  ·  2026-09-01  ·  2026  ·  09  ·  01

    Choose one and it writes the token into the prefix box for
    you, at the front or the back; "first"/"last" moves it,
    "no date" takes it out again and puts the prefix back exactly
    as it was. Under that, a live line shows what a file would
    actually be called. So you can SEE the answer instead of
    guessing at the spelling.

    The date used is the EMAIL's own date, not today's — an
    electricity bill that arrives in June for May keeps its
    month.

    Typing tokens by hand still works, and it is no longer fussy
    about the brackets: {YYYY-MM}, [YYYY-MM], (YYYY-MM) and
    <yyyy-mm> all do the same thing. (On a Swedish keyboard { is
    AltGr+7 and [ is AltGr+8 — one key apart. Square brackets
    used to come out as the literal letters YYYY-MM with nothing
    to say why.) Brackets around anything NOT a token are left
    alone, so a file called "[note]" keeps its brackets.

    The other tokens are {sender} {sender_email} {account}
    {subject}, and take brackets just the same.

  Saving is read-only towards Gmail and never overwrites an
  identical file that is already there.

ADDRESS BOOK (Accounts → Address book)
--------------------------------------
  Save named contacts (name, email, optional group) and filter
  them. When composing, start typing in the To: field and a
  suggestion list appears — use Up/Down + Enter, or click, to
  pick a contact. Type a comma to add another recipient.

  The 📖 button at the end of every To: / Cc: / Bcc: row opens
  the picker instead: ★ Favorites first, "All contacts" beside
  it, a filter box, and multi-select. It is on the Compose
  window AND on Smart Reply.

  EDITING A CONTACT: click the row. It drops into the fields at
  the bottom, the button changes to "💾 Save changes", and the
  row is highlighted so you can see which one you are on. Change
  the name, the address or the group and press it. Changing the
  ADDRESS replaces that contact — you do not end up with the old
  one beside the new. "✖ Clear" (or Esc) lets go of the row, and
  the next Add makes a new contact instead. The ★ and the group
  survive an edit even when you only touched the name.

  At the bottom of the address book, two switches decide when
  people are remembered for you:
    • when I REPLY to someone            — on  (recommended)
    • when I send a NEW message          — off (a one-off mail
      to a web shop needn't live here forever)
  An address already in the book is merged, never duplicated.

  🚫 NEVER SAVE… — the list of addresses that must never be
  remembered automatically. Four kinds of rule:
    Address is    the exact address        robot@shop.example
    Domain is     that domain and below    shop.example  (also
                  catches mail.shop.example, never notshop.example)
    Starts with   noreply, no-reply, info…
    Ends with     -bounce, .ru, +shop…     (matches the end of the
                  address, or the end of the name before the @)
  A matching address is skipped everywhere it would be saved for
  you: replying, sending, a .vcf or CSV import. Typing one in by
  hand still works — it asks first, and takes your yes.
  "✨ Add the usual robots" fills in noreply / no-reply /
  donotreply / bounce / mailer-daemon / postmaster in one press.
  "🧹 Clean the book now" applies the rules to contacts you
  ALREADY have — it shows the whole list and removes nothing
  without your yes. Adding a rule never deletes anything by
  itself.

CONTACT COLOURS (Accounts → Contact colours)
--------------------------------------------
  Give a sender a colour so their messages stand out in the
  list (the sender name is shown in that colour with a ● dot).
  Add an entry with "Sender contains" (an address or part of a
  name), pick a colour from the palette (or "More…" for any
  colour), and an optional group label. Give SEVERAL senders
  the SAME colour to colour-code an informal group. This also
  doubles as a simple, colour-coded address book.

COMPOSING A MESSAGE
-------------------
  • Fill in To:, Cc:, and Subject: fields.
  • When replying, the original message stays visible in a box on
    the left while you type a clean answer on the right. Tick
    "Quote original on send" if you want the original quoted in
    the sent mail (off by default — keeps replies clean).
  • Press ENTER in any header field to jump to the next.
  • Click Send, or press ENTER after the body is ready.
  • Press Escape or click Discard to cancel.

READING MESSAGES
----------------
  • Click any row in the message list to read it.
  • Unread messages appear brighter with a blue dot.
  • Starred messages show a ★ in the list.
  • Use the scrollbar or mouse-wheel in the reading pane.
  • Click the column headers (Subject, Correspondent, Date, ★…)
    to sort; click again to reverse. The arrow shows the order.
  • For HTML newsletters, click "View formatted (HTML) in popup".
    Remote images are blocked until you tick "Load remote images".
  • At the bottom, "Load older messages" fetches the next page.
  • The OLDER messages of a thread are shown above the one you
    opened, shortened to a couple of lines. "Show the whole
    message" under one of them opens it in full, with its links
    clickable — which is how you reach something that lives at
    the BOTTOM of an earlier message, such as BoardGameGeek's
    link to the original geekmail.

FOLDER SIDEBAR
--------------
  Click a folder name to switch (Inbox, Sent, Drafts, etc.).
  Unread counts appear next to the folder name and now update
  the instant you read a message (they no longer wait for the
  next server check).

  COMPACT FOLDER LIST (View menu, on by default): Inbox stays a
  full row; the rest are packed into side-by-side columns
  (Sent|Drafts, Spam|Trash|Deleted, …) to save space. Turn it
  off for one-folder-per-row. "Merge duplicate folders" hides
  Thunderbird look-alikes (Junk, Skickat, Utkast, Papperskorg)
  since the real Gmail folder is already listed. Spam, Trash and
  Deleted are different things: Spam = Gmail's junk, Trash =
  recoverable for 30 days, Deleted = your local copies of mail
  removed from Gmail for good.

  ALL ACCOUNTS (🌐 — top of sidebar)
  ------------------------------------
  The "All Accounts" entry at the top is a unified view across
  every Gmail account you have added.

  • Inbox   — shows ALL incoming mail from every account together,
              sorted by date. A small "⟶name" badge shows which
              account each message was received on.
  • Sent    — combined sent mail from all accounts.
  • Starred — all starred messages across accounts.
  • etc.

  When you Reply from the unified view, F(re)email automatically
  sets From: to the account that originally received the message.
  When you compose a New Message from the unified view, From: is
  set to your default account — but you can change it via the
  From: dropdown in the compose window.

KEYBOARD SHORTCUTS
------------------
  ↑ / ↓        — move up and down INSIDE the pane that currently
                 has the arrow keys
  ← / →        — hand the arrow keys to the folder pane (←) or to
                 the message pane (→). A thin blue edge along the
                 top of a pane shows which one has them; clicking
                 a folder or a message moves them there too.
  Shift+↑ / ↓  — grow the message selection from where you
                 started. Turn round and it shrinks again. The
                 list always keeps ONE row of headroom in the
                 direction you are travelling, so you can see
                 the message you are about to take before you
                 take it.
  N  or Ctrl+N — New message
  R            — Reply to the selected message
  F            — Forward the selected message
  Del          — Delete selected (Phase 1: hides locally)
  F5           — Refresh / check for new mail
  F1           — Help
  (Letter shortcuts are ignored while you are typing in a
   field, so they never interfere with composing or search.
   The arrow keys are dead while a Write or Reply window has the
   keyboard — those are windows of their own.)

AUTO-CHECK FOR NEW MAIL
-----------------------
  FASTEST WAY: RIGHT-CLICK THE ACCOUNT in the left sidebar. Its
  own menu opens with "Auto-check for this account" (Use default /
  Off / 1 / 5 / 10 / 15 / 30 / 60 min), "Check this account now",
  "Set as default sender", "Account colours…", collapse and
  remove. Right-click the "All Accounts" header for the shared
  default interval and "Check all accounts now".

  The same settings also live in Tools -> Auto-check for new
  mail..., a window with one row per account. There is a
  "Default (all accounts)" interval, and every account can have
  its OWN interval that overrides the default (for example: work
  every 1 minute, private every 15 minutes). Choose Off / 1 / 5 /
  10 / 15 / 30 / 60 minutes, or "Use default" per account.

  Each account runs on its own timer and is checked independently
  in the background. When a check finds new mail you get the
  normal new-mail toast, even if you are looking at another
  account. It is read-only — it only fetches, never changes Gmail.

  Tools -> Check for new mail now (or the ↻ Refresh button)
  checks the account you are viewing right this second. In the
  "All Accounts" view that means every account at once.

  FAST UPDATES / LOCAL CACHE
  Same window: "Keep a local copy of messages". With it on (the
  default) F(re)email works like Thunderbird — a message is
  downloaded ONCE and kept in Helpfiles/Freemail/Cache, so later refreshes
  only pull the mail that is actually new and re-check read/unread
  flags. That is what makes updating an inbox fast. "Clear cache"
  throws the local copy away (Gmail is untouched); the next
  refresh simply downloads it again. All settings are remembered
  between sessions.

READING & RIGHT-CLICK
---------------------
  RIGHT-CLICK A MESSAGE for its actions: Reply, Mark read/unread,
  Star, Mark as spam (remembers the sender), Snooze, Save to
  Notes, "Always keep this sender unread", Delete. If several
  rows are ticked, it acts on all of them.

  A TICK STAYS TICKED. Marking rows and then having the folder
  update — the automatic check finishing, a rule running, you
  pressing ↻ — used to leave you unmarked and starting again.
  It does not any more: the ticks are carried over to the
  refreshed list, and they are carried by the message's own
  Message-ID, so a mail that one of your rules MOVES in the
  meantime (which gives it a new number on the server) keeps its
  tick as well. A tick only goes when the message itself has
  genuinely left the folder — or when you change folder, which
  clears them all on purpose.

  RIGHT-CLICK AN ACCOUNT (left sidebar) for that account's own
  menu: auto-check interval, check now, signature, default
  sender, colours, collapse, remove.

  MARK-READ TIMING (Tools -> Reading): a message turns read once
  you have kept it open for your chosen time (default 1 second) —
  scrolling past does not read it. A message you flag unread by
  hand needs a longer dwell to read again (default 5 s). Marking
  read can also add the "seen" flag on Gmail (never removes it), so
  your phone stops showing it as new; "mark unread" here is always
  local. That server part needs Tools -> Server changes on.

  ALWAYS-UNREAD SENDERS: right-click a message -> "Always keep
  this sender unread". Their mail stays bold/unread while it sits
  in an Inbox, so it keeps standing out until you deal with it.

SETTINGS
--------
  Window size, last-selected folder, sort column and the
  per-account auto-check intervals are remembered automatically
  between sessions. Everything this program stores lives in ONE
  folder next to the program: Helpfiles/Freemail/ (settings.json,
  Accounts/, Cache/, Drafts/, …). The log alone stays in
  Helpfiles/0---Empty/Freemail.log. Data from an older version is
  moved into Helpfiles/Freemail/ automatically the first time you
  run this one.

ACCOUNTS
--------
  Accounts menu → Add Gmail account / Remove account.
  Removing an account only forgets it inside F(re)email —
  nothing on Gmail is touched. Each account is fetched
  independently; "All Accounts" merges them by date.

SENDING: UNDO SEND AND SEND LATER
---------------------------------
  Everything you send goes through an OUTBOX, which is what
  makes both of these possible.

  Undo send (Tools → Sending) is ON by default and holds each
  message for 10 seconds. A small window appears in the bottom-
  right corner with a Cancel button — one click and the message
  comes straight back to you in a compose window, untouched.
  The delay can be anything from 5 seconds to 10 minutes, and a
  live countdown can be switched on (it is off by default).

  Send later (the 🕒 button in the compose window) queues the
  message for a chosen time: in 5 minutes, tonight, tomorrow
  morning, next Monday, or any date and time you type.

  File → Outbox shows everything waiting: send it now, change
  the time, edit it again, or remove it. Queued mail survives a
  restart — but F(re)email must be RUNNING when the time comes,
  so a message scheduled for 07:00 needs the program open then.
  A failed send stays in the outbox with its error message; it
  is never silently thrown away.

SEND AND SAVE — THE MAIL YOU CANNOT LOSE
----------------------------------------
  ✉🔒 Send and save is the third Send button. It sends the
  message exactly like the ordinary one — same outbox, same
  10-second undo window — and PROTECTS the copy that lands in
  Sent.

  Protected means two things, and deliberately nothing else:

    • Tick forty rows in Sent and press Delete, and the
      protected ones are simply not in the batch. No popup per
      message; the status bar says how many were left behind.
    • Delete a protected message ON ITS OWN and you are asked
      first, with "Keep it" as the answer that Enter and Escape
      both give. Only "Delete it anyway" removes it, and even
      that still goes to the Trash with the usual Undo button.

  So the only way to lose one is to pick it out by hand and
  answer a question — which is the whole point.

  A padlock 🔒 marks protected messages in the list and in the
  reading pane, so you see it BEFORE you tick the row.

  Any message can be protected afterwards, not just ones you
  sent: right-click → 🔒 Protect. The same menu has 🔓 Unprotect.

  The mark travels with the message itself (an
  X-Freemail-Protected header), so it survives a reinstall, a
  second machine, and any rule that moves the mail somewhere
  else — none of which a note on this computer would survive.
  Protection is F(re)email's own, though: Gmail's web interface
  and your phone know nothing about it and will delete a
  protected message like any other.

SIGNATURES (Accounts → Signatures)
----------------------------------
  Signatures have names, and each account is assigned one. Two
  or more accounts can use the SAME signature — edit it once and
  every account that points at it follows. The signature is
  added after a "-- " line, and it is swapped automatically if
  you change the From: account while writing.

DRAFTS — NOTHING IS EVER LOST
-----------------------------
  Every compose window saves itself to Helpfiles/Freemail/Drafts
  a couple of seconds after you stop typing, so a crash or a power cut
  costs you at most those seconds. Unsent drafts are offered
  back the next time you start. Closing a half-written message
  asks whether to keep it. A draft whose message was actually
  sent is kept a short while (10 minutes by default, Tools →
  Sending) and then deleted by itself.

  Your unsent drafts also APPEAR in the Drafts folder, at the
  top, marked "✎ Draft (on this computer)" — they are on your
  own disk, not on Gmail. Open one and the reading pane offers
  "✎ Continue writing" and "🗑 Throw this draft away". They show
  instantly, with no waiting, because there is nothing to fetch.

  The Drafts badge counts MESSAGES, not unread ones. Gmail leaves
  drafts unflagged, so the old unread-based count sat on "(2)"
  for ever even when the folder was empty — and came back a few
  seconds after opening the folder cleared it.

FORGOTTEN ATTACHMENT
--------------------
  If you write that you are attaching something — "attached",
  "enclosed", "bifogar", "bilaga", or a sending verb and a file
  word on the same line — but there is no attachment, you get
  one question before the message leaves. Quoted text and
  anything below your signature is ignored.

TEMPLATES (Tools → Templates)
-----------------------------
  Reusable texts, inserted from the 📄 Template button while
  composing. Subject and body accept the same {tokens} as the
  attachment rules, filled in from the message you are replying
  to.

OFTEN-USED TEXT (the ➕ row above the writing area)
--------------------------------------------------
  For the things that go in SEVERAL messages but not all of
  them: your mail address, payment details, a sign-off. New
  message, Reply, Forward and Note all have the row.

      ➕ Add 1     one click, drops in the text you gave it
      ➕ Add 2     the same, for a second one
      ➕ Add ▾     a list of everything you have saved

  The text goes in at the CURSOR, in the middle of whatever you
  are already writing — that is the difference from a Template,
  which starts a whole message and fills the Subject too.

  TO PUT SOMETHING ON A BUTTON
    Tools → Snippets… (or click an empty "Add 1", or right-click
    either button). Give it a name — that is what the button
    will say — type the text, and tick "button 1" or "button 2".
    A button holds one text, so assigning a second one to
    button 1 takes the first one off it. Everything saved stays
    in the ▾ list whether or not it is on a button, and the
    list marks them ① and ②.

  WHAT GOES IN, EXACTLY
    The text is inserted as you typed it, newlines and all — so
    put the blank lines you want into the snippet itself. The
    one thing added is a SPACE, when the text would otherwise
    run straight into the word beside it ("…tillissusbarn@" →
    "…till issusbarn@"). Untick "Add a space if it would run
    into the word next to it" for a snippet that must go in
    completely verbatim. A snippet that starts or ends with a
    newline is treated as a block and never gets a space.

  Renaming or deleting one updates the buttons straight away,
  even in a compose window that is already open, and deleting
  the text a button pointed at leaves that button empty rather
  than pointing at nothing. Saved in Helpfiles/Accounts/
  snippets.json, and included in Backup and in a migration.

THE SEARCH WINDOW (🔎… button, or Ctrl+Shift+F)
------------------------------------------------
  A window of its own. The main window stays completely
  usable beside it — change folder, read mail, reply — and
  Escape steps back to the mailbox instead of closing it.

  The results are YOUR FOLDER TREE, not a flat list. Account,
  then folder, and a folder only appears if something in it
  matched. So the answer to "where did that receipt end up?"
  is on screen, instead of a list of hits with no sense of
  where they live. Click a folder to open or fold it.

  LOOK IN — tick any combination:
    Subject · Sender · To / Cc · Message text
  Each has its own colour, and every hit carries a small
  coloured chip for each part that matched it. So a mail found
  by its subject looks different from one found deep in the
  text, at a glance. Your choices are remembered.

  Folders are searched one at a time and every account at once,
  so results start appearing immediately rather than after the
  whole thing has finished. "Stop" keeps whatever was found.

  WHAT YOU CAN DO WITH A HIT
    📂 Open it        Jumps the MAIN window to the folder the
                      message really lives in and opens it
                      there (double-click does the same)
    📁 Move to…       For something filed in the wrong place
    🔒 Protect that   Protects the folder it is in, so no rule
       folder         can move it out again
    ✕ Exclude         Takes that hit out of the results — the
                      message is not touched in any way, it
                      just stops cluttering the list. Excluding
                      hides the ROW you clicked; the same
                      message under a different label stays.
                      "✕ exclude these" on a folder does a
                      whole folder at once, and "↺ Bring back
                      all" restores everything.

  Only headers are downloaded, so searching every folder of
  every account is quick and costs almost nothing. The body is
  fetched if you open one, exactly as everywhere else.

SEARCH — ONE FOLDER, OR ALL OF THEM
-----------------------------------
  The drop-down next to the search box chooses the scope:
    This folder            — instant filter of what is loaded
    All folders            — real IMAP search of the whole
                             mailbox (Inbox, Sent, Spam, Trash…)
    All folders + accounts — the same, across every account
    All except…            — every folder of every account,
                             YOUR OWN LABELS INCLUDED, minus what
                             you left out
  The wide scopes ask the server, so they find mail that was
  never downloaded. Results are listed with the folder each hit
  lives in. Searching is read-only, like everything else in
  Phase 1.

  "All except…" is the one that goes everywhere. The other wide
  scopes only walk the six standard folders, so a big archive of
  your own — 0---Frakt & kvitto, say — was never in them to
  begin with. This one searches it too, unless you say not to.

  Tools → "Search: what to leave out…" is where you say not to.
  Tick a folder to keep it out of the search, or tick a whole
  account. Nothing else changes: a folder left out of searching
  is still fetched, still filtered, still in the sidebar with
  its unread count. The search WINDOW (Ctrl+Shift+F) honours the
  same list while its "Skip what I left out" box is on, and that
  box has a ⚙ Choose… button straight to the list.

A FOLDER THAT READS ITSELF  (right-click any folder)
----------------------------------------------------
  "Mail that lands in X reads itself (no alert, no count)".
  For the folder a rule files receipts into: the mail is
  fetched, filed, and marked read straight away — no new-mail
  popup, no "(N)" next to the folder, nothing to dismiss.

  It belongs to the FOLDER, not to the rule. Any number of rules
  may aim at the same receipt folder, and something you drag
  there by hand behaves the same way. Sub-folders can be done in
  one go from the same menu.

  With Tools → Server changes ON it also sets the read flag on
  Gmail, so your phone stops showing them as new. That flag is
  only ever ADDED — nothing here can make a message unread
  again on the server.

  The folder is NOT hidden and its mail is not touched in any
  other way. Open it and everything is there, in order.

IF IT SITS ON "UPDATING…"  (and the rules seem asleep)
------------------------------------------------------
  Look at the status line at the bottom. An account that has
  stopped answering is named there — "… not answering, trying
  again in 2 min" — and automatic checks skip it for a while
  instead of spending a 30-second timeout on it every minute.
  Its mail stays on screen exactly as it was.

  Pressing ↻ Refresh, or opening a folder yourself, always
  tries every account again and clears the stand-down. So if
  you think an account is fine now, just refresh.

MAIL FILTERS (Tools → Mail filters)
-----------------------------------
  Rules that run on every fetched message in every folder.
  Match on sender, receiving account, subject, body, folder, or
  "has attachment", then choose what happens:
    • tint the row a colour        • star it
    • mark it read here           • hide it from the list
    • snooze it automatically     • always/never notify
  All actions are LOCAL. Moving or deleting on Gmail itself is
  Phase 2 and is deliberately not offered here.

BACKUP THAT REALLY RESTORES  (File → Export / Restore)
------------------------------------------------------
  "Export mail to a file…" writes the messages loaded in the
  folder you are looking at into ONE .zip you can keep
  anywhere — another disk, a stick, a cupboard.

  Inside it: each message exactly as it arrived, plus what the
  message itself does not carry — its date, whether it was read
  or starred, and every label it had. That is what makes a
  restore put things back the way they were rather than
  dumping a year of mail stamped "today" and all unread.

  "Restore mail from a file…" puts it back. Before uploading
  anything it ASKS THE SERVER, message by message, whether it
  already has it — and skips everything that is still there.

  So it is safe to run twice. Restore a year-old backup over a
  mailbox you have kept using and the only thing that happens
  is that what is genuinely missing comes back. Nothing is
  duplicated, and nothing already on Gmail is touched.
  "🔍 Check first" does all the looking and uploads nothing,
  so you can see what a restore would do before it does it.

  Restoring only ever ADDS. It never moves, changes or deletes
  anything on Gmail.

  One honest limit: Gmail decides for itself which messages
  form a conversation, so a restored message may end up in a
  thread of its own. Every message is there — the grouping may
  just look different.

TIDY DRAFTS  (File → Tidy drafts…)
----------------------------------
  Finds unsent drafts whose message has, in fact, already gone
  out — because you finished it on your phone, or it was sent
  before this program started keeping track.

  It reads your Sent folder and only pairs a draft with a sent
  message when the subject matches (ignoring Re:/Sv:/Fwd: and
  capitals), at least one recipient is the same, AND the sent
  copy is not older than the draft. A draft with no subject or
  no recipient is never matched — too risky.

  Each match is shown with the reason it was matched, and
  nothing is deleted until you tick it and confirm. The sent
  messages are never touched.

WHERE IS THIS MESSAGE?  (right-click a message)
-----------------------------------------------
  Finds every copy of it — every folder, every one of
  your accounts — and lists the Gmail labels it carries.

  On Gmail a message does not sit IN a folder; it wears
  labels. So "in three places at once" is normal and still
  means one message. If you also copy mail between accounts,
  this is what tells you which mailbox you are looking at.

  Read-only: it only looks.

RULE HEALTH  (Tools → Rule health)
----------------------------------
  How much each rule is really doing: how often it has fired,
  when it last fired, and how many of the messages loaded in
  front of you it matches right now.

  For a rule that is catching nothing, it says WHICH condition
  is to blame — including the case where a whole either/or
  section is the problem, which is easy to miss because
  removing any single row of it changes nothing.

  One button drops the offending condition, after showing you
  exactly which rows it will remove and how many messages the
  rule would then match. Everything else about the rule stays
  as it was, and no mail is touched until the rule next runs.

  Open the folder you EXPECT a rule to catch before coming
  here — that is the mail it is judged against.

LONG RECIPIENT LISTS
--------------------
  A circular sent to fifty people used to put a screenful of
  strangers' addresses between you and the message. Above five
  recipients the To:/Cc: line folds to one line; click
  "▾ show all" to open it.

  Right-click that line to change the threshold, to turn
  folding off entirely, or to say "never show recipients from
  this sender" for a list that does it every time.

STORAGE  (Tools → Storage)
--------------------------
  What this program is using on disk, folder by folder.

  Two things grow without limit: the message cache (offline
  copies, which refill themselves from Gmail) and the Deleted
  archive (local copies of mail you erased from the Trash).
  Both can be trimmed here — the cache by age or entirely, the
  Deleted archive by how many days to keep. Your accounts,
  rules and contacts are never touched.

FOLDERS — RIGHT-CLICK ONE
-------------------------
  Right-clicking any folder in the sidebar offers:

    Show only when expanded   Hide it while the account is
                              collapsed (a small · marks it)
    Mark everything as read   The whole folder, on the server
    Don't show an unread      No (N) badge and nothing added to
    count                     the taskbar total; its mail still
                              shows as unread when you open it
    …and its sub-folders      The same, for the folder and
                              everything beneath it in one go
    🔒 Protect                See below
    📁 New folder inside…     Make a sub-folder
    📅 Month folders in…      See below
    Delete the folder         Custom folders only. On Gmail a
                              folder IS a label, so this removes
                              the label — the mail stays in All
                              Mail

MONTH FOLDERS (right-click → 📅 Month folders in…)
--------------------------------------------------
  Makes one folder per month inside the folder you clicked.
  Choose the naming:

    01, 02, 03 …          short, but next January's 01 lands
                          in the same place as this one
    2026-01, 2026-02 …    sorts correctly for ever
    2026 / 01, 02 …       a folder per year, months inside

  Say how many months forward, and how many back, and the
  preview shows exactly what will be made. A folder that
  already exists is left completely alone — nothing is ever
  overwritten or emptied.

  Filing has its own right-click entry too — "📅 File the mail
  in X into its month folders…" — because creating the folders
  is a once-a-year job and filing is the bit you repeat. You do
  not have to have the folder open: it reads it itself, makes
  any month folder that is missing, and skips whatever has
  already been filed.

  A rule will NOT pull month-filed mail back out again. A move
  to where a message already is — or to the parent of where it
  now sits — is refused, and the reason is written to the log.

  "Create, then file what is here" also goes through the mail
  currently in that folder and moves each message into the month
  ITS OWN date falls in — so a receipt that arrived on the 1st
  for something bought on the 31st lands in the right month. You
  see the whole plan and confirm before anything moves.

PROTECTING A FOLDER (right-click → 🔒 Protect)
----------------------------------------------
  Once mail has been filed where it belongs, another rule
  picking it up and moving it on again is what turns finding a
  receipt into a hunt. A protected folder refuses that.

  While a folder is protected:
    • NO rule may move mail out of it, and no rule may trash
      mail in it — whatever the rule says, now or later.
    • Mail can still ARRIVE. A rule may still file things INTO
      it; protection only refuses to take mail back out.
    • YOU can still move it, and you can still delete it. Both
      are things you did on purpose.

  Every refusal is written to the activity log (the 🧾 Log
  button), so a rule that keeps trying is visible rather than
  silent. A 🔒 next to the folder name shows which folders are
  protected.

SNOOZE
------
  ⏰ Notify (the old "Snooze") does NOT hide anything. The mail stays
  exactly where it is; on the day you pick (1 week, 2 months, 1 year,
  "In N weeks/months/years", or an exact date) a pop-up tells you
  "Time to deal with this mail" — Open / Remind me again… / Done.
  It is a one-shot follow-up, so it is also listed in the Follow-ups
  folder and marked 🔔 in the list. If the program was closed at that
  time the pop-up comes when it starts. Purely local: Gmail never
  knows.

DELETE, TRASH & THE DELETED ARCHIVE
-----------------------------------
  Deleting a normal message MOVES it to the Gmail Trash, where
  Gmail keeps it 30 days — you can put it back from any client.

  THE UNDO WINDOW, AND THE ⚡ DO IT BUTTON BESIDE IT
  A delete happens on screen at once and is held back from Gmail
  for a minute (Tools → "Sending & deleting"). Two buttons appear
  at the right of the quick-filter row for as long as that lasts:
    ↺ Undo delete  — take it back; nothing ever reached Gmail
    ⚡ Do it        — stop waiting: send it to Gmail NOW
  The same pair appears while a message is on its way out:
  ✖ Cancel send and ⚡ Send now.

  You can carry on working during the undo window — move mail,
  switch folder, press Refresh, let the auto-check run. A message
  waiting to be deleted stays out of the list however the list is
  rebuilt, so it cannot reappear and then vanish under you, and
  Undo brings it back exactly once. If you have walked to another
  folder in the meantime, Undo restores it where it belongs
  rather than dropping it into the folder you are looking at.

  Deleting a message that is ALREADY in the Trash means "for
  good": it is permanently removed from Gmail. Before that
  happens Freemail saves a hidden LOCAL copy, so a permanent
  delete you regret is not lost. Several at once ask ONCE, not
  once per message.

  Those saved copies live in the "♻ Deleted" folder in the
  sidebar. Right-click one to:
    • Restore to Gmail   — uploads it back to your Inbox
    • Continue           — reply to the sender with it quoted
    • Remove local copy  — drop just this saved copy
  Right-click the Deleted folder (or a message in it) for
  "Empty the Deleted archive" and "Keep deleted copies for N
  days" (default 30; 0 = keep forever). Old copies are pruned
  automatically at start-up.

  Permanent delete and Restore both need Tools -> Server changes
  switched on (Freemail asks and can turn it on for you).

NEW-MAIL NOTIFICATIONS (Tools → Notifications)
----------------------------------------------
  When a background auto-check finds mail you have not seen, a
  small window appears in the bottom-right corner with sender
  and subject. Click it to open the message. Pressing Refresh
  yourself never pops anything up. A sound can be enabled.

PHISHING WARNING
----------------
  Every opened message is checked for the classic tells:
    • a display name showing a different address than the real
      sender
    • Reply-To pointing at another domain than From
    • a link whose TEXT says one domain while it GOES to another
    • links to raw IP addresses or punycode (xn--) look-alikes
    • executable or double-extension attachments ("bill.pdf.exe")
    • urgency/password wording next to a link
    • DKIM/SPF/DMARC failures reported by the server
  A red banner explains exactly what was found. Nothing is
  hidden, moved or deleted — you decide.

  If a sender keeps triggering it wrongly, click "✔ Not
  phishing — trust this sender" in the banner. That silences
  the heuristics for that exact address (not the whole domain)
  — EXCEPT warnings about executable or disguised attachments,
  which are never silenced: if a trusted sender's account is
  taken over, that is the one warning you need. Undo it under
  Tools → Blocked & trusted senders.

ATTACHMENT SIZE
---------------
  While composing you see the total size of your attachments
  and what they will weigh once encoded for sending (about
  37 % more). It turns amber near Gmail's 25 MB limit and red
  above it, and pressing Send checks it before the message is
  queued — with "send later" a rejection would otherwise reach
  you hours afterwards. Files that have been moved or deleted
  since you attached them are reported as well.

UNSUBSCRIBE
-----------
  A newsletter shows an "Unsubscribe…" button right under the
  subject — always, not only when the message-actions strip is
  switched on. Next to it, "Links (N)…" lists every link the
  message has, including the ones that exist only inside the
  HTML and cannot be clicked in the text view.

  You pick HOW:
    * One click — no page, no browser. Offered when the sender
      ships the RFC 8058 header, which is them saying "one
      request to this address is enough". F(re)email sends
      exactly that and tells you what came back.
    * Open the page HERE, in F(re)email's own mini view: the
      page's text and its buttons as real controls. No
      JavaScript, no images, no cookies kept afterwards, and
      your real browser and its logins are never involved.
      Nothing is sent until you press one of the page's own
      buttons, and "Show exactly what will be sent" prints the
      literal name=value pairs first. If the page needs
      JavaScript it says so and hands you a button through to
      the real browser.
    * Open the page in your real browser (the old behaviour).
    * Send an unsubscribe e-mail, through the outbox like any
      other message you send.

  …and WHAT ELSE should happen: nothing, block the sender,
  mark it spam locally, or open the filter editor.

  FROM A RULE. A filter can unsubscribe from what it catches —
  set "Unsubscribe" in the rule editor, next to the junk
  actions. "Collect them for me" contacts nobody: matching mail
  goes on a list you clear in one pass (Tools ▸ Unsubscribes
  waiting), so the rule that trashes a newsletter can also get
  you off it. "Do it automatically" needs no confirmation, but
  only ever uses a route the SENDER declared in a header — a
  link merely found in the message text is never followed
  unattended and goes on the waiting list instead.

  Either way, a list you have already left is never asked
  twice: Tools ▸ Unsubscribe log is what remembers, and it is
  why a rule does not re-fire on the stragglers that keep
  arriving for a few days afterwards.

  An unsubscribe link is also a way for a sender to confirm
  that your address is live. For real spam, block and trash it
  instead — never ask a spammer to stop.
  Blocked senders can be reviewed in Tools → Blocked senders.

SAVE AS PDF
-----------
  Any open message can be written to a real PDF file from the
  reading pane or File → Save message as PDF. No extra software
  is needed.

BACKUP (File → Backup)
----------------------
  One .zip with every setting, account, rule, signature,
  template, contact and unsent draft. App passwords stay
  encrypted inside it, and can only be decrypted again by the
  same Windows user on the same machine — restoring elsewhere
  restores everything except the passwords. Automatic backup on
  exit can be switched on, keeping the last N files. Restore
  backs up the current state first.

DEFAULT MAIL CLIENT (Tools → Set as default mail client)
--------------------------------------------------------
  Registers F(re)email as a mailto: handler under your own
  Windows user account. Windows 11 does not allow a program to
  make itself the default, so the Default apps page opens
  afterwards for you to finish the job. After that, clicking an
  e-mail address anywhere in Windows opens a compose window
  here, prefilled. "Unregister" removes every key again.

CALENDAR (📅 toolbar button, Ctrl+K, or the Calendar menu)
----------------------------------------------------------
  Three views, switched at the top:
    Month  — the overview. Click a day to select it, double-
             click to create an event there, "+N more" opens
             that day in the week view.
    Week   — one column per day, with times and places.
    Agenda — everything coming up in the next 60 days as one
             list. 🔔 marks an event with a reminder, 🔁 one
             that repeats.
  ◀ / Today / ▶ move a month, a week or 30 days depending on
  the view; the arrow keys do the same.

  AN EVENT can have a title, place, notes, a colour, repetition
  and any number of reminders:
    Repeat  — daily / weekly / monthly / yearly, "every 2nd",
              weekly on chosen weekdays, ending never, after N
              times, or on a date.
    Remind  — at the time, 5/15/30 minutes, 1/2 hours, 1/2 days
              or a week before. Tick as many as you want.
  All-day events hide the clock fields, and an event can span
  several days via the End date field.

  REMINDERS appear in the bottom-right corner with Snooze
  (5 min / 15 min / 1 h) and Dismiss. They do not steal the
  keyboard. A reminder that has been shown is not shown again
  after a restart; one that fell due while the program was
  closed still appears if it is less than an hour old.
  IMPORTANT: like scheduled sending, reminders need F(re)email
  to be RUNNING. There is no background service.

  INVITATIONS BY MAIL: a message carrying a meeting invitation
  shows "📅 Add to calendar" in the reading pane — it reads the
  invitation (time, place, repetition, its own alarms) and opens
  the editor so you can add your reminder before saving. Any
  other message shows "📅 Make appointment" instead, which
  starts an event from its subject, date and text.

  .ICS FILES can be imported and the whole calendar exported,
  so events move to and from Thunderbird, Outlook or Google
  Calendar by file. Re-importing the same invitation does not
  create a duplicate. There is deliberately no CalDAV/Google
  sync: that would mean writing to a server, which Phase 1 does
  not do. The calendar is included in the backup.

KEYBOARD
--------
  N / Ctrl+N  New message        T / Ctrl+T  New note
  R           Reply
  K / Ctrl+K  Calendar
  Click +/−   Open or close a conversation
  F           Forward            F5 Refresh
  Delete      Hide from view (Phase 1: local only)
  F1          Help               ESC Close a dialog
  In Smart Reply: Ctrl+Down / Ctrl+Up move between paragraphs.

LOG FILE
--------
  If something goes wrong, a diagnostic log is saved at:
  Helpfiles/0---Empty/Freemail.log

Press ESC to close this window.
"""

def _show_help(root):
    top = tk.Toplevel(root)
    top.title("F(re)email — Help")
    top.configure(bg=C_BG2)
    _center_over(top, root, 580, 540)
    top.transient(root)
    top.grab_set()
    top.focus_force()
    top.bind("<Escape>", lambda e: top.destroy())

    tk.Label(top, text="F(re)email — Help", bg=C_BG1, fg=C_ACCENT,
             font=("Segoe UI", 13, "bold"), pady=8).pack(fill="x")

    frm = tk.Frame(top, bg=C_BG2)
    frm.pack(fill="both", expand=True, padx=8, pady=6)

    sb = tk.Scrollbar(frm, bg=C_BG3, troughcolor=C_BG1)
    sb.pack(side="right", fill="y")

    t = tk.Text(frm, bg=C_BG2, fg=C_FG, relief="flat",
                font=("Consolas", 9), wrap="word", state="normal",
                yscrollcommand=sb.set, padx=8, pady=6,
                insertofftime=0, insertontime=9999999)
    no_blink(t)
    sb.configure(command=t.yview)
    t.pack(fill="both", expand=True)
    t.insert("1.0", _HELP_TEXT.strip())
    t.configure(state="disabled")

    _bind_mousewheel(t, None)

    tk.Button(top, text="Close", bg=C_BTN_STD, fg=C_BTN_FG,
              relief="flat", padx=20, pady=4,
              command=top.destroy).pack(pady=8)



class RelocatorWindow(tk.Toplevel):
    """⤴ The Mail Relocator — the rules, a ▶ beside each, and ▶▶ for the lot.

    Deliberately NOT modal: it is a workbench, and he wants to look at the
    mail list while he decides. Deliberately NOT automatic: nothing here ever
    runs on a fetch or a timer, which is the whole difference from filters."""

    def __init__(self, app):
        super().__init__(app.root)
        self.app = app
        self.title("Mail Relocator")
        self.configure(bg=C_BG3)
        self.store = _load_reloc()
        self.rules = self.store["rules"]
        self._rows = {}            # index → (count label, run button)
        self._busy = False
        _center_over(self, app.root, 900, 620)
        self.transient(app.root)
        self.bind("<Escape>", lambda e: self.destroy())
        self._build()
        self._render()
        self.focus_force()

    # ── layout ────────────────────────────────────────────────────────────
    def _build(self):
        head = tk.Frame(self, bg=C_BG1)
        head.pack(fill="x")
        tk.Label(head, text="⤴  Mail Relocator", bg=C_BG1, fg=C_ACCENT,
                 font=("Segoe UI", 13, "bold")).pack(side="left", padx=12,
                                                     pady=8)
        tk.Label(head, text="move mail where it belongs — only when you "
                            "press the button",
                 bg=C_BG1, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left", pady=8)
        tk.Button(head, text="＋  New rule", bg=C_BTN_NEW, fg=C_BTN_FG,
                  font=("Segoe UI", 9, "bold"), relief="flat", cursor="hand2",
                  padx=10, pady=3,
                  command=self._new_rule).pack(side="right", padx=(4, 10),
                                               pady=6)

        tk.Label(self,
                 text="This is not the filter engine. Filters run on every "
                      "fetch and see only the mail already downloaded; the "
                      "Relocator runs when you say so and asks Gmail itself, "
                      "so it reaches years of mail. Pressing ▶ SEARCHES "
                      "first and shows you the count and the destination "
                      "before anything moves.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 wraplength=850, justify="left",
                 anchor="w").pack(fill="x", padx=14, pady=(8, 4))

        # Bottom first — an expanding list would otherwise leave these 1 px
        # tall (the packer trap this family of programs keeps meeting).
        self._status = tk.Label(self, text="", bg=C_BG3, fg=C_FG_DIM,
                                font=("Segoe UI", 9), anchor="w",
                                wraplength=860, justify="left")
        self._status.pack(side="bottom", fill="x", padx=14, pady=(0, 10))

        bot = tk.Frame(self, bg=C_BG3)
        bot.pack(side="bottom", fill="x", padx=12, pady=(0, 4))
        self._ask = tk.BooleanVar(
            value=bool(self.app.cfg.get("reloc_confirm", True)))
        tk.Checkbutton(bot, text="Ask before running everything",
                       variable=self._ask, bg=C_BG3, fg=C_FG_DIM,
                       selectcolor=C_BG2, activebackground=C_BG3,
                       activeforeground=C_FG, font=("Segoe UI", 8),
                       highlightthickness=0,
                       command=self._save_ask).pack(side="left")
        tk.Button(bot, text="Close", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=14, pady=4,
                  command=self.destroy).pack(side="right", padx=4)
        self._btn_all = tk.Button(
            bot, text="▶▶  Run every ticked rule", bg=C_BTN_NEW, fg=C_BTN_FG,
            font=("Segoe UI", 9, "bold"), relief="flat", cursor="hand2",
            padx=12, pady=4, command=self._run_all)
        self._btn_all.pack(side="right", padx=4)
        self._btn_count = tk.Button(
            bot, text="🔍  Count them all", bg=C_BTN_STD, fg=C_BTN_FG,
            font=("Segoe UI", 9), relief="flat", cursor="hand2",
            padx=12, pady=4, command=self._count_all)
        self._btn_count.pack(side="right", padx=4)
        add_tooltip(self._btn_count,
                    "Read-only. Asks Gmail how many messages each ticked "
                    "rule would move, and moves nothing.")

        # The scrolling rule list.
        wrap = tk.Frame(self, bg=C_BG3)
        wrap.pack(fill="both", expand=True, padx=12, pady=(4, 6))
        sb = tk.Scrollbar(wrap, bg=C_BG3, troughcolor=C_BG1)
        sb.pack(side="right", fill="y")            # before the canvas
        self._canvas = tk.Canvas(wrap, bg=C_BG3, highlightthickness=0,
                                 yscrollcommand=sb.set)
        self._canvas.pack(side="left", fill="both", expand=True)
        sb.configure(command=self._canvas.yview)
        self.body = tk.Frame(self._canvas, bg=C_BG3)
        self._win = self._canvas.create_window((0, 0), window=self.body,
                                               anchor="nw")
        self.body.bind("<Configure>", lambda e: self._canvas.configure(
            scrollregion=self._canvas.bbox("all")))
        self._canvas.bind("<Configure>", lambda e: self._canvas.itemconfigure(
            self._win, width=e.width))
        # The shared wheel dispatcher, never bind_all of our own: bind_all is
        # application-wide whichever window calls it, so a private one here
        # would scroll this list while the mouse was over the MESSAGE list.
        _bind_mousewheel(self.body, self._canvas)

    # ── the rows ──────────────────────────────────────────────────────────
    def _render(self):
        for w in self.body.winfo_children():
            w.destroy()
        self._rows.clear()
        if not self.rules:
            tk.Label(self.body,
                     text="No rules yet.\n\nA rule says “this mail, from "
                          "these folders, belongs THERE”.\nStart from one of "
                          "these, or make an empty one:",
                     bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 10),
                     justify="left").pack(anchor="w", pady=(10, 12), padx=6)
            for label, maker in (
                    ("⤴  Shipping receipts  →  a receipts folder",
                     self._starter_shipping),
                    ("⤴  One sender  →  a folder of their own",
                     self._starter_sender),
                    ("⤴  Everything older than a year  →  an archive folder",
                     self._starter_old),
                    ("🗑  Delete what matches, after two days",
                     self._starter_delete),
                    ("＋  Empty rule — I'll fill it in myself",
                     self._new_rule)):
                tk.Button(self.body, text=label, bg=C_BG2, fg=C_FG,
                          anchor="w", relief="flat", cursor="hand2",
                          activebackground=C_BG4, activeforeground=C_FG,
                          padx=12, pady=7,
                          command=maker).pack(fill="x", pady=3, padx=6)
            self._btn_all.configure(state="disabled")
            self._btn_count.configure(state="disabled")
            return
        self._btn_all.configure(state="normal")
        self._btn_count.configure(state="normal")
        for i, r in enumerate(self.rules):
            self._render_row(i, r)

    def _render_row(self, idx, r):
        on = bool(r.get("enabled", True))
        row = tk.Frame(self.body, bg=C_BG2, padx=8, pady=6)
        row.pack(fill="x", pady=2, padx=2)

        var = tk.BooleanVar(value=on)

        def _toggle(i=idx, v=var):
            self.rules[i]["enabled"] = bool(v.get())
            _save_reloc(self.store)
            self._render()

        # fg matters: the tick is drawn in the FOREGROUND colour and the
        # default black on a dark indicator is invisible — an enabled rule
        # then looks switched off.
        tk.Checkbutton(row, variable=var, bg=C_BG2, activebackground=C_BG2,
                       fg=C_FG, activeforeground=C_FG, selectcolor=C_BG1,
                       highlightthickness=0,
                       command=_toggle).pack(side="left")

        right = tk.Frame(row, bg=C_BG2)
        right.pack(side="right")
        cnt = tk.Label(right, text="", bg=C_BG2, fg=C_FG_DIM, width=13,
                       anchor="e", font=("Segoe UI", 9))
        cnt.pack(side="left", padx=(0, 8))
        run = tk.Button(right, text="▶  Run", bg=C_BTN_NEW, fg=C_BTN_FG,
                        font=("Segoe UI", 9, "bold"), relief="flat",
                        cursor="hand2", padx=10, pady=2,
                        state=("normal" if on else "disabled"),
                        command=lambda i=idx: self._run_one(i))
        run.pack(side="left")
        tk.Button(right, text="✎", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=8, pady=2,
                  command=lambda i=idx: self._edit(i)).pack(side="left",
                                                            padx=(4, 0))
        tk.Button(right, text="🗑", bg=C_BTN_DEL, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=8, pady=2,
                  command=lambda i=idx: self._delete(i)).pack(side="left",
                                                              padx=(4, 0))

        left = tk.Frame(row, bg=C_BG2)
        left.pack(side="left", fill="x", expand=True, padx=(6, 0))
        tk.Label(left, text=r.get("name") or "(unnamed rule)", bg=C_BG2,
                 fg=(C_FG if on else C_FG_DIM),
                 font=("Segoe UI", 10, "bold"), anchor="w").pack(anchor="w")
        tk.Label(left, text=_reloc_describe(r), bg=C_BG2, fg=C_FG_DIM,
                 font=("Segoe UI", 8), anchor="w", justify="left",
                 wraplength=560).pack(anchor="w")
        self._rows[idx] = (cnt, run)

    # ── plumbing ──────────────────────────────────────────────────────────
    def _save_ask(self):
        self.app.cfg["reloc_confirm"] = bool(self._ask.get())
        _save_settings(self.app.cfg)

    def _set_busy(self, on, text=""):
        self._busy = on
        if text:
            self._status.configure(text=text)
        state = "disabled" if on else "normal"
        for b in (self._btn_all, self._btn_count):
            try:
                b.configure(state=state)
            except Exception:
                pass
        for idx, (cnt, run) in self._rows.items():
            try:
                run.configure(
                    state="disabled" if (on or not
                                         self.rules[idx].get("enabled", True))
                    else "normal")
            except Exception:
                pass

    def _say(self, text):
        try:
            self.app.root.after(0, lambda t=text: self._status.configure(text=t)
                                if self.winfo_exists() else None)
        except Exception:
            pass

    def _ticked(self):
        return [i for i, r in enumerate(self.rules) if r.get("enabled", True)]

    # ── count (read-only) ─────────────────────────────────────────────────
    def _count_all(self):
        idxs = self._ticked()
        if not idxs:
            self._status.configure(text="No rule is ticked.")
            return
        if self.app._demo_mode:
            self._need_account()
            return
        self._set_busy(True, "Asking Gmail…")
        for i in idxs:
            self._rows[i][0].configure(text="counting…", fg=C_FG_DIM)
        rules = [dict(self.rules[i]) for i in idxs]

        def worker():
            got = {}
            for i, r in zip(idxs, rules):
                msgs, notes, probs = self.app._reloc_find(r, progress=self._say)
                got[i] = (len(msgs), probs)
            self.app.root.after(0, lambda: self._counted(got))
        threading.Thread(target=worker, daemon=True).start()

    def _counted(self, got):
        if not self.winfo_exists():
            return
        total = 0
        for i, (n, probs) in got.items():
            total += n
            cnt = self._rows.get(i, (None, None))[0]
            if cnt is None:
                continue
            if probs:
                cnt.configure(text="problem", fg="#e0a030")
            elif n:
                cnt.configure(text=f"{n} message{'s' if n != 1 else ''}",
                              fg=C_ACCENT)
            else:
                cnt.configure(text="nothing", fg=C_FG_DIM)
        self._set_busy(False,
                       f"{total} message(s) are waiting to be moved."
                       if total else "Nothing to move right now.")

    # ── run ───────────────────────────────────────────────────────────────
    def _need_account(self):
        messagebox.showinfo(
            "Mail Relocator",
            "The Relocator searches your real mailbox on Gmail, so it needs "
            "an account.\n\nAccounts → Add Gmail account…", parent=self)

    def _run_one(self, idx):
        if self.app._demo_mode:
            self._need_account()
            return
        rule = dict(self.rules[idx])
        nm = rule.get("name") or "this rule"
        self._set_busy(True, f"Searching for “{nm}”…")
        self._rows[idx][0].configure(text="searching…", fg=C_FG_DIM)

        def worker():
            msgs, notes, probs = self.app._reloc_find(rule, progress=self._say)
            self.app.root.after(
                0, lambda: self._found_one(idx, rule, msgs, notes, probs))
        threading.Thread(target=worker, daemon=True).start()

    def _found_one(self, idx, rule, msgs, notes, probs):
        if not self.winfo_exists():
            return
        cnt = self._rows.get(idx, (None, None))[0]
        if cnt is not None:
            cnt.configure(text=(f"{len(msgs)} message"
                                f"{'s' if len(msgs) != 1 else ''}")
                          if msgs else "nothing",
                          fg=(C_ACCENT if msgs else C_FG_DIM))
        if probs and not msgs:
            self._set_busy(False, "Problem: " + " · ".join(probs[:3]))
            return
        if not msgs:
            self._set_busy(False,
                           f"Nothing matches “{rule.get('name') or 'that rule'}”"
                           + ("   ·   " + " · ".join(notes[:2]) if notes else ""))
            return
        self._set_busy(False, f"{len(msgs)} message(s) found.")
        self.app._reloc_confirm_and_move(
            [(rule, msgs)], parent=self, on_done=self._after_move,
            notes=notes, problems=probs)

    def _run_all(self):
        idxs = self._ticked()
        if not idxs:
            self._status.configure(text="No rule is ticked.")
            return
        if self.app._demo_mode:
            self._need_account()
            return
        rules = [dict(self.rules[i]) for i in idxs]
        self._set_busy(True, f"Searching for {len(rules)} rule(s)…")
        for i in idxs:
            self._rows[i][0].configure(text="searching…", fg=C_FG_DIM)

        def worker():
            jobs, allnotes, allprobs = [], [], []
            counts = {}
            for i, r in zip(idxs, rules):
                msgs, notes, probs = self.app._reloc_find(r, progress=self._say)
                counts[i] = len(msgs)
                allnotes.extend(notes)
                allprobs.extend(probs)
                if msgs:
                    jobs.append((r, msgs))
            self.app.root.after(
                0, lambda: self._found_all(counts, jobs, allnotes, allprobs))
        threading.Thread(target=worker, daemon=True).start()

    def _found_all(self, counts, jobs, notes, probs):
        if not self.winfo_exists():
            return
        for i, n in counts.items():
            cnt = self._rows.get(i, (None, None))[0]
            if cnt is not None:
                cnt.configure(text=(f"{n} message{'s' if n != 1 else ''}"
                                    if n else "nothing"),
                              fg=(C_ACCENT if n else C_FG_DIM))
        total = sum(counts.values())
        self._set_busy(False, f"{total} message(s) found.")
        if not jobs:
            self._status.configure(
                text="Nothing to move."
                     + ("   ·   Problems: " + " · ".join(probs[:3])
                        if probs else ""))
            return
        self.app._reloc_confirm_and_move(
            jobs, parent=self, on_done=self._after_move, notes=notes,
            problems=probs, ask=bool(self._ask.get()))

    def _after_move(self, moved, problems):
        if not self.winfo_exists():
            return
        for cnt, _run in self._rows.values():
            cnt.configure(text="", fg=C_FG_DIM)
        self._set_busy(
            False,
            f"{moved} message(s) moved."
            + ("   ·   Problems: " + " · ".join(problems[:3])
               if problems else ""))

    # ── editing ───────────────────────────────────────────────────────────
    def _new_rule(self, prefill=None):
        RelocatorRuleDialog(self, prefill or {}, None)

    def _edit(self, idx):
        RelocatorRuleDialog(self, dict(self.rules[idx]), idx)

    def _delete(self, idx):
        r = self.rules[idx]
        if not messagebox.askyesno(
                "Delete the rule",
                f"Delete “{r.get('name') or '(unnamed rule)'}”?\n\n"
                f"Only the rule goes — no mail is touched.",
                parent=self, default="no"):
            return
        self.rules.pop(idx)
        _save_reloc(self.store)
        self._render()

    def _rule_saved(self, rule, idx):
        if idx is None:
            self.rules.append(rule)
        else:
            self.rules[idx] = rule
        self.store["rules"] = self.rules
        _save_reloc(self.store)
        self._render()

    # ── ready-made starters ───────────────────────────────────────────────
    # ── ready-made starters ───────────────────────────────────────────────
    # "_new_row" is what a starter's own blank row should look like, since the
    # everyday default (Subject / any one of) is not what a rule about ONE
    # SENDER wants to open with.
    def _starter_shipping(self):
        self._new_rule({
            "name": "Shipping receipts → 0---Frakt & Kvitto",
            "enabled": True, "folders": ["Inbox"], "dest_folder": "",
            "conditions": [{"field": "from", "op": "contains",
                            "value": "tradera.com", "group": "all"}],
        })

    def _starter_sender(self):
        self._new_rule({"name": "One sender → their own folder",
                        "enabled": True, "folders": ["Inbox"],
                        "_new_row": {"field": "from", "group": "all"}})

    def _starter_old(self):
        self._new_rule({"name": "Older than a year → archive",
                        "enabled": True, "folders": ["Inbox"],
                        "older_h": 365 * 24, "dest_folder": ""})

    def _starter_delete(self):
        self._new_rule({"name": "Delete these after two days",
                        "enabled": True, "folders": ["Inbox"],
                        "action": "trash", "older_h": 48})


class RelocatorRuleDialog(tk.Toplevel):
    """One Relocator rule: what to look for, where to look, what happens.

    The condition half is built like the filter editor's on purpose (Issu
    2026-08-23: "gör som med filter att jag kan lägga till flera saker") —
    as many rows as you like, each one either a MUST or one of the "any one
    of these will do" alternatives, so "From is Tradera AND the subject is
    any of these three" is one rule instead of three."""

    _FIELDS = (("from", "From"), ("subject", "Subject"), ("body", "Body"),
               ("to", "Account"), ("folder", "Folder"))
    _OPS = ("contains", "not_contains", "is", "is_not", "begins", "ends")
    _GROUPS = (("all", "MUST"), ("any", "any one of"))

    # What a fresh, empty condition row starts as (Issu 2026-08-23: "ändra så
    # att default är Any of + Subject"). It is the row you add most: one more
    # subject line for the same sender, as one more alternative. A starter
    # button can override it through the rule's "_new_row" key.
    _NEW_ROW = {"field": "subject", "op": "contains", "group": "any"}

    def __init__(self, owner: "RelocatorWindow", rule: dict, idx):
        super().__init__(owner)
        self.owner, self.app, self.idx = owner, owner.app, idx
        self._seed = dict(self._NEW_ROW)
        self._seed.update((rule or {}).get("_new_row") or {})
        self.r = _reloc_norm(rule)
        self._cond_rows = []          # [(field, op, value, group, row, pair)]
        self.title("Relocator rule")
        self.configure(bg=C_BG3)
        # Never taller than the screen — a dialog whose buttons are below the
        # bottom edge is a dialog with no buttons (the trap Sell_a_box hit).
        h = min(820, max(520, self.winfo_screenheight() - 120))
        _center_over(self, owner, 760, h)
        self.transient(owner)
        self.grab_set()
        self.bind("<Escape>", lambda e: self.destroy())
        self._build()
        self.focus_force()

    # ── small builders ────────────────────────────────────────────────────
    def _label(self, parent, text):
        tk.Label(parent, text=text, bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 9, "bold"), anchor="w").pack(fill="x",
                                                                pady=(10, 2))

    def _entry(self, parent, value="", width=None):
        e = tk.Entry(parent, textvariable=None, bg=C_BG2, fg=C_FG,
                     relief="flat", insertbackground=C_ACCENT,
                     font=("Segoe UI", 10), insertofftime=0,
                     insertontime=9999999, **({"width": width} if width else {}))
        no_blink(e)
        e.insert(0, value or "")
        return e

    def _option(self, parent, var, choices, width=None, cmd=None):
        om = tk.OptionMenu(parent, var, *choices,
                           **({"command": cmd} if cmd else {}))
        om.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                     activeforeground=C_FG, highlightthickness=0,
                     relief="flat", font=("Segoe UI", 9), anchor="w",
                     **({"width": width} if width else {}))
        om["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                             activeforeground=C_FG)
        return om

    def _build(self):
        tk.Label(self, text="⤴  Relocator rule", bg=C_BG1, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold"), pady=8).pack(fill="x")

        # Buttons first, at the bottom, so an expanding body can never eat
        # them (the packer rule this program keeps re-learning).
        btns = tk.Frame(self, bg=C_BG3)
        btns.pack(side="bottom", fill="x", padx=16, pady=10)
        tk.Button(btns, text="Cancel", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=16, pady=5,
                  command=self.destroy).pack(side="right", padx=4)
        tk.Button(btns, text="Save the rule", bg=C_BTN_NEW, fg=C_BTN_FG,
                  font=("Segoe UI", 9, "bold"), relief="flat", cursor="hand2",
                  padx=16, pady=5,
                  command=self._save).pack(side="right", padx=4)
        self._warn = tk.Label(btns, text="", bg=C_BG3, fg="#e0a030",
                              font=("Segoe UI", 9), anchor="w",
                              wraplength=460, justify="left")
        self._warn.pack(side="left", fill="x", expand=True)

        # Scrollable body — the conditions list has no fixed height.
        wrap = tk.Frame(self, bg=C_BG3)
        wrap.pack(fill="both", expand=True)
        sb = tk.Scrollbar(wrap, bg=C_BG3, troughcolor=C_BG1)
        sb.pack(side="right", fill="y")
        cv = tk.Canvas(wrap, bg=C_BG3, highlightthickness=0,
                       yscrollcommand=sb.set)
        cv.pack(side="left", fill="both", expand=True)
        sb.configure(command=cv.yview)
        b = tk.Frame(cv, bg=C_BG3, padx=16)
        win = cv.create_window((0, 0), window=b, anchor="nw")
        b.bind("<Configure>",
               lambda e: cv.configure(scrollregion=cv.bbox("all")))
        cv.bind("<Configure>", lambda e: cv.itemconfigure(win, width=e.width))
        _bind_mousewheel(b, cv)

        self._label(b, "Name")
        self.e_name = self._entry(b, self.r["name"])
        self.e_name.pack(fill="x", ipady=3)

        # ── What happens ──────────────────────────────────────────────────
        self._label(b, "What this rule does")
        arow = tk.Frame(b, bg=C_BG3)
        arow.pack(fill="x")
        self.v_action = tk.StringVar(value=self.r["action"])
        for val, txt, tip in (
                ("move", "⤴  Move it to…",
                 "A real Gmail move: the mail changes label. Nothing is "
                 "deleted."),
                ("trash", "🗑  Delete it  (Gmail Trash)",
                 "Everything the rule matches goes to the Gmail Trash in one "
                 "go, where it stays 30 days and can be put back from any "
                 "mail program. Name the rule “Delete …” and it is a delete "
                 "button for one kind of mail.")):
            rb = tk.Radiobutton(arow, text=txt, value=val,
                                variable=self.v_action, bg=C_BG3, fg=C_FG,
                                selectcolor=C_BG2, activebackground=C_BG3,
                                activeforeground=C_FG, font=("Segoe UI", 9),
                                highlightthickness=0, command=self._sync_action)
            rb.pack(side="left", padx=(0, 14))
            add_tooltip(rb, tip)

        self._dest_row = tk.Frame(b, bg=C_BG3)
        self._dest_row.pack(fill="x", pady=(4, 0))
        self.e_dest = self._entry(self._dest_row, self.r["dest_folder"])
        self.e_dest.pack(side="left", fill="x", expand=True, ipady=3)
        self._b_pick = tk.Button(self._dest_row, text="📂  Pick…",
                                 bg=C_BTN_STD, fg=C_BTN_FG,
                                 font=("Segoe UI", 9), relief="flat",
                                 cursor="hand2", padx=10, pady=2,
                                 command=self._pick_dest)
        self._b_pick.pack(side="left", padx=(6, 0))

        self._dest_row2 = tk.Frame(b, bg=C_BG3)
        self._dest_row2.pack(fill="x", pady=(4, 0))
        tk.Label(self._dest_row2, text="on account:", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left")
        self._same = "(the one it is already in)"
        self.v_dest_acct = tk.StringVar(
            value=self.r["dest_account"] or self._same)
        choices = [self._same] + [a["email"] for a in self.app._accounts
                                  if not a.get("virtual")]
        self._om_dest = self._option(self._dest_row2, self.v_dest_acct, choices)
        self._om_dest.pack(side="left", padx=8)
        self.v_mark = tk.BooleanVar(value=bool(self.r["mark_read"]))
        tk.Checkbutton(self._dest_row2, text="mark it read on the way",
                       variable=self.v_mark, bg=C_BG3, fg=C_FG,
                       selectcolor=C_BG2, activebackground=C_BG3,
                       activeforeground=C_FG, font=("Segoe UI", 9),
                       highlightthickness=0).pack(side="left", padx=(14, 0))

        # ── Conditions ────────────────────────────────────────────────────
        self._label(b, "Which mail   —   add as many rows as you need")
        tk.Label(b, text="MUST rows all have to be true.  “any one of” rows "
                         "count as alternatives: at least one of them has to "
                         "be true.  Three subjects as “any one of” plus one "
                         "From as MUST = that sender, with any of those three "
                         "subjects.  The letter box PAIRS “any one of” rows: "
                         "same letter = one alternative that has to match "
                         "together, so (subject A + from X) OR (subject B + "
                         "from Y) is one rule.  “–” = the row on its own.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 anchor="w", justify="left",
                 wraplength=680).pack(fill="x", pady=(0, 4))
        self._conds = tk.Frame(b, bg=C_BG3)
        self._conds.pack(fill="x")
        addrow = tk.Frame(b, bg=C_BG3)
        addrow.pack(fill="x", pady=(4, 0))
        tk.Button(addrow, text="＋  Add a condition", bg=C_BTN_STD,
                  fg=C_BTN_FG, font=("Segoe UI", 9), relief="flat",
                  cursor="hand2", padx=10, pady=2,
                  command=lambda: self._add_cond()).pack(side="left")
        self._sentence = tk.Label(b, text="", bg=C_BG3, fg=C_ACCENT,
                                  font=("Segoe UI", 9), anchor="w",
                                  justify="left", wraplength=680)
        self._sentence.pack(fill="x", pady=(6, 0))

        for c in self.r["conditions"]:
            self._add_cond(c, redraw=False)
        if not self.r["conditions"]:
            self._add_cond(redraw=False)

        # ── The rest of the "which mail" ──────────────────────────────────
        srow = tk.Frame(b, bg=C_BG3)
        srow.pack(fill="x", pady=(10, 0))
        tk.Label(srow, text="Read state:", bg=C_BG3, fg=C_FG_DIM, width=12,
                 anchor="w", font=("Segoe UI", 9)).pack(side="left")
        self.v_state = tk.StringVar(value=self.r["state"])
        for val, txt in (("any", "any"), ("unread", "unread only"),
                         ("read", "read only")):
            tk.Radiobutton(srow, text=txt, value=val, variable=self.v_state,
                           bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                           activebackground=C_BG3, activeforeground=C_FG,
                           font=("Segoe UI", 9), highlightthickness=0,
                           command=self._describe).pack(side="left",
                                                        padx=(0, 10))
        self.v_attach = tk.BooleanVar(value=bool(self.r["has_attachment"]))
        tk.Checkbutton(srow, text="only with an attachment",
                       variable=self.v_attach, bg=C_BG3, fg=C_FG,
                       selectcolor=C_BG2, activebackground=C_BG3,
                       activeforeground=C_FG, font=("Segoe UI", 9),
                       highlightthickness=0,
                       command=self._describe).pack(side="left")

        # Age — in hours or days, because "after X hours/days" is how the
        # thought arrives ("radera alla matchande mail … efter X timmar/dagar").
        arow2 = tk.Frame(b, bg=C_BG3)
        arow2.pack(fill="x", pady=(6, 0))
        tk.Label(arow2, text="Age:", bg=C_BG3, fg=C_FG_DIM, width=12,
                 anchor="w", font=("Segoe UI", 9)).pack(side="left")
        self.v_older_n, self.v_older_u = self._age_widgets(
            arow2, "older than", self.r["older_h"])
        arow3 = tk.Frame(b, bg=C_BG3)
        arow3.pack(fill="x", pady=(2, 0))
        tk.Label(arow3, text="", bg=C_BG3, width=12).pack(side="left")
        self.v_newer_n, self.v_newer_u = self._age_widgets(
            arow3, "newer than", self.r["newer_h"])

        # ── Where to look ─────────────────────────────────────────────────
        self._label(b, "Look in these folders")
        frow = tk.Frame(b, bg=C_BG3)
        frow.pack(fill="x")
        self.v_folders = {}
        picked = {_folder_norm(f) for f in self.r["folders"]}
        for nm in _SWEEP_FOLDERS:
            v = tk.BooleanVar(value=_folder_norm(nm) in picked)
            self.v_folders[nm] = v
            tk.Checkbutton(frow, text=nm, variable=v, bg=C_BG3, fg=C_FG,
                           selectcolor=C_BG2, activebackground=C_BG3,
                           activeforeground=C_FG, font=("Segoe UI", 9),
                           highlightthickness=0).pack(side="left", padx=(0, 10))
        extra = [f for f in self.r["folders"]
                 if _folder_norm(f) not in {_folder_norm(n)
                                            for n in _SWEEP_FOLDERS}]
        erow = tk.Frame(b, bg=C_BG3)
        erow.pack(fill="x", pady=(2, 0))
        tk.Label(erow, text="…and these labels:", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(side="left")
        self.e_extra = self._entry(erow, ", ".join(extra))
        self.e_extra.pack(side="left", fill="x", expand=True, padx=6, ipady=2)
        tk.Button(erow, text="📂 add…", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 8), relief="flat", cursor="hand2",
                  padx=8, command=self._add_source).pack(side="left")

        self._label(b, "Only these accounts   (none ticked = every account)")
        arow4 = tk.Frame(b, bg=C_BG3)
        arow4.pack(fill="x")
        self.v_accts = {}
        want = {a.lower() for a in self.r["accounts"]}
        for a in [x for x in self.app._accounts if not x.get("virtual")]:
            v = tk.BooleanVar(value=a["email"].lower() in want)
            self.v_accts[a["email"]] = v
            tk.Checkbutton(arow4, text=a["email"].split("@")[0], variable=v,
                           bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                           activebackground=C_BG3, activeforeground=C_FG,
                           font=("Segoe UI", 9),
                           highlightthickness=0).pack(side="left", padx=(0, 10))

        tk.Label(b, text="A different account means the message is UPLOADED "
                         "there (the original sender is kept) and then "
                         "removed here — slower, and it downloads each "
                         "message in full. Same account is a plain Gmail "
                         "move.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 wraplength=680, justify="left",
                 anchor="w").pack(fill="x", pady=(4, 10))

        self._sync_action()
        self._describe()

    def _age_widgets(self, parent, caption, hours):
        """One "older than [n] [hours|days]" line. Returns (n var, unit var)."""
        tk.Label(parent, text=caption, bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9), width=10,
                 anchor="w").pack(side="left")
        h = int(hours or 0)
        if h and h % 24 == 0:
            n, unit = h // 24, "days"
        else:
            n, unit = h, "hours"
        v_n = tk.StringVar(value=str(n or ""))
        e = tk.Entry(parent, textvariable=v_n, width=6, justify="center",
                     bg=C_BG2, fg=C_FG, relief="flat",
                     insertbackground=C_ACCENT, font=("Segoe UI", 10),
                     insertofftime=0, insertontime=9999999)
        no_blink(e)
        e.pack(side="left", padx=4, ipady=2)
        v_u = tk.StringVar(value=unit)
        self._option(parent, v_u, ("hours", "days"), width=6,
                     cmd=lambda _v: self._describe()).pack(side="left")
        v_n.trace_add("write", lambda *_a: self._describe())
        tk.Label(parent, text="   (empty = no limit)", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(side="left")
        return v_n, v_u

    # ── conditions ────────────────────────────────────────────────────────
    def _add_cond(self, cond=None, redraw=True):
        cond = cond or dict(self._seed, value="")
        row = tk.Frame(self._conds, bg=C_BG3)
        row.pack(fill="x", pady=1)

        v_group = tk.StringVar(value=dict(self._GROUPS).get(
            cond.get("group", "all"), "MUST"))
        self._option(row, v_group, [t for _v, t in self._GROUPS], width=10,
                     cmd=lambda _v: self._describe()).pack(side="left")
        # The pair letter. Read only for "any one of" rows — on a MUST row it
        # would be a label nothing acts on, and _conditions() drops it there.
        v_pair = tk.StringVar(value=_cond_pair(cond) or _PAIR_NONE)
        om_pair = self._option(row, v_pair, [_PAIR_NONE] + list(_PAIR_LABELS),
                               width=2, cmd=lambda _v: self._describe())
        om_pair.pack(side="left", padx=(2, 0))
        add_tooltip(om_pair,
                    "Pairs “any one of” rows. Two rows with the same letter "
                    "are ONE alternative and must both match; “–” leaves the "
                    "row on its own.")
        v_field = tk.StringVar(value=dict(self._FIELDS).get(
            cond.get("field", "from"), "From"))
        self._option(row, v_field, [t for _v, t in self._FIELDS], width=8,
                     cmd=lambda _v: self._describe()).pack(side="left", padx=2)
        v_op = tk.StringVar(value=_FILTER_OP_LABELS.get(
            cond.get("op", "contains"), "contains"))
        self._option(row, v_op, [_FILTER_OP_LABELS[o] for o in self._OPS],
                     width=12,
                     cmd=lambda _v: self._describe()).pack(side="left", padx=2)
        v_val = tk.StringVar(value=cond.get("value", ""))
        e = tk.Entry(row, textvariable=v_val, bg=C_BG2, fg=C_FG,
                     relief="flat", insertbackground=C_ACCENT,
                     font=("Segoe UI", 10), insertofftime=0,
                     insertontime=9999999)
        no_blink(e)
        e.pack(side="left", fill="x", expand=True, padx=2, ipady=2)
        v_val.trace_add("write", lambda *_a: self._describe())

        entry = (v_field, v_op, v_val, v_group, row, v_pair)
        tk.Button(row, text="✕", bg=C_BTN_DEL, fg=C_BTN_FG,
                  font=("Segoe UI", 8), relief="flat", cursor="hand2",
                  padx=6, pady=0,
                  command=lambda en=entry: self._drop_cond(en)
                  ).pack(side="left", padx=(2, 0))
        self._cond_rows.append(entry)
        if redraw:
            e.focus_set()
            self._describe()

    def _drop_cond(self, entry):
        try:
            entry[4].destroy()          # index 4 is the row Frame
        except Exception:
            pass
        self._cond_rows = [c for c in self._cond_rows if c is not entry]
        if not self._cond_rows:
            self._add_cond(redraw=False)
        self._describe()

    def _conditions(self) -> list:
        rev_f = {t: v for v, t in self._FIELDS}
        rev_o = {v: k for k, v in _FILTER_OP_LABELS.items()}
        rev_g = {t: v for v, t in self._GROUPS}
        out = []
        for v_field, v_op, v_val, v_group, _row, v_pair in self._cond_rows:
            value = v_val.get().strip()
            if not value:
                continue
            group = rev_g.get(v_group.get(), "all")
            row = {"field": rev_f.get(v_field.get(), "from"),
                   "op": rev_o.get(v_op.get(), "contains"),
                   "value": value,
                   "group": group}
            pair = _cond_pair({"pair": v_pair.get()}) if group == "any" else ""
            if pair:
                row["pair"] = pair
            out.append(row)
        return out

    # ── live description ──────────────────────────────────────────────────
    def _describe(self, *_a):
        try:
            rule = self._collect()
        except Exception:
            return
        plan = _reloc_plan(rule)
        txt = _reloc_describe(rule).replace("\n     ", "\n")
        if not plan["ok"]:
            txt += f"\n⚠  Cannot run: {plan['why']}."
        self._sentence.configure(text=txt,
                                 fg=(C_ACCENT if plan["ok"] else "#e0a030"))

    def _sync_action(self):
        trash = self.v_action.get() == "trash"
        for w in (self.e_dest, self._b_pick, self._om_dest):
            try:
                w.configure(state="disabled" if trash else "normal")
            except Exception:
                pass
        self._describe()

    # ── pickers ───────────────────────────────────────────────────────────
    def _add_source(self):
        name = self.app._pick_target_folder("Also look in this folder…")
        if not name:
            return
        cur = [s.strip() for s in self.e_extra.get().split(",") if s.strip()]
        if name not in cur:
            cur.append(name)
        self.e_extra.delete(0, "end")
        self.e_extra.insert(0, ", ".join(cur))

    def _pick_dest(self):
        name = self.app._pick_target_folder("Move the mail into…")
        if name:
            self.e_dest.delete(0, "end")
            self.e_dest.insert(0, name)
            self._describe()

    # ── save ──────────────────────────────────────────────────────────────
    def _hours(self, v_n, v_u) -> int:
        try:
            n = max(0, int((v_n.get() or "0").strip() or 0))
        except ValueError:
            n = 0
        return n * 24 if v_u.get() == "days" else n

    def _collect(self) -> dict:
        folders = [n for n, v in self.v_folders.items() if v.get()]
        folders += [s.strip() for s in self.e_extra.get().split(",")
                    if s.strip()]
        dest_acct = self.v_dest_acct.get()
        return _reloc_norm({
            "name": self.e_name.get().strip(),
            "enabled": self.r.get("enabled", True),
            "accounts": [e for e, v in self.v_accts.items() if v.get()],
            "folders": folders or ["Inbox"],
            "conditions": self._conditions(),
            "newer_h": self._hours(self.v_newer_n, self.v_newer_u),
            "older_h": self._hours(self.v_older_n, self.v_older_u),
            "state": self.v_state.get(),
            "has_attachment": bool(self.v_attach.get()),
            "action": self.v_action.get(),
            "dest_account": "" if dest_acct == self._same else dest_acct,
            "dest_folder": self.e_dest.get().strip(),
            "mark_read": bool(self.v_mark.get()),
            "per_folder": self.r.get("per_folder", 500),
        })

    def _save(self):
        rule = self._collect()
        if not rule["name"]:
            first = (rule["conditions"][0]["value"]
                     if rule["conditions"] else "")
            what = "Delete" if rule["action"] == "trash" else "Move"
            rule["name"] = (f"{what} {first or 'mail'} → "
                            f"{_reloc_dest_label(rule)}")
        plan = _reloc_plan(rule)
        if not plan["ok"]:
            self._warn.configure(
                text="⚠  This rule cannot run: " + plan["why"] + ".")
            return
        if (rule["action"] == "move" and rule["dest_account"]
                and not self.app._secret_for(rule["dest_account"])):
            self._warn.configure(
                text=f"⚠  There is no stored password for "
                     f"{rule['dest_account']}, so nothing could be uploaded "
                     f"there.")
            return
        self.owner._rule_saved(rule, self.idx)
        self.destroy()

# ******************************************************************************
# DEL 09 — MAIN APPLICATION CLASS
# ******************************************************************************

class FreemailApp:

    def __init__(self, root: tk.Tk):
        self.root = root
        self.cfg  = _load_settings()
        # Apply the connection-reuse preference to the pool (DEL 04v).
        _set_imap_reuse(self.cfg.get("imap_reuse", True))

        # State
        # Load real configured accounts; fall back to DEMO mode (mock data)
        # when none has been added yet, so the UI is never empty.
        self._account_store = _load_account_store()
        self._autosave_store = _load_autosave_rules()
        self._contacts_store = _load_contacts()
        self._addressbook_store = _load_addressbook()
        # ── Stores added in DEL 04d ──────────────────────────────────────────
        self._signature_store = _load_signatures()
        self._template_store  = _load_templates()
        self._snippet_store   = _load_snippets()
        self._filter_store    = _load_filters()
        self._blocklist_store = _load_blocklist()
        self._unsub_store     = _load_unsubs()   # DEL 04e2: done + waiting
        self._snooze_store    = _load_snooze()
        self._hiddenparts_store = _load_hidden_parts()   # DEL 04t
        self._outbox_store    = _load_outbox()
        self._calendar_store  = _load_calendar()
        self._timers_store    = _load_timers()          # DEL 04f3 quick timers
        self._timer_after_ids = {}                       # id → after() handle
        self._followup_store  = _load_followups()
        self._tag_store       = _load_tags()
        self._address_store   = _load_address_mails()   # ✉ manual address marks
        self._protected_store = _load_protected()      # DEL 09p "Send and save"
        self._merge_store     = _load_merge_groups()   # manual conversation groups
        self._ship_store      = _load_ship_facts()     # DEL 09m shipping facts
        self._ship_dirty      = False                  # …needs writing back
        self._ship_memo       = {}                     # …this session's lookups
        self._folderplan_store = _load_folderplans()
        self._folderage_store  = _load_folder_ages()   # DEL 04r ageing rules
        self._folderage_busy   = set()                 # rule ids running now
        self._search_store     = _load_searches()
        self._browser_store    = _load_browser_profiles()
        self._rebuild_accounts()
        self._ps_boot()          # DEL 58: phone sync state + quiet background sync

        # Outbox / notification state
        self._outbox_after_id = None    # scheduler tick
        self._undo_toasts     = {}      # outbox id → UndoToast
        self._sending_ids     = set()   # outbox ids currently in SMTP
        self._seen_keys       = _BoundedSet(8000)   # message keys already shown to the user
        self._first_fetch     = True    # do not notify about the whole inbox
        # One-shot: reopen the message that was open last time, on the first
        # list that appears after start-up (DEL 04t).
        self._restore_pending = bool(self.cfg.get("last_msg_key", ""))
        # Filter log (DEL 04x): recent "rule X acted on message Y" events, for
        # the Filter-log viewer. Deduped by (rule, message) so a re-fetch of the
        # same mail does not log it again.
        self._filter_log      = []
        # Bounded: the log itself keeps 500 entries, so a dedupe set that
        # remembered everything for ever disagreed with it (see _BoundedSet).
        self._filter_log_seen = _BoundedSet(2000)
        # Activity log (Issu 2026-08-08): the SAME kind of information, but
        # kept on disk so it is still there tomorrow. The filter log above dies
        # with the session, which is useless for "the phone buzzed this morning
        # — what happened to that mail?".
        self._activity_store  = _load_activity()
        # How much each rule is actually doing, kept across restarts
        # (Issu 2026-08-08) — see the Rule health window.
        self._rule_stats      = _load_rule_stats()
        # The last filter run explained in full (DEL 04z5) — every rule against
        # every message, including the near misses. Shown by
        # "Why didn't my rule fire?" and mirrored to Freemail.log.
        self._filter_diag     = None
        # Which pane the arrow keys drive: "folders" or "messages" (DEL 09f).
        self._nav_zone        = "messages"
        self._folder_rows     = []      # ordered (account, folder, label) rows
        # Server-side filter actions already carried out (fid, msg key, kind),
        # so a re-fetch never runs the same move/trash/flag twice (DEL 04y).
        self._filter_action_done = _BoundedSet(5000)
        # Which messages have already been DELIVERED to another account
        # (DEL 04y2). On disk, unlike the set above: the whole point is that a
        # message trashed on the source account keeps matching its rule for as
        # long as it sits in Trash, across restarts, and must not be copied to
        # the Main account a second time each session.
        self._delivered       = _load_delivered()
        # Messages whose body has already been fetched so that a BODY-reading
        # rule could be judged on it (see _finish_deferred_rules). Bounded, and
        # per session only: once the body is downloaded it is in the disk cache
        # anyway, so the next run has it for free.
        self._body_for_rules_done = _BoundedSet(3000)
        # Standing "hide this boilerplate everywhere" rules (DEL 04t2), and the
        # blocks you have clicked open again. The reveal set is per SESSION on
        # purpose: showing a folded footer once is a look, not a decision — it
        # must not quietly turn the rule off for ever.
        self._trim_store    = _load_trim_rules()
        self._trim_revealed = set()          # {(msg key, folded text)}
        # Quoted context messages opened out of their 240-character summary
        # (session-only, same reasoning as _trim_revealed above).
        self._ctx_expanded  = set()          # {msg key}
        # Which built-ins this installation has already been offered. An older
        # settings.json only knows the boolean, so read it as "version 1".
        _seen_seed = int(self.cfg.get(
            "trim_seed_version", 1 if self.cfg.get("trim_seeded") else 0))
        if _seen_seed < _TRIM_SEED_VERSION:
            added    = _seed_trim_rules(self._trim_store, since=_seen_seed)
            repaired = _repair_trim_rules(self._trim_store)
            if added or repaired:
                _save_trim_rules(self._trim_store)
                log.info("Message-trim rules: seeded %d, repaired %d",
                         added, repaired)
            self.cfg["trim_seeded"] = True
            self.cfg["trim_seed_version"] = _TRIM_SEED_VERSION
            _save_settings(self.cfg)
        self._bg_check        = False   # True only during an automatic check
        # Set when a backup has been restored over the running configuration,
        # so _on_close does not write the stale in-memory settings back.
        self._settings_restored = False
        # False until the saved sash (divider) positions have actually been
        # placed at their real height. Until then _on_configure must NOT save
        # the current sash coords — during a cold-boot autostart the panes are
        # still laid out tiny for the first few frames, and saving that would
        # overwrite the good value with a one-message-tall one (see
        # _restore_sashes / _on_configure).
        self._sash_ready = False

        # Calendar state (DEL 04f/06d)
        self._calendar_win    = None    # the open CalendarWindow, if any
        self._cal_after_id    = None    # reminder ticker
        self._open_reminders  = []      # ReminderPopup instances on screen
        self._reminder_snoozes = []     # [(fire_at, ev, occ, mins, key), ...]
        self._search_results  = None    # wide-search result list, or None

        self._current_acct = self.cfg.get("last_account") or ALL_ACCOUNTS_ID
        # Guard: stored account may no longer exist
        if self._current_acct not in {a["email"] for a in self._accounts}:
            self._current_acct = self._accounts[0]["email"] if self._accounts else ALL_ACCOUNTS_ID
        self._current_folder = self.cfg.get("last_folder", "Inbox")
        self._messages       = []
        self._selected_msg   = None
        self._folder_vars    = {}   # folder_name → label widget
        # Custom (user-created) IMAP folders/labels per account, discovered in
        # the background so the sidebar can list them under the standard set
        # (DEL 09c). email → [ {mailbox, display, full, depth}, ... ].
        self._user_folders   = {}
        self._folders_loading = False
        # (account, folder) -> uids already flagged \Seen for an auto-read
        # folder, so a re-fetch of the same list does not re-send the STORE.
        self._auto_read_done = {}
        # Accounts whose REFUSAL (bad password, not a timeout) has already been
        # put in front of you once this session. A dialog you have read is not
        # worth raising again every minute.
        self._told_about_account = set()
        # Per-folder UNSEEN counts, discovered via IMAP STATUS (DEL 09c):
        # email → {folder-key: unread-count}. Drives the "(N)" badges in the
        # sidebar, the window title, and the taskbar icon.
        self._folder_unread   = {}
        # Of that unread, how many are "kept" (always-unread senders: read on
        # Gmail so \Seen, but held unread here on purpose). email → {folder:
        # kept-count}. Genuine (=to-look-at) unread = _folder_unread − this;
        # it drives the taskbar badge COLOUR (red = genuine new mail, blue-
        # purple = only kept). See _unread_kind / _reconcile_folder_badge.
        self._folder_kept     = {}
        self._counts_loading  = False
        self._counts_last     = 0.0     # monotonic time of the last count pass
        self._row_frames     = []   # message row frames
        self._expanded_rows  = set()  # message ids whose thread is expanded inline
        self._fetch_token    = None   # identity of the latest fetch (drops stale)
        self._fetch_in_flight = False # a fetch is on the wire right now
        self._fetch_started   = 0.0   # …since when (monotonic), for the guard
        self._no_merge_cache  = None  # (stored list, normalised key set)
        self._closing        = False  # set on exit; stops the body prefetch
        self._all_messages   = []     # unfiltered fetch result (for local search)
        self._acct_poll_ids  = {}     # email → scheduled auto-check callback id
        # email → when its auto-check started (monotonic). Present = one is on
        # the wire. Self-healing: an entry older than FETCH_DEADLINE_SEC * 3 is
        # treated as a dead worker and stepped over.
        self._poll_inflight  = {}
        self._read_timer_id  = None   # pending "mark read after dwell" callback
        self._read_timer_msg = None   # the message that timer belongs to
        self._fetch_limit    = FETCH_LIMIT  # grows via "Load more"; reset per folder
        # ── Column-layout migration (Issu 2026-09-23) ────────────────────────
        # The ✉ column was inserted at index 1, so every saved sort_col from
        # index 1 upward moved up by one (📎 stayed 0). Bump a remembered value
        # once, keyed on a version flag so it can never double-shift.
        if not self.cfg.get("msg_cols_v"):
            try:
                if int(self.cfg.get("sort_col", 8)) >= 1:
                    self.cfg["sort_col"] = int(self.cfg["sort_col"]) + 1
            except Exception:
                self.cfg["sort_col"] = 8
            self.cfg["msg_cols_v"] = 1
            try:
                _save_settings(self.cfg)
            except Exception:
                pass
        # Sort state — click a column header to change. Default: newest first.
        self._sort_col  = self.cfg.get("sort_col", 8)    # 8 = Date column
        self._sort_desc = self.cfg.get("sort_desc", True)
        # ── Multi-select (DEL 09e) ───────────────────────────────────────────
        # Ids of every message ticked. Ctrl+click adds one, Shift+click adds a
        # run. Kept as ids, not objects, so a re-fetch does not strand it.
        self._selected_ids  = set()
        self._last_click_ix = None      # anchor for Shift+click
        # ── Quick filters — which toggles are pressed ────────────────────────
        self._quick = {"unread": False, "starred": False, "attach": False,
                       "tagged": False, "followup": False}
        # ── Undo (DEL 09e): the last reversible thing that happened ──────────
        self._undo_stack = []
        # ── Delete limbo (Issu 2026-08-01) ───────────────────────────────────
        # A delete acts at once (no Yes/No popup) but the real Gmail change is
        # held for delete_undo_seconds behind an Undo button. One batch at a
        # time: starting a new delete commits any previous one first.
        self._pending_delete = None      # {msgs, permanent, server, after_id}
        # ── DEL 09k — THE UNDO WINDOW MUST SURVIVE THE REST OF THE PROGRAM ───
        # Issu 2026-08-22: "Blir det problem att göra saker (t.ex. Move)
        # samtidigt som det är UNDO-period (för t.ex. DELETE)?"  It could,
        # and the fault was not the Move itself — it was any RELOAD during the
        # limbo. A message in limbo has been taken out of the list but is
        # still on Gmail, so the moment anything re-read the folder (a failed
        # move reloads, a folder switch, ↻ Refresh, the auto-check) the server
        # handed it straight back and it reappeared as a row that was about to
        # be deleted under him — and Undo then added a SECOND copy of it.
        # These keys are the memory of "gone, pending": the list filters them
        # out however it was rebuilt, and Undo clears them instead of pushing
        # rows back in by hand.
        self._pending_delete_keys = set()
        # The in-window Undo bar's scheduled label changes (60→30→10) and its
        # auto-hide, so they can all be cancelled on Undo/commit. No per-second
        # ticking — only three states — because Issu is sensitive to blinking.
        self._undo_after_ids = []

        root.title("F(re)email")
        root.configure(bg=C_BG1)
        w = self.cfg["win_width"]
        h = self.cfg["win_height"]
        x = self.cfg["win_x"]
        y = self.cfg["win_y"]
        root.geometry(f"{w}x{h}+{x}+{y}")
        root.minsize(700, 450)
        # Restore the maximized state too, but only AFTER the normal geometry
        # is in place — un-maximizing then gives back the size you chose.
        if self.cfg.get("win_zoomed"):
            try:
                root.state("zoomed")
            except Exception:
                pass   # not supported on this platform; normal size is fine

        self._build_menu()
        self._build_toolbar()
        self._build_statusbar()      # before the panels: it packs to the bottom
        self._build_panels()
        self._bind_shortcuts()
        self._refresh_messages()

        root.bind("<Configure>", self._on_configure)
        root.protocol("WM_DELETE_WINDOW", self._on_close)

        self._reschedule_autocheck()

        # ── Start-up housekeeping (DEL 04d/09b) ──────────────────────────────
        # 1. Throw away drafts whose message was sent long enough ago.
        # 2. Start the outbox scheduler — anything whose time passed while the
        #    program was closed goes out on the first tick.
        # 3. Offer to reopen drafts that were never sent (crash recovery).
        try:
            _sweep_drafts(int(self.cfg.get("draft_keep_min", 10)))
        except Exception as e:
            log.warning("Draft sweep failed: %s", e)
        try:
            _outbox_prune_attachments(self._outbox_store)
        except Exception as e:
            log.warning("Outbox prune failed: %s", e)
        try:
            gone = _deleted_prune(self.cfg.get("deleted_keep_days", 30))
            if gone:
                log.info("Pruned %d expired deleted copies", gone)
        except Exception as e:
            log.warning("Deleted-archive prune failed: %s", e)
        self._outbox_tick()
        self._calendar_tick()
        self._arm_all_timers()      # re-arm saved quick timers (DEL 04f3)
        root.after(600, self._offer_draft_restore)
        root.after(900, self._nag_stuck_outbox)
        # The sidebar's own folders, straight off the disk, BEFORE anything
        # touches the network — see _folderlist_cache_load for the minute and a
        # half this used to cost. The scan below then corrects it in the
        # background, exactly as the message list has always worked.
        self._seed_folder_tree_from_cache()
        # Discover each account's own folders/labels in the background so the
        # sidebar can list them beneath the standard set (DEL 09c). The folder
        # scan chains into an unread-count pass; this call covers the case where
        # there are no custom folders at all.
        root.after(800, self._refresh_folder_tree)
        root.after(1400, self._refresh_unread_counts)
        # Run the filters across every account shortly after start, so mail that
        # arrived while the program was closed is filed without opening each
        # inbox by hand (Issu 2026-09-23). Delayed so it never blocks first paint.
        root.after(2200, lambda: self._sweep_all_accounts("startup"))

    # ── Keyboard shortcuts (ignored while typing in a field) ───────────────────
    def _typing_focused(self) -> bool:
        try:
            w = self.root.focus_get()
        except Exception:
            w = None
        if w is None:
            return False
        # The reading pane is a read-only tk.Text, so "is the focus a Text?"
        # used to answer YES the moment you clicked a message to read it — and
        # every single-letter shortcut and every arrow key went dead
        # (Issu 2026-08-03: "Arrow up/down, kan fortfarande inte flytta sig").
        # Widgets that only DISPLAY text are marked when they are built.
        if getattr(w, "_nav_passthrough", False):
            return False
        return isinstance(w, (tk.Entry, tk.Text, tk.Spinbox))

    def _sc(self, fn):
        """Wrap an action so it fires only when NOT typing in a text field."""
        def handler(event=None):
            if self._typing_focused():
                return
            fn()
            return "break"
        return handler

    # ── DEL 09f — arrow-key navigation of both panes (Issu 2026-08-03) ─────────
    #
    #   Up / Down          move inside whichever pane has the arrows
    #   Left / Right       hand the arrows to the folder pane / the message pane
    #   Shift+Up / Down    grow (or shrink) the message selection from an anchor
    #
    # A compose or reply window is a Toplevel of its own, and Tk only sends key
    # events up to THAT window — so these bindings on the main window are
    # already inert while you are writing, which is what Issu asked for.

    def _nav_typing(self, arrows="ud") -> bool:
        """True when the keystroke belongs to whatever you are typing in.

        Up/Down do nothing useful in a one-line Entry, so they are handed to the
        list even from the search box (which is how you search and then walk the
        hits). Left/Right DO move the caret, so those stay with the Entry."""
        try:
            w = self.root.focus_get()
        except Exception:
            return False
        if w is None or getattr(w, "_nav_passthrough", False):
            return False
        if isinstance(w, tk.Text):
            return True
        if isinstance(w, (tk.Entry, tk.Spinbox)):
            return arrows != "ud"
        return False

    def _attach_nav(self, widget):
        """Let a read-only text/canvas pass the arrow keys to the navigator
        instead of swallowing them."""
        try:
            widget._nav_passthrough = True
            widget.bind("<Up>",         lambda e: self._nav_key(-1))
            widget.bind("<Down>",       lambda e: self._nav_key(+1))
            widget.bind("<Shift-Up>",   lambda e: self._nav_key(-1, extend=True))
            widget.bind("<Shift-Down>", lambda e: self._nav_key(+1, extend=True))
            widget.bind("<Left>",       lambda e: self._nav_to_zone("folders"))
            widget.bind("<Right>",      lambda e: self._nav_to_zone("messages"))
        except Exception:
            pass

    def _nav_key(self, delta, extend=False):
        """One Up/Down press, sent to whichever pane currently owns them."""
        if self._nav_typing("ud"):
            return None
        if self._nav_zone == "folders" and not extend:
            return self._nav_folder(delta)
        return self._nav_message(delta, extend=extend)

    def _nav_to_zone(self, zone):
        """Left/Right: hand the arrow keys to the other pane."""
        if self._nav_typing("lr"):
            return None
        if zone == self._nav_zone:
            return "break"
        self._nav_zone = zone
        self._paint_nav_zone()
        if zone == "messages" and self._selected_msg is None:
            self._nav_message(+1)
        return "break"

    def _paint_nav_zone(self):
        """Show which pane the arrows drive, as a static accent edge. No
        flashing, no animation — it changes only when you change panes."""
        try:
            on, off = C_ACCENT, C_BG1
            for widget, zone in ((getattr(self, "_nav_edge_folders", None),
                                  "folders"),
                                 (getattr(self, "_nav_edge_messages", None),
                                  "messages")):
                if widget is not None and widget.winfo_exists():
                    widget.configure(bg=on if self._nav_zone == zone else off)
        except Exception:
            pass

    def _nav_folder(self, delta):
        """Move up/down the folder list in the left pane and open that folder."""
        rows = list(getattr(self, "_folder_rows", None) or [])
        if not rows:
            return "break"
        cur = next((i for i, (a, f, _w) in enumerate(rows)
                    if a == self._current_acct and f == self._current_folder),
                   None)
        if cur is None:
            cur = 0 if delta > 0 else len(rows) - 1
        else:
            cur = max(0, min(len(rows) - 1, cur + delta))
        acct, folder, widget = rows[cur]
        try:                       # keep the row on screen in a long sidebar
            widget.winfo_toplevel().update_idletasks()
        except Exception:
            pass
        self._select_folder(acct, folder)
        self._nav_zone = "folders"     # _select_folder already sets this
        self._paint_nav_zone()
        return "break"

    def _bind_shortcuts(self):
        r = self.root
        r.bind("<KeyPress-n>", self._sc(self._compose_new))
        r.bind("<KeyPress-N>", self._sc(self._compose_new))
        r.bind("<KeyPress-r>", self._sc(self._reply))
        r.bind("<KeyPress-R>", self._sc(self._reply))
        r.bind("<KeyPress-f>", self._sc(self._forward))
        r.bind("<KeyPress-F>", self._sc(self._forward))
        r.bind("<Delete>",     self._sc(self._delete_selected))
        # Arrows: Up/Down inside the active pane, Left/Right to swap panes,
        # Shift+Up/Down to grow or shrink the message selection from its anchor.
        r.bind("<Up>",         lambda e: self._nav_key(-1))
        r.bind("<Down>",       lambda e: self._nav_key(+1))
        r.bind("<Shift-Up>",   lambda e: self._nav_key(-1, extend=True))
        r.bind("<Shift-Down>", lambda e: self._nav_key(+1, extend=True))
        r.bind("<Left>",       lambda e: self._nav_to_zone("folders"))
        r.bind("<Right>",      lambda e: self._nav_to_zone("messages"))
        r.bind("<F5>",         lambda e: self._check_now())  # refresh + sweep all
        # Ctrl+N also opens a new message even while typing (matches the menu).
        r.bind("<Control-n>",  lambda e: (self._compose_new(), "break")[1])
        # Ctrl+K opens the calendar even while typing (matches the menu).
        r.bind("<Control-k>",  lambda e: (self._open_calendar(), "break")[1])
        r.bind("<Control-t>",  lambda e: (self._new_note(), "break")[1])
        # Ctrl+Shift+T — the post-it board (DEL 04g3), next to the long note.
        r.bind("<Control-T>",  lambda e: (self._postit_board(), "break")[1])
        r.bind("<Control-u>",  lambda e: (self._show_message_source(),
                                          "break")[1])
        r.bind("<Control-a>",  lambda e: (self._select_all(True), "break")[1])
        # Ctrl+Shift+F opens the search WINDOW even while typing — the same
        # reflex as everywhere else, and it takes whatever is in the search box
        # with it (Issu 2026-08-08).
        r.bind("<Control-F>",  lambda e: (self.open_search_window(
            "" if self.e_search.get() == "Search mail…"
            else self.e_search.get().strip()), "break")[1])
        r.bind("<Control-z>",  lambda e: (self._undo_last(), "break")[1])
        r.bind("<Escape>",     self._sc(lambda: self._select_all(False)))
        r.bind("<KeyPress-t>", self._sc(self._new_note))
        # 1-9 toggle the first nine tags on the selected message (DEL 04k) —
        # the same reflex as Thunderbird.
        for _n in range(1, 10):
            r.bind(f"<KeyPress-{_n}>",
                   self._sc(lambda i=_n: self._tag_selected(i)))
        r.bind("<KeyPress-k>", self._sc(self._open_calendar))

    # ── Auto-check (read-only background refresh, per account) ─────────────────
    #
    # Each account runs on its OWN timer at its OWN interval (Tools → Auto-check
    # for new mail…). When a timer fires we check just that account's Inbox in
    # the background (read-only, cached), update its unread badges and toast on
    # anything new. If you happen to be looking at that inbox (or the All
    # Accounts view) the visible list is refreshed too.

    def _account_interval(self, email):
        """Minutes between auto-checks for one account. A per-account override
        wins; otherwise the global default applies. 0 = off."""
        per = self.cfg.get("account_intervals", {}) or {}
        if email in per:
            try:
                return max(0, int(per[email]))
            except Exception:
                return 0
        try:
            return max(0, int(self.cfg.get("check_interval_min", 0)))
        except Exception:
            return 0

    def _cancel_all_autochecks(self):
        for aid in list(self._acct_poll_ids.values()):
            try:
                self.root.after_cancel(aid)
            except Exception:
                pass
        self._acct_poll_ids = {}

    def _schedule_one_account(self, email):
        """(Re)arm a single account's timer, cancelling any pending one first
        so intervals can never stack up."""
        old = self._acct_poll_ids.pop(email, None)
        if old is not None:
            try:
                self.root.after_cancel(old)
            except Exception:
                pass
        mins = self._account_interval(email)
        if mins > 0 and not self._demo_mode:
            self._acct_poll_ids[email] = self.root.after(
                mins * 60_000, lambda e=email: self._poll_account(e))

    def _reschedule_autocheck(self):
        """Rebuild every account's timer from the current settings."""
        self._cancel_all_autochecks()
        if self._demo_mode:
            return
        for a in self._accounts:
            if a.get("virtual"):
                continue
            self._schedule_one_account(a.get("email"))

    def _poll_account(self, email):
        """One account's scheduled, read-only background check of its Inbox.

        Issu 2026-08-16 — the reason "filter verkar inte fungera":

        This used to run the filters ONLY when you happened to be looking at
        the account it just checked. Every other account's new mail was
        fetched, counted, announced in a toast… and then left exactly where it
        arrived. His five accounts are checked every 1–60 minutes precisely so
        that shipping receipts from ALL of them are filed into the Main
        account's 0---Frakt & Kvitto by themselves — but nothing was filed
        until he opened that account by hand, at which point the rules fired
        all at once and it looked as though the filters worked "sometimes".

        The rules now run on every scheduled check of every account, which is
        what "från ALLA konton" has to mean. _apply_local_state is the same
        single path the visible list uses, so a background check and a manual
        refresh cannot behave differently."""
        self._acct_poll_ids.pop(email, None)
        if self._demo_mode:
            return
        a = next((x for x in self._accounts
                  if x.get("email") == email and not x.get("virtual")), None)
        if a is None:
            return
        # Not answering? Come back later instead of spending a 30-second
        # timeout on it every minute (Issu 2026-08-17). The timer is re-armed
        # either way, so it heals by itself the moment the account does.
        left = _stall_left(email)
        if left > 0:
            log.debug("Skipping the auto-check for %s — standing down for "
                      "another %.0f s", email, left)
            self._schedule_one_account(email)
            return

        # ── THE CHAIN MUST NOT BE ABLE TO BREAK (Issu 2026-08-19) ────────────
        #
        # "9:51 så står den som loading… nytt mail från Tradera har inte kommit
        # fram. 9:40 kom det till gmail… det är opålitligt."
        #
        # This method popped its timer id at the top and armed the NEXT one
        # only from `done()` — which runs after the worker's fetch returns. So
        # a worker that never returned did not merely miss one check: it ended
        # the account's auto-check for the rest of the session, and the only
        # way to see new mail was to press Refresh by hand. That is exactly
        # what his log shows at 09:40, when issusbarn@gmail.com timed out and
        # was stood down:
        #
        #   09:40:16  issusbarn@gmail.com is not answering …
        #   10:22:18  The previous refresh has been running 503 s and never
        #             reported back — starting a new one
        #
        # Eight and a half minutes with nothing polling at all.
        #
        # The next timer is armed HERE, before any network call, so the chain
        # survives a worker that hangs, throws, or is still on the wire.
        # `done()` re-arms as well; _schedule_one_account cancels any pending
        # timer first, so arming twice is harmless and never stacks.
        #
        # The in-flight guard is a dict rather than a set so it is self-healing
        # too: a stuck worker blocks its own account for a couple of rounds,
        # not for ever.
        started = self._poll_inflight.get(email)
        if started is not None:
            busy = time.monotonic() - started
            if busy < FETCH_DEADLINE_SEC * 3:
                log.debug("Auto-check for %s skipped — the previous one has "
                          "been running %.0f s", email, busy)
                self._schedule_one_account(email)
                return
            log.info("The auto-check for %s has been running %.0f s and never "
                     "finished — starting a new one", email, busy)
        self._poll_inflight[email] = time.monotonic()
        self._schedule_one_account(email)

        def worker():
            msgs = None
            trash_msgs = None
            try:
                pwd  = _decrypt_secret(a.get("secret", ""))
                msgs = _fetch_folder_smart(
                    email, pwd, "Inbox", limit=self._fetch_limit,
                    use_cache=self.cfg.get("cache_enabled", True))
            except Exception as e:
                log.error("Auto-check for %s failed: %s", email, e)
            if msgs is not None:
                trash_msgs = self._fetch_rescue_trash(email, pwd)

            def done():
                try:
                    viewing = (self._current_folder == "Inbox"
                               and self._current_acct in (email, ALL_ACCOUNTS_ID))
                    if viewing:
                        # The visible list handles its own new-mail toast, and
                        # _apply_messages runs the rules on the way through.
                        self._refresh_messages(background=True)
                    else:
                        if msgs is not None:
                            self._bg_check = True
                            # RUN THE RULES. This is a background pass over an
                            # account that is not on screen, so nothing here
                            # touches self._messages or redraws anything — the
                            # returned list is only used for the new-mail
                            # toast, which now correctly leaves out whatever a
                            # rule just hid, trashed or filed away.
                            #
                            # `shown`, not `msgs`: assigning to the closed-over
                            # name would make it local to this function and
                            # the `if msgs is not None` above would raise
                            # UnboundLocalError on every single check.
                            shown = msgs
                            try:
                                shown = self._apply_local_state(msgs)
                            except Exception as e:
                                log.error("Background filter run for %s "
                                          "failed: %s", email, e)
                            self._notify_new(shown)
                        self._maybe_refresh_counts(force=True)
                    self._run_rescue_trash(email, trash_msgs)
                finally:
                    self._poll_inflight.pop(email, None)
                    self._schedule_one_account(email)
            try:
                self.root.after(0, done)
            except Exception:
                # Window closed mid-check, or Tk refused the callback. Either
                # way the account must not be left marked "busy" for ever.
                self._poll_inflight.pop(email, None)

        def guarded():
            """The worker, wrapped so the in-flight mark is always released.

            Without this, a fetch that raises somewhere the inner try does not
            cover would leave `_poll_inflight[email]` set, and the guard above
            would then skip this account for FETCH_DEADLINE_SEC * 3 every
            round — quiet, and indistinguishable from "no new mail"."""
            try:
                worker()
            except Exception as e:
                log.error("Auto-check worker for %s crashed: %s", email, e)
                self._poll_inflight.pop(email, None)
                try:
                    self.root.after(0, lambda: self._schedule_one_account(email))
                except Exception:
                    pass

        threading.Thread(target=guarded, daemon=True).start()

    def _check_now(self):
        """Refresh the open folder AND run the filters across every account.

        The open account/folder is fetched and rendered by _refresh_messages;
        _sweep_all_accounts then fetches every OTHER account's Inbox in the
        background and runs the same rule pass, so a manual Refresh files mail on
        all accounts at once instead of only the inbox you happen to be in
        (Issu 2026-09-23). Wired to ↻ Refresh and F5 as well."""
        self._refresh_messages()
        self._sweep_all_accounts("refresh")

    # ── Auto-check settings dialog (per-account intervals + cache) ─────────────
    def _autocheck_dialog(self):
        """Pick how often each account is checked in the background, plus the
        local-cache switch. One row per account; a per-account choice overrides
        the default. Read-only — it only ever fetches, never changes Gmail."""
        # (label shown, minutes stored). 0 = off.
        CHOICES = [("Off", 0), ("1 min", 1), ("2 min", 2), ("3 min", 3),
                   ("5 min", 5), ("10 min", 10),
                   ("15 min", 15), ("30 min", 30), ("60 min", 60)]
        min_by_label = {lab: m for lab, m in CHOICES}
        label_by_min = {m: lab for lab, m in CHOICES}
        USE_DEFAULT  = "Use default"

        reals = [a for a in self._accounts if not a.get("virtual")]
        rows_h = 34 * max(1, len(reals))
        height = min(620, 300 + rows_h)
        top = self._dialog_shell("Auto-check for new mail", 560, height)

        def _om(parent, var, options):
            om = tk.OptionMenu(parent, var, *options)
            om.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                         activeforeground=C_FG, highlightthickness=0,
                         relief="flat", font=("Segoe UI", 9), width=11,
                         anchor="w")
            om["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                                 activeforeground=C_FG)
            return om

        f = tk.Frame(top, bg=C_BG3)
        f.pack(fill="both", expand=True, padx=18, pady=10)

        tk.Label(f, text="How often should F(re)email look for new mail in the "
                         "background?",
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 10, "bold"),
                 anchor="w", justify="left", wraplength=500).pack(fill="x")
        tk.Label(f, text="Checking is read-only — it only fetches, it never "
                         "changes anything on Gmail. Each account can have its "
                         "own interval. Tip: you can also right-click an account "
                         "in the sidebar to set the same things.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w",
                 justify="left", wraplength=500).pack(fill="x", pady=(2, 8))

        # ── Default (used by every account without its own setting) ──────────
        drow = tk.Frame(f, bg=C_BG3)
        drow.pack(fill="x", pady=(0, 4))
        tk.Label(drow, text="Default (all accounts):", bg=C_BG3, fg=C_FG,
                 width=22, anchor="w", font=("Segoe UI", 9, "bold")
                 ).pack(side="left")
        cur_def = int(self.cfg.get("check_interval_min", 0) or 0)
        v_default = tk.StringVar(value=label_by_min.get(cur_def, "Off"))
        _om(drow, v_default, [lab for lab, _m in CHOICES]).pack(side="left")

        tk.Frame(f, bg=C_SEP, height=1).pack(fill="x", pady=8)

        account_vars = {}
        if not reals:
            tk.Label(f, text="No accounts yet — add one under the Accounts menu "
                             "to set a per-account interval.",
                     bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9, "italic"),
                     anchor="w", wraplength=500, justify="left").pack(fill="x")
        else:
            tk.Label(f, text="Per account (\"Use default\" follows the row above):",
                     bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w"
                     ).pack(fill="x")

            # Scrollable list so many accounts still fit.
            canvas = tk.Canvas(f, bg=C_BG3, highlightthickness=0,
                               height=min(rows_h, 240))
            canvas.pack(side="left", fill="both", expand=True, pady=(4, 0))
            sb = tk.Scrollbar(f, orient="vertical", command=canvas.yview)
            inner = tk.Frame(canvas, bg=C_BG3)
            win_id = canvas.create_window((0, 0), window=inner, anchor="nw")
            canvas.configure(yscrollcommand=sb.set)

            def _on_inner(_e=None):
                canvas.configure(scrollregion=canvas.bbox("all"))
                canvas.itemconfigure(win_id, width=canvas.winfo_width())
            inner.bind("<Configure>", _on_inner)
            canvas.bind("<Configure>", _on_inner)
            # Only show the scrollbar when it is actually needed.
            if rows_h > 240:
                sb.pack(side="right", fill="y", pady=(4, 0))

                def _wheel(e):
                    canvas.yview_scroll(int(-e.delta / 120), "units")
                canvas.bind_all("<MouseWheel>", _wheel)
                top.bind("<Destroy>", lambda e: canvas.unbind_all("<MouseWheel>"))

            per = dict(self.cfg.get("account_intervals", {}) or {})
            for a in reals:
                email = a.get("email")
                r = tk.Frame(inner, bg=C_BG3)
                r.pack(fill="x", pady=2)
                dot = a.get("color") or C_FG_DIM
                tk.Label(r, text="●", bg=C_BG3, fg=dot,
                         font=("Segoe UI", 10)).pack(side="left", padx=(0, 4))
                tk.Label(r, text=(a.get("name") or email), bg=C_BG3, fg=C_FG,
                         width=26, anchor="w", font=("Segoe UI", 9)
                         ).pack(side="left")
                if email in per:
                    init = label_by_min.get(int(per[email] or 0), "Off")
                else:
                    init = USE_DEFAULT
                v = tk.StringVar(value=init)
                account_vars[email] = v
                _om(r, v, [USE_DEFAULT] + [lab for lab, _m in CHOICES]
                    ).pack(side="left")

        # ── Local cache switch ───────────────────────────────────────────────
        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x", padx=18)
        cf = tk.Frame(top, bg=C_BG3)
        cf.pack(fill="x", padx=18, pady=(8, 4))
        v_cache = tk.BooleanVar(value=bool(self.cfg.get("cache_enabled", True)))
        tk.Checkbutton(cf, text="Keep a local copy of messages so updates are "
                               "fast (recommended)",
                       variable=v_cache, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9), highlightthickness=0,
                       anchor="w").pack(fill="x")
        try:
            mb_size = _cache_size_bytes() / (1024 * 1024)
        except Exception:
            mb_size = 0.0
        crow = tk.Frame(cf, bg=C_BG3)
        crow.pack(fill="x", pady=(2, 0))
        tk.Label(crow, text=f"Downloaded once, then only new mail is fetched.  "
                            f"Cache size: {mb_size:.1f} MB",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8),
                 anchor="w").pack(side="left")

        def _clear_cache():
            if not messagebox.askyesno(
                    "Clear cache",
                    "Delete the local copy of all downloaded messages?\n\n"
                    "Nothing on Gmail is touched — the next refresh simply "
                    "downloads them again.", parent=top):
                return
            _cache_clear_all()
            self._flash("Local cache cleared")
        tk.Button(crow, text="Clear cache", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 8), relief="flat", cursor="hand2",
                  padx=10, pady=2, command=_clear_cache).pack(side="right")

        # ── Save / Cancel ────────────────────────────────────────────────────
        def _save(event=None):
            self.cfg["check_interval_min"] = min_by_label.get(v_default.get(), 0)
            newper = {}
            for email, var in account_vars.items():
                lab = var.get()
                if lab != USE_DEFAULT:
                    newper[email] = min_by_label.get(lab, 0)
            self.cfg["account_intervals"] = newper
            self.cfg["cache_enabled"]     = bool(v_cache.get())
            _save_settings(self.cfg)
            self._reschedule_autocheck()
            top.destroy()
            self._flash("Auto-check settings saved")

        top.bind("<Return>", _save)
        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(pady=10)
        tk.Button(btns, text="Save", bg=C_BTN_NEW, fg=C_BTN_FG,
                  font=("Segoe UI", 9, "bold"), relief="flat", cursor="hand2",
                  padx=18, pady=4, command=_save).pack(side="left", padx=5)
        tk.Button(btns, text="Cancel", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=18, pady=4, command=top.destroy).pack(side="left", padx=5)

    # ── Account list (real or demo) ────────────────────────────────────────────
    def _rebuild_accounts(self):
        """Build self._accounts from the credential store, or fall back to
        DEMO mode (mock data) when no real account has been added yet."""
        real = self._account_store.get("accounts", [])
        if real:
            self._demo_mode = False
            default_sender = (self._account_store.get("default_sender")
                              or real[0]["email"])
            self._accounts = [{
                "email":   ALL_ACCOUNTS_ID,
                "name":    "All Accounts",
                "unread":  0,
                "virtual": True,
                "default_sender": default_sender,
            }]
            for a in real:
                self._accounts.append({
                    "email":   a["email"],
                    "name":    a.get("name") or a["email"],
                    "unread":  0,
                    "virtual": False,
                    "secret":  a.get("secret", ""),
                })
        else:
            self._demo_mode = True
            self._accounts = _mock_accounts()
        self._assign_account_colors()

    def _assign_account_colors(self):
        """Give every real account a stable colour (DEL 09c).

        Custom colours (Accounts → Account colours…) win; the rest are handed
        out from ACCOUNT_PALETTE in order. Builds self._acct_colors, an
        email → hex map used by the sidebar and the message list."""
        custom = self._account_store.get("colors", {}) if self._account_store else {}
        self._acct_colors = {}
        idx = 0
        for a in self._accounts:
            if a.get("virtual"):
                continue
            email = a.get("email", "")
            col = custom.get(email) or ACCOUNT_PALETTE[idx % len(ACCOUNT_PALETTE)]
            a["color"] = col
            self._acct_colors[email] = col
            idx += 1

    def _contact_color(self, msg):
        """Return the assigned colour for a message's sender, or None.
        First matching contact rule wins (substring on address or name)."""
        hay = (msg.get("from", "") + " " + msg.get("from_name", "")).lower()
        for c in self._contacts_store.get("contacts", []):
            mt = (c.get("match") or "").strip().lower()
            if mt and mt in hay:
                return c.get("color")
        return None

    def _secret_for(self, email_addr) -> str:
        for a in self._accounts:
            if a.get("email") == email_addr and not a.get("virtual"):
                return _decrypt_secret(a.get("secret", ""))
        return ""

    # ── Menu bar ──────────────────────────────────────────────────────────────
    def _build_menu(self):
        mb = tk.Menu(self.root, bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                     activeforeground=C_FG, relief="flat", tearoff=0)

        # File
        m_file = tk.Menu(mb, bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                         activeforeground=C_FG, tearoff=0)
        m_file.add_command(label="New Message    Ctrl+N", command=self._compose_new)
        # Two kinds of note, and they are different jobs — see DEL 04g3.
        m_file.add_command(label="📌 Post-it notes…   Ctrl+Shift+T",
                           command=self._postit_board)
        m_file.add_command(label="Long note (compose window)    Ctrl+T",
                           command=self._new_note)
        m_file.add_command(label="Outbox…", command=self._outbox_dialog)
        m_file.add_separator()
        m_file.add_command(label="Open the Notes folder…",
                           command=self._open_notes_folder)
        m_file.add_command(label="Change the Notes folder…",
                           command=self._notes_folder_dialog)
        m_file.add_separator()
        m_file.add_command(label="Save message as PDF…",
                           command=lambda: (self._save_msg_pdf(self._selected_msg)
                                            if self._selected_msg else
                                            messagebox.showinfo(
                                                "Save as PDF",
                                                "Select a message first.",
                                                parent=self.root)))
        m_file.add_command(label="Import old mail and contacts…",
                           command=self._import_dialog)
        m_file.add_command(label="Tidy drafts…  (ones already sent)",
                           command=self._tidy_drafts_dialog)
        m_file.add_command(label="Export mail to a file…",
                           command=self._export_mail_dialog)
        m_file.add_command(label="Restore mail from a file…",
                           command=self._restore_mail_dialog)
        m_file.add_command(label="Local archive…", command=self._archive_dialog)
        m_file.add_command(label="Backup…", command=self._backup_dialog)
        m_file.add_separator()
        m_file.add_command(label="Exit", command=self._on_close)
        mb.add_cascade(label="File", menu=m_file)

        # Accounts (stub — Claude Code will add OAuth here)
        m_acc = tk.Menu(mb, bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                        activeforeground=C_FG, tearoff=0)
        m_acc.add_command(label="Add Gmail account…",
                          command=self._add_account_dialog)
        m_acc.add_command(label="Remove account…",
                          command=self._remove_account_dialog)
        m_acc.add_command(label="Refresh folder list",
                          command=lambda: self._refresh_folder_tree(announce=True))
        m_acc.add_command(label="Export / import accounts…",
                          command=self._accounts_io_dialog)
        m_acc.add_separator()
        m_acc.add_command(label="Address book…",
                          command=self._addressbook_dialog)
        m_acc.add_command(label="Contact colours…",
                          command=self._contacts_dialog)
        m_acc.add_command(label="Account colours…",
                          command=self._account_colours_dialog)
        m_acc.add_command(label="Attachment auto-save rules…",
                          command=self._autosave_rules_dialog)
        m_acc.add_command(label="Signatures…", command=self._signatures_dialog)
        m_acc.add_command(label="Automatic folders…",
                          command=self._folderplans_dialog)
        m_acc.add_command(label="Folder ageing…",
                          command=lambda: self._folderage_dialog())
        m_acc.add_command(label="Browser profiles…",
                          command=self._browser_profiles_dialog)
        m_acc.add_separator()
        m_acc.add_command(label="📱  Phone sync (Issu's Freemail app)…",
                          command=self._phone_sync_dialog)
        mb.add_cascade(label="Accounts", menu=m_acc)

        # Tools — auto-check interval (read-only background refresh)
        m_tools = tk.Menu(mb, bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                          activeforeground=C_FG, tearoff=0)
        m_tools.add_command(label="Check for new mail now",
                            command=self._check_now)
        m_tools.add_command(label="Auto-check for new mail…",
                            command=self._autocheck_dialog)
        m_tools.add_separator()
        m_tools.add_command(label="Mail filters…", command=self._filters_dialog)
        m_tools.add_command(label="Rule health…  (which rules actually work)",
                            command=self._rule_health_dialog)
        m_tools.add_command(label="Storage…  (what is using disk)",
                            command=self._storage_dialog)
        m_tools.add_command(label="Run mail filters now  (loaded mail)",
                            command=self._run_filters_now)
        m_tools.add_command(label="Clean the whole mailbox with a rule…",
                            command=self._sweep_dialog)
        # DEL 51 — a separate thing from the filters on purpose: it never runs
        # by itself, only when he presses the button.
        m_tools.add_command(label="⤴  Relocator — move mail by rule…  "
                                  "(manual only)",
                            command=self.open_relocator)
        m_tools.add_command(label="Why didn't my rule fire?…",
                            command=self._filter_diag_dialog)
        m_tools.add_command(label="Find duplicate mail…",
                            command=self._dup_finder_dialog)
        m_tools.add_command(label="Mail with no body…  (find & repair empty "
                                  "copies)",
                            command=self._empty_body_dialog)
        m_tools.add_command(label="Rescue mail from the Trash…  (receipts a "
                                  "rule never filed)",
                            command=self._rescue_trash_dialog)
        m_tools.add_command(label="Cross-account delivery log…",
                            command=self._delivered_dialog)
        m_tools.add_command(label="Hide boilerplate in messages…",
                            command=self._trim_rules_dialog)
        m_tools.add_separator()
        m_tools.add_command(label="Empty the Trash (erase for good)…",
                            command=self._empty_trash)
        # ── Unsubscribes (DEL 04e2) ─────────────────────────────────────────
        # The queue label carries its own count, so a rule that has been
        # quietly collecting newsletters says so from the menu bar rather than
        # waiting to be found.
        m_tools.add_separator()
        self._m_tools = m_tools
        self._unsub_menu_index = m_tools.index("end") + 1
        m_tools.add_command(label=self._unsub_menu_label(),
                            command=self._unsub_queue_dialog)
        m_tools.add_command(label="Unsubscribe log…",
                            command=self._unsub_log_dialog)
        # ── "=C3=A5" instead of "å" (Issu 2026-08-18) ────────────────────────
        # OFF by default and switched on here, exactly as he asked: "en funktion
        # som jag aktiverar (programmet behöver inte läsa av/igenom alla mail)".
        # It only ever looks at the message you have OPEN — never a scan, never
        # a background pass over the mailbox.
        self._fix_enc_var = tk.BooleanVar(
            value=bool(self.cfg.get("fix_broken_encoding", False)))

        m_tools.add_checkbutton(
            label="Repair åäö in mail that shows “=C3=A5”",
            variable=self._fix_enc_var, selectcolor=C_ACCENT,
            command=self._toggle_fix_encoding)
        m_tools.add_command(
            label="Repair åäö in THIS message now",
            command=lambda: self._fix_encoding_now())
        m_tools.add_separator()
        self._filter_diag_var = tk.BooleanVar(
            value=bool(self.cfg.get("filter_diagnostics", True)))
        m_tools.add_checkbutton(
            label="Explain every filter run in the log",
            variable=self._filter_diag_var, selectcolor=C_ACCENT,
            command=lambda: (self.cfg.__setitem__(
                "filter_diagnostics", bool(self._filter_diag_var.get())),
                _save_settings(self.cfg)))
        m_tools.add_command(label="Templates…",    command=self._templates_dialog)
        m_tools.add_command(label="Snippets…  (often-used text)",
                            command=self._snippets_dialog)
        m_tools.add_command(label="Blocked / trusted / kept-unread senders…",
                            command=self._blocklist_dialog)
        # Phishing: how hard the brand-impersonation check tries (DEL 04e)
        self._phish_level_var = tk.StringVar(
            value=str(self.cfg.get("phish_brand_level", "balanced")))
        m_phish = tk.Menu(m_tools, bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                          activeforeground=C_FG, tearoff=0)
        for label, val in [
                ("Off — no brand-name check", "off"),
                ("Domain in name only (safest)", "domain"),
                ("Balanced (recommended)", "balanced"),
                ("Aggressive (more warnings)", "aggressive")]:
            m_phish.add_radiobutton(label=label, value=val,
                                    variable=self._phish_level_var,
                                    command=self._on_phish_level_changed)
        m_tools.add_cascade(label="Phishing: fake-sender warnings", menu=m_phish)
        m_tools.add_separator()
        m_tools.add_command(label="Sending & deleting (undo, drafts)…",
                            command=self._sending_dialog)
        m_tools.add_command(label="Notifications…",
                            command=self._notifications_dialog)
        m_tools.add_command(label="Reading (mark-read timing, read ahead)…",
                            command=self._reading_dialog)
        m_tools.add_command(label="Search: what to leave out…  (folders & "
                                  "accounts)",
                            command=self._search_exclude_dialog)
        m_tools.add_separator()
        m_tools.add_command(label="Set as default mail client…",
                            command=self._default_client_dialog)
        m_tools.add_separator()
        m_tools.add_command(label="Archive folder (“Send & archive”)…",
                            command=self._archive_folder_dialog)
        m_tools.add_command(label="Server changes (delete on Gmail)…",
                            command=self._server_changes_dialog)
        mb.add_cascade(label="Tools", menu=m_tools)

        # View — how the message list is arranged
        m_view = tk.Menu(mb, bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                         activeforeground=C_FG, tearoff=0)
        self._thread_view_var = tk.BooleanVar(
            value=bool(self.cfg.get("thread_view", False)))
        m_view.add_checkbutton(
            label="Auto-merge conversations (off = one row per message)",
            variable=self._thread_view_var,
            command=self._on_thread_view_changed)
        m_view.add_command(
            label="Merge selected messages…",
            command=self._merge_selected_from_menu)
        m_view.add_separator()
        # ── Sidebar folder layout ────────────────────────────────────────────
        self._compact_var = tk.BooleanVar(
            value=bool(self.cfg.get("compact_folders", True)))
        m_view.add_checkbutton(
            label="Compact folder list (side-by-side columns)",
            variable=self._compact_var, command=self._on_compact_changed)
        self._merge_dup_var = tk.BooleanVar(
            value=bool(self.cfg.get("merge_duplicate_folders", True)))
        m_view.add_checkbutton(
            label="Merge duplicate folders (Junk, Skickat, Utkast…)",
            variable=self._merge_dup_var, command=self._on_merge_dup_changed)
        m_view.add_separator()
        m_view.add_command(label="Expand all conversations",
                           command=lambda: self._expand_all(True))
        m_view.add_command(label="Collapse all conversations",
                           command=lambda: self._expand_all(False))
        m_view.add_separator()
        self._real_addr_var = tk.BooleanVar(
            value=bool(self.cfg.get("show_real_address", False)))
        m_view.add_checkbutton(
            label="Always show the sender's real address",
            variable=self._real_addr_var, command=self._toggle_real_address)
        m_view.add_command(label="Message source…   Ctrl+U",
                           command=self._show_message_source)
        m_view.add_separator()
        m_view.add_command(label="Search window…   Ctrl+Shift+F",
                           command=lambda: self.open_search_window(
                               "" if self.e_search.get() == "Search mail…"
                               else self.e_search.get().strip()))
        m_view.add_separator()
        m_view.add_command(label="Select all    Ctrl+A",
                           command=lambda: self._select_all(True))
        m_view.add_command(label="Select none",
                           command=lambda: self._select_all(False))
        m_view.add_separator()
        m_view.add_command(label="Tags…", command=self._tags_dialog)
        m_view.add_separator()
        m_view.add_command(label="What needs me?", command=self._needs_me_dialog)
        m_view.add_command(label="Attachments…",
                           command=self._attachments_dialog)
        m_view.add_command(label="Senders & newsletters…",
                           command=self._senders_dialog)
        m_view.add_command(label="Statistics…", command=self._stats_dialog)
        m_view.add_command(label="Save the current search…",
                           command=self._save_current_search)
        mb.add_cascade(label="View", menu=m_view)

        # Calendar (DEL 04f/06d/09d)
        m_cal = tk.Menu(mb, bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                        activeforeground=C_FG, tearoff=0)
        m_cal.add_command(label="Open calendar…   Ctrl+K",
                          command=self._open_calendar)
        m_cal.add_command(label="New event…", command=self._new_event_dialog)
        m_cal.add_command(label="⏱ Quick timer…  (stand up / oven off)",
                          command=self._quick_timer_dialog)
        m_cal.add_separator()
        m_cal.add_command(label="Add selected message to calendar…",
                          command=lambda: (
                              self._add_message_to_calendar(self._selected_msg)
                              if self._selected_msg else
                              messagebox.showinfo("Calendar",
                                                  "Select a message first.",
                                                  parent=self.root)))
        mb.add_cascade(label="Calendar", menu=m_cal)

        # Help
        m_help = tk.Menu(mb, bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                         activeforeground=C_FG, tearoff=0)
        m_help.add_command(label="Help…   F1",    command=lambda: _show_help(self.root))
        m_help.add_command(label="About F(re)email", command=lambda: _show_about(self.root))
        mb.add_cascade(label="Help", menu=m_help)

        self.root.configure(menu=mb)
        self.root.bind("<F1>", lambda e: _show_help(self.root))

    # ── Toolbar ───────────────────────────────────────────────────────────────
    def _build_toolbar(self):
        tb = tk.Frame(self.root, bg=C_BG1, pady=5)
        tb.pack(fill="x")

        # ── Narrow buttons (Issu 2026-08-23) ─────────────────────────────
        # "Contacts, refresh, Log o.s.v. — de knapparna kan bli mindre breda
        #  så att programmet inte måste vara så bred." Fourteen buttons at
        #  10 px of padding each side plus 4 px between them spend about 200
        #  px on nothing but air, and that air is what forces the window
        #  wide. The text is untouched — a button you cannot read is not
        #  narrower, it is gone.
        def _btn(text, color, cmd, side="left", tip=None):
            b = tk.Button(tb, text=text, bg=color, fg=C_BTN_FG,
                          font=("Segoe UI", 9), relief="flat",
                          padx=5, pady=3, cursor="hand2",
                          command=cmd)
            b.pack(side=side, padx=2)
            if tip:
                add_tooltip(b, tip)
            return b

        _btn("✉ New Message", C_BTN_NEW, self._compose_new,
             tip="Write a brand-new email.")
        _btn("📌 Notes",      C_BTN_NOTE, self._postit_board,
             tip="Your post-it board: small notes you jot down and read at a "
                 "glance. Kept as one plain-text file on your own disk — it "
                 "never touches any mail server.")
        tk.Frame(tb, bg=C_SEP, width=1).pack(side="left", fill="y", padx=4)
        _btn("↩ Reply",      C_BTN_REPLY, self._reply,
             tip="Reply to the selected message. The original stays visible "
                 "beside a clean answer box.")
        self._reply_all_var = tk.BooleanVar(value=True)
        chk_reply_all = tk.Checkbutton(
            tb, text="All", variable=self._reply_all_var,
            bg=C_BG1, fg=C_FG_DIM, selectcolor=C_BG2,
            activebackground=C_BG1, activeforeground=C_FG,
            font=("Segoe UI", 8), highlightthickness=0, relief="flat",
            padx=2, cursor="hand2")
        chk_reply_all.pack(side="left", padx=(0, 4))
        add_tooltip(chk_reply_all,
            "On (default): Reply and Smart Reply also Cc everyone else who "
            "was on the original message — not just the sender. Off: reply "
            "only to the sender, like before.")
        _btn("💬 Smart Reply", C_BTN_STD, self._smart_reply,
             tip="Answer point-by-point UNDER each paragraph of their message — "
                 "your replies are woven in beneath the text they belong to, "
                 "instead of one block on top.")
        _btn("↪ Forward",    C_BTN_STD, self._forward,
             tip="Forward the selected message to someone else.")
        tk.Frame(tb, bg=C_SEP, width=1).pack(side="left", fill="y", padx=4)
        _btn("🗑 Delete",     C_BTN_DEL, self._delete_selected,
             tip="Delete the selected message(s). With several rows ticked, all "
                 "of them go. Deleted mail waits a short while so you can Undo.")
        tk.Frame(tb, bg=C_SEP, width=1).pack(side="left", fill="y", padx=4)
        # ── Contacts, on the main toolbar (Issu 2026-08-08) ──────────────────
        # "Contacts borde vara på huvudsidan… kanske innan Refresh." Exactly
        # here, then — it was buried under Accounts → Address book, which is a
        # long way to go for something you reach for constantly.
        _btn("👥 Contacts",  C_BTN_STD, self._addressbook_dialog,
             tip="Your address book: named contacts, groups, and everyone you "
                 "have written to. Pick people from here when writing.")
        _btn("↻ Refresh",    C_BTN_REFRESH, self._check_now,
             tip="Check for new mail now and run the filters on every account.")
        # ── Activity log (Issu 2026-08-08) ───────────────────────────────────
        # "Behöver ha en knapp-log där jag kan få upp en popup som visar vad
        # som hänt senast, kortfattat." One click, and every message a rule
        # has touched is accounted for — including the ones handled before you
        # ever saw them.
        _btn("🧾 Log",       C_BTN_STD, self._activity_log_dialog,
             tip="What has happened to your mail lately — which rule moved, "
                 "read or binned what, and into which account. Kept when you "
                 "close the program, so mail handled before you looked is "
                 "still explained.")
        # Run Filter — runs EVERY enabled rule (incl. the "only when I run them"
        # ones) over the mail loaded here (Issu 2026-08-02).
        _btn("▶ Run Filter", C_BTN_STD, self._run_filters_now,
             tip="Run every enabled mail filter over the messages loaded here, "
                 "right now — including rules set to run only on demand.")

        _btn("⏰ Notify me",  C_BTN_STD, self._snooze_selected,
             tip="Pop up a notification about this message on a date you "
                 "choose (weeks, months, years). The message is not hidden "
                 "or moved.")
        tk.Frame(tb, bg=C_SEP, width=1).pack(side="left", fill="y", padx=4)
        _btn("📅 Calendar",  C_BTN_STD, self._open_calendar,
             tip="Open the calendar: events, reminders and .ics import/export.")
        _btn("❓ Needs me",  C_BTN_NEW, self._needs_me_dialog,
             tip="Show the mail that is actually waiting on YOU to do something.")

        # The gap between the left half and the search half.
        #
        # Measured while narrowing the toolbar (Issu 2026-08-23), because it
        # looks like it ought to matter and does not: when the toolbar wants
        # more width than the window has, Tk drops the LAST-packed children to
        # one pixel — and moving this spacer to the end of the method changes
        # nothing, the right-hand widgets collapse either way. The only thing
        # that keeps the search box on screen is the toolbar FITTING, which is
        # what the smaller button padding above is for. Left where it is.
        tk.Frame(tb, bg=C_BG1).pack(side="left", fill="x", expand=True)

        # ── Search scope (DEL 04e) ───────────────────────────────────────────
        # "This folder" is the instant local filter that has always been here.
        # The two wider scopes run a REAL read-only IMAP SEARCH on a worker
        # thread, so they cover the whole mailbox and not just what has been
        # downloaded — that is the "filter for all folders at once" feature.
        # "All except…" (Issu 2026-08-17) is the widest one MINUS the folders
        # and accounts you named in Tools → "Search: what to leave out…". It is
        # also the only scope that walks your OWN labels, which is what makes
        # leaving one out mean anything.
        _SCOPES = {
            "This folder":            "folder",
            "All folders":            "all_folders",
            "All folders + accounts": "all_accounts",
            "All except…":            "all_except",
        }
        self._scope_labels = _SCOPES
        cur_scope = self.cfg.get("search_scope", "folder")
        cur_label = next((k for k, v in _SCOPES.items() if v == cur_scope),
                         "This folder")
        self._scope_var = tk.StringVar(value=cur_label)
        om = tk.OptionMenu(tb, self._scope_var, *_SCOPES.keys())
        om.configure(bg=C_BG3, fg=C_FG_DIM, activebackground=C_BG4,
                     activeforeground=C_FG, highlightthickness=0,
                     relief="flat", font=("Segoe UI", 8), padx=4, pady=1)
        om["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                             activeforeground=C_FG, font=("Segoe UI", 9))
        om.pack(side="right", padx=(0, 8))
        add_tooltip(om,
                    "How wide the search box looks.\n\n"
                    "This folder — instant filter of what is already loaded.\n"
                    "All folders — a real read-only IMAP search of the whole "
                    "mailbox: Inbox, Sent, Drafts, Starred, Spam, Trash.\n"
                    "All folders + accounts — the same, for every account.\n"
                    "All except… — every folder of every account INCLUDING "
                    "your own labels, minus the folders and accounts you left "
                    "out in Tools → “Search: what to leave out…”. Use it to "
                    "keep a big archive like 0---Frakt & kvitto out of the "
                    "way.")
        self.e_search = tk.Entry(tb, bg=C_BG3, fg=C_FG_DIM, relief="flat",
                                 font=("Segoe UI", 9), width=26,
                                 insertbackground=C_ACCENT,
                                 insertofftime=0, insertontime=9999999)
        no_blink(self.e_search)
        self.e_search.insert(0, "Search mail…")
        self.e_search.bind("<FocusIn>",  lambda e: (
            self.e_search.delete(0, "end"),
            self.e_search.configure(fg=C_FG)) if self.e_search.get() == "Search mail…" else None)
        self.e_search.bind("<FocusOut>", lambda e: (
            self.e_search.insert(0, "Search mail…"),
            self.e_search.configure(fg=C_FG_DIM)) if not self.e_search.get() else None)
        self.e_search.bind("<Return>", lambda e: self._do_search())
        self.e_search.pack(side="right", padx=(0, 8), ipady=4)
        # ── The search WINDOW, right next to the box (Issu 2026-08-08) ───────
        # The box above filters/searches into the main list. This opens the
        # separate window, where the results are your folder TREE instead of a
        # flat list — so you can see where things actually are. Whatever is
        # already typed in the box comes with it.
        b_sw = tk.Button(tb, text="🔎…", bg=C_BTN_STD, fg=C_BTN_FG,
                         font=("Segoe UI", 8), relief="flat", cursor="hand2",
                         padx=6, pady=1,
                         command=lambda: self.open_search_window(
                             "" if self.e_search.get() == "Search mail…"
                             else self.e_search.get().strip()))
        b_sw.pack(side="right", padx=(0, 4))
        # ── ⤴ Relocator, just before the magnifying glass (Issu 2026-08-23) ──
        # Packed AFTER b_sw with side="right", which is what puts it to the
        # LEFT of it: with side="right" the first one packed sits furthest out.
        b_rl = tk.Button(tb, text="⤴", bg=C_BTN_STD, fg=C_BTN_FG,
                         font=("Segoe UI", 10), relief="flat", cursor="hand2",
                         padx=6, pady=0, command=self.open_relocator)
        b_rl.pack(side="right", padx=(0, 4))
        add_tooltip(b_rl,
                    "⤴ Relocator — move (or delete) mail by rule, and only "
                    "when you press the button.\n\n"
                    "Not the filter engine: filters run on every fetch and "
                    "see only what is downloaded. This asks Gmail itself, so "
                    "it reaches years of mail — and it never runs on its own.")
        add_tooltip(b_sw,
                    "Open the search WINDOW (Ctrl+Shift+F).\n\n"
                    "Searches every folder of every account and shows the "
                    "results as your own folder tree — only the folders that "
                    "actually contain a match — so you can see WHERE things "
                    "are instead of getting one flat list. Choose whether to "
                    "look in the subject, the sender, To/Cc or the message "
                    "text (several at once, each in its own colour), exclude "
                    "hits you are not interested in, and move or protect from "
                    "there. It stays open while you work in this window.")

    # ── Status bar (DEL 09e) ──────────────────────────────────────────────────
    #
    # Everything the program wants to tell you about routine work goes HERE,
    # quietly, instead of popping a box in front of what you are reading.
    # Thunderbird's habit of announcing every pass over the mailbox is exactly
    # the thing to avoid: a line that is always there, that you can glance at,
    # beats an interruption that demands you look.
    #
    # Popups are kept for the two cases that genuinely deserve one: NEW MAIL
    # arriving in the background, and a reminder falling due.

    def _build_statusbar(self):
        bar = tk.Frame(self.root, bg=C_BG1, pady=2)
        bar.pack(side="bottom", fill="x")
        tk.Frame(bar, bg=C_SEP, height=1).pack(fill="x", side="top")

        inner = tk.Frame(bar, bg=C_BG1)
        inner.pack(fill="x", padx=8, pady=2)

        self.sb_check = tk.Label(inner, text="Latest check: —", bg=C_BG1,
                                 fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w")
        self.sb_check.pack(side="left")

        self.sb_extra = tk.Label(inner, text="", bg=C_BG1, fg=C_FG_DIM,
                                 font=("Segoe UI", 8), anchor="w")
        self.sb_extra.pack(side="left", padx=12)

        # ── Mailbox fullness, on the right ───────────────────────────────────
        self.sb_quota = tk.Label(inner, text="", bg=C_BG1, fg=C_FG_DIM,
                                 font=("Segoe UI", 8), anchor="e")
        self.sb_quota.pack(side="right")
        # A small gauge: an outline frame with a coloured fill inside it.
        self.sb_gauge = tk.Frame(inner, bg=C_BG3, width=90, height=8)
        self.sb_gauge.pack(side="right", padx=6, pady=4)
        self.sb_gauge.pack_propagate(False)
        self.sb_gauge_fill = tk.Frame(self.sb_gauge, bg=C_ACCENT, width=0,
                                      height=8)
        self.sb_gauge_fill.place(x=0, y=0, relheight=1.0)
        self._quota_cache = {}      # account -> (used, total, checked_at)

    def _set_status(self, checked=None, extra=None):
        """Update the quiet line. Either part may be left alone."""
        try:
            if checked is not None:
                self.sb_check.configure(
                    text=f"Latest check: {checked.strftime('%H:%M')}")
            if extra is not None:
                self.sb_extra.configure(text=extra)
        except Exception:
            pass

    def _show_quota(self, used, total):
        """Draw the fullness gauge. Amber past 80 %, red past 95 % — the two
        points where it stops being trivia and starts being a problem."""
        try:
            if not total:
                self.sb_quota.configure(text="")
                self.sb_gauge_fill.configure(width=0)
                return
            pct = max(0.0, min(1.0, used / total))
            colour = ("#c0392b" if pct >= 0.95 else
                      "#d68910" if pct >= 0.80 else C_ACCENT)
            self.sb_gauge_fill.configure(bg=colour)
            self.sb_gauge_fill.place(relwidth=pct)
            self.sb_quota.configure(
                text=f"{_human_size(used)} of {_human_size(total)}"
                     f"  ({pct * 100:.0f}%)",
                fg=colour if pct >= 0.80 else C_FG_DIM)
        except Exception as e:
            log.debug("quota display: %s", e)

    def _quota_target_account(self):
        """Which account the gauge shows: the one selected, or the first real
        one when the unified view is open."""
        if self._current_acct != ALL_ACCOUNTS_ID:
            return self._current_acct
        for a in self._accounts:
            if not a.get("virtual"):
                return a["email"]
        return ""

    # ── Two-panel layout (sidebar | message list) ─────────────────────────────
    def _build_panels(self):
        self.pane = tk.PanedWindow(self.root, orient="horizontal",
                                   bg=C_SEP, sashwidth=4,
                                   sashrelief="flat", handlesize=0)
        self.pane.pack(fill="both", expand=True)

        self._build_sidebar()
        self._build_right_panel()

        # Restore sash positions after geometry is set. A single after(100)
        # was NOT enough on a cold-boot autostart: the window/panes are still
        # being laid out (only a few pixels tall) at 100 ms, so sash_place got
        # clamped to the minimum — leaving the message list one row tall — and
        # then _on_configure saved that clamped value back over the good one.
        # _restore_sashes waits until the panes actually have their real height
        # before placing, and flips self._sash_ready only once that succeeds.
        sl = self.cfg.get("sash_left", 220)
        sr = self.cfg.get("sash_right", 320)
        self.root.after(50, lambda: self._restore_sashes(sl, sr))

        # Remember the divider positions whenever YOU drag one. _on_configure
        # only fires when the whole window is resized/moved, so a sash drag on
        # its own was never saved — which is why the reading pane kept coming
        # back tiny (one message) no matter how far you dragged it down.
        self.pane.bind("<ButtonRelease-1>", self._remember_sashes)
        self.rpane.bind("<ButtonRelease-1>", self._remember_sashes)

    def _restore_sashes(self, sl, sr, attempts=0, last_dims=None):
        """Place both dividers at their saved positions — but only once the
        panes have stopped growing, i.e. the layout has settled.

        On a normal in-session start this settles on the first tick. On a
        cold-boot autostart the window/panes are laid out only a few pixels
        tall for the first frames; placing then would clamp the message list
        to one row. So we wait until the pane width/height are BOTH non-trivial
        AND unchanged from the previous 50 ms tick (a robust "layout settled"
        signal that does not depend on how large the saved sash happens to be),
        retrying for up to ~3 s. Only after actually placing do we set
        _sash_ready, the gate that lets _on_configure save sash coords."""
        try:
            self.root.update_idletasks()
            pw = self.pane.winfo_width()          # horizontal pane → left sash x
            ph = self.rpane.winfo_height()         # vertical pane   → right sash y
            settled = (pw > 200 and ph > 150 and last_dims == (pw, ph))
            if not settled and attempts < 60:
                self.root.after(
                    50, lambda: self._restore_sashes(sl, sr, attempts + 1,
                                                     (pw, ph)))
                return
            self.pane.sash_place(0, sl, 0)
            self.rpane.sash_place(0, 0, sr)
        except Exception:
            pass
        # Whether we placed cleanly or gave up after ~3 s, stop blocking saves.
        self._sash_ready = True

    def _remember_sashes(self, _event=None):
        """Store both divider positions in the settings (written on exit).

        Skipped until _sash_ready, so closing the program before the panes
        have been restored (a very fast open/close after a cold-boot
        autostart) cannot save a clamped, one-message-tall value over the
        good one."""
        if not getattr(self, "_sash_ready", False):
            return
        try:
            self.cfg["sash_left"]  = self.pane.sash_coord(0)[0]
            self.cfg["sash_right"] = self.rpane.sash_coord(0)[1]
        except Exception:
            pass

    # ── LEFT: Folder sidebar ──────────────────────────────────────────────────
    def _build_sidebar(self):
        sidebar = tk.Frame(self.pane, bg=C_BG1, width=220)
        self.pane.add(sidebar, minsize=140)

        # Logo / branding strip
        tk.Label(sidebar, text="✉  F(re)email", bg=C_BG1, fg=C_ACCENT,
                 font=("Segoe UI", 11, "bold"), pady=10).pack(fill="x")
        # A 2-pixel edge that lights up when the arrow keys drive THIS pane
        # (DEL 09f). Static: it changes when you press Left/Right, never on a
        # timer — nothing in this program is allowed to blink.
        self._nav_edge_folders = tk.Frame(sidebar, bg=C_BG1, height=2)
        self._nav_edge_folders.pack(fill="x")
        tk.Frame(sidebar, bg=C_SEP, height=1).pack(fill="x")

        # Scrollable area for accounts + folders
        canvas = tk.Canvas(sidebar, bg=C_BG1, highlightthickness=0)
        sb = tk.Scrollbar(sidebar, orient="vertical", command=canvas.yview,
                          bg=C_BG3, troughcolor=C_BG1)
        sb.pack(side="right", fill="y")
        canvas.configure(yscrollcommand=sb.set)
        canvas.pack(fill="both", expand=True)

        inner = tk.Frame(canvas, bg=C_BG1)
        cwin  = canvas.create_window((0, 0), window=inner, anchor="nw")
        inner.bind("<Configure>",
                   lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
        canvas.bind("<Configure>",
                    lambda e: canvas.itemconfig(cwin, width=e.width))
        _bind_mousewheel(inner, canvas)

        self.sidebar_inner = inner
        self._populate_sidebar(inner)

    def _populate_sidebar(self, parent):
        for widget in parent.winfo_children():
            widget.destroy()
        # Rebuilt on every redraw: the ordered list of clickable folder rows,
        # so Up/Down in the left pane walks exactly what you can see (DEL 09f).
        self._folder_rows = []

        # Per-account collapse + "mini" folder hiding (DEL 09c)
        collapsed_set = set(self.cfg.get("collapsed_accounts", []))
        mini_hidden   = set(self.cfg.get("mini_hidden_folders", []))

        for acct in self._accounts:
            is_all   = acct.get("virtual", False)
            acct_col = acct.get("color")   # None for the virtual "All Accounts"
            collapsed = acct["email"] in collapsed_set

            # ── Account header row ────────────────────────────────────────────
            a_bg = "#1a1e35" if is_all else C_BG3
            a_frame = tk.Frame(parent, bg=a_bg, pady=1)
            a_frame.pack(fill="x", pady=(8 if is_all else 4, 1))

            # Unread on the account header = its Inbox unread (for All
            # Accounts, the sum of every account's Inbox).
            acct_unread = self._folder_count(acct["email"], "Inbox", is_all=is_all)
            unread_txt = f"  ({acct_unread})" if acct_unread else ""
            icon_txt   = "🌐" if is_all else "✉"
            caret      = "▸" if collapsed else "▾"
            # The account name wears its own colour so you can spot it instantly;
            # the currently-open account is highlighted in the accent blue.
            if acct["email"] == self._current_acct:
                fg_acct = C_ACCENT
            elif acct_col:
                fg_acct = acct_col
            else:
                fg_acct = C_FG
            font_acct  = ("Segoe UI", 9, "bold") if is_all else ("Segoe UI", 8, "bold")

            if is_all:
                # "All Accounts" gets a separator line above it
                tk.Frame(parent, bg=C_SEP, height=1).pack(fill="x", pady=(0, 2))

            hdr_lbl = tk.Label(a_frame,
                     text=f"  {caret} {icon_txt}  {acct['name']}{unread_txt}",
                     bg=a_bg, fg=fg_acct,
                     font=font_acct,
                     anchor="w", cursor="hand2")
            hdr_lbl.pack(fill="x", padx=4, pady=2)
            # Click the account name to fold / unfold its folder list;
            # right-click it for this account's own menu (auto-check interval,
            # default sender, colour, remove…).
            hdr_lbl.bind("<Button-1>",
                         lambda e, a=acct["email"]: self._toggle_account_collapse(a))
            hdr_lbl.bind("<Button-3>",
                         lambda e, a=acct["email"], v=is_all:
                         self._account_context_menu(e, a, v))
            hdr_lbl.bind("<Enter>", lambda e, w=hdr_lbl: w.configure(bg=C_BG4))
            hdr_lbl.bind("<Leave>", lambda e, w=hdr_lbl, b=a_bg: w.configure(bg=b))

            if is_all:
                tk.Frame(parent, bg=C_SEP, height=1).pack(fill="x")

            # ── Custom-folder tree for this account ───────────────────────────
            # Built once per account: children of INBOX render directly under
            # the Inbox row (Issu's request), everything else as its own
            # top-level subtree after the standard folders. Only for real
            # accounts (labels are per-account). The tree renders in BOTH the
            # expanded and the collapsed account view — collapse now only hides
            # the individual folders you have marked "only when expanded"
            # (mini_hidden), exactly like the standard folders.
            inbox_children, toplevel = [], []
            if not is_all:
                ufolders = self._user_folders.get(acct["email"], [])
                if ufolders:
                    inbox_children, toplevel = self._build_folder_tree(ufolders)
                    # Hide Thunderbird duplicate folders (Junk/Skickat/Utkast…)
                    # since the real Gmail folder is already in the list.
                    if self.cfg.get("merge_duplicate_folders", True):
                        inbox_children = [n for n in inbox_children
                                          if not self._is_dup_folder_node(n)]
                        toplevel = [n for n in toplevel
                                    if not self._is_dup_folder_node(n)]
                    self._seed_folder_expansion(acct["email"],
                                                inbox_children, toplevel)

            # ── Folders under this account ────────────────────────────────────
            # When collapsed, only the folders you have NOT parked in
            # mini_hidden are drawn. Right-click a folder to move it in or out.
            #
            # COMPACT layout (default): Inbox stays a full-width row (it owns the
            # custom-folder tree); every other standard folder is packed into the
            # multi-column rows below. NORMAL layout: one folder per row.
            compact = bool(self.cfg.get("compact_folders", True))
            loop_folders = ["Inbox"] if compact else _FOLDERS
            for folder in loop_folders:
                if collapsed and self._mini_key(acct["email"], folder) in mini_hidden:
                    continue
                is_sel = (acct["email"] == self._current_acct and
                          folder == self._current_folder)
                bg_f = C_FOLD_SEL if is_sel else (a_bg if is_all else C_BG1)
                fg_f = C_FG if is_sel else C_FG_DIM

                # Unread "(N)" on any server-backed folder that has unread.
                # Virtual folders (Notes/Snoozed/Follow-ups) are local and have
                # no server UNSEEN count, so they never get one.
                fcount = (0 if folder in _VIRTUAL_FOLDERS
                          else self._folder_count(acct["email"], folder, is_all=is_all))
                muted = (folder not in _VIRTUAL_FOLDERS
                         and self._is_count_muted(acct["email"], folder))
                badge = (f"  ({fcount})" if fcount
                         else "  🔕" if muted else "")
                # 🔒 = protected: no rule may move mail out of it.
                if self._is_protected(acct["email"], folder):
                    badge += "  🔒"
                icon  = {"Inbox":    "📥", "Starred": "⭐", "Sent":     "📤",
                         "Drafts":   "📝", "Spam":    "⚠",  "Trash":    "🗑",
                         "All Mail": "🗂", "Notes":   "🗒",  "Snoozed":  "⏰",
                         "Follow-ups": "🔔", "Deleted": "♻",
                         }.get(folder, "📁")

                # A folder marked "hidden while collapsed" gets a small dot so
                # you can see, while expanded, what will vanish when you fold.
                mini_mark = " ·" if (not is_all and
                                     self._mini_key(acct["email"], folder) in mini_hidden) else ""

                # Does the Inbox row own a subtree of custom folders?
                inbox_has_tree = (folder == "Inbox" and bool(inbox_children))
                inbox_open = (inbox_has_tree and
                              self._folder_is_expanded(acct["email"], "__INBOX__"))

                # One row = a thin colour strip (this account's colour) + an
                # optional twisty (only Inbox, when it has a subtree) + label.
                row = tk.Frame(parent, bg=bg_f)
                row.pack(fill="x")
                tk.Frame(row, bg=(acct_col or bg_f), width=3).pack(side="left", fill="y")
                if inbox_has_tree:
                    tw = tk.Label(row, text=("▾" if inbox_open else "▸"),
                                  bg=bg_f, fg=C_ACCENT, font=("Segoe UI", 8),
                                  width=2, cursor="hand2")
                    tw.pack(side="left")
                    tw.bind("<Button-1>",
                            lambda e, a=acct["email"]:
                            self._toggle_folder_expand(a, "__INBOX__"))

                lbl = tk.Label(row,
                               text=f"   {icon}  {folder}{badge}{mini_mark}",
                               bg=bg_f, fg=fg_f,
                               font=("Segoe UI", 9),
                               anchor="w", cursor="hand2")
                lbl.pack(side="left", fill="x", expand=True)
                lbl.bind("<Button-1>",
                         lambda e, a=acct["email"], f=folder: self._select_folder(a, f))
                lbl.bind("<Button-3>",
                         lambda e, a=acct["email"], f=folder: self._folder_context_menu(e, a, f))
                lbl.bind("<Enter>",
                         lambda e, w=lbl, s=is_sel: w.configure(bg=C_BG4) if not s else None)
                lbl.bind("<Leave>",
                         lambda e, w=lbl, b=bg_f: w.configure(bg=b))
                self._folder_rows.append((acct["email"], folder, lbl))

                # Notes rides on the Inbox row (compact mode) — Issu's request,
                # so it does not take a whole row of its own.
                if (compact and folder == "Inbox"
                        and not (collapsed and self._mini_key(acct["email"],
                                                              "Notes") in mini_hidden)):
                    self._folder_cell(row, "Notes", acct, is_all, mini_hidden,
                                      expand=False)

                # Inbox's own sub-folders, indented directly beneath it.
                if inbox_has_tree and inbox_open:
                    for child in inbox_children:
                        self._render_folder_node(parent, child, acct,
                                                 acct_col, depth=1,
                                                 collapsed=collapsed,
                                                 mini_hidden=mini_hidden)

            # ── Compact multi-column rows for every non-Inbox folder ──────────
            if compact:
                self._render_compact_folders(parent, acct, acct_col, is_all,
                                             collapsed, mini_hidden)

            # ── Top-level custom labels (not under Inbox) ─────────────────────
            for node in toplevel:
                self._render_folder_node(parent, node, acct, acct_col, depth=0,
                                         collapsed=collapsed,
                                         mini_hidden=mini_hidden)

        # ── Saved searches, at the foot of the sidebar (DEL 04m) ─────────────
        searches = self._search_store.get("searches", [])
        if searches:
            tk.Frame(parent, bg=C_SEP, height=1).pack(fill="x", pady=(6, 2))
            tk.Label(parent, text="  🔎  Saved searches", bg=C_BG1,
                     fg=C_FG_DIM, font=("Segoe UI", 8, "bold"),
                     anchor="w").pack(fill="x", pady=(0, 2))
            for s in searches:
                lbl = tk.Label(parent, text=f"    🔎  {s.get('name','')}",
                               bg=C_BG1, fg=C_FG_DIM, font=("Segoe UI", 9),
                               anchor="w", cursor="hand2")
                lbl.pack(fill="x")
                lbl.bind("<Button-1>",
                         lambda e, ss=s: self._run_saved_search(ss))
                lbl.bind("<Button-3>",
                         lambda e, ss=s: self._delete_saved_search(ss))
                lbl.bind("<Enter>", lambda e, w=lbl: w.configure(bg=C_BG4))
                lbl.bind("<Leave>", lambda e, w=lbl: w.configure(bg=C_BG1))
            tk.Label(parent, text="      (right-click to delete)", bg=C_BG1,
                     fg="#555a75", font=("Segoe UI", 7),
                     anchor="w").pack(fill="x")

    def _is_dup_folder_node(self, node):
        """A custom folder that just duplicates a standard one (Junk=Spam,
        Skickat=Sent, …) — hidden when "Merge duplicate folders" is on.

        Sent/Skickat/Junk/Utkast/Papperskorg are hidden even if they carry
        sub-folders (that was the second "Sent" with an arrow). Archive-like
        names (Arkiv/Archive/All Mail) are ONLY hidden when they are a bare
        leaf, so a real archive tree of year/month folders is never lost."""
        leaf = (node.get("disp") or node.get("seg") or "").strip().lower()
        if leaf not in _DUP_FOLDER_ALIASES:
            return False
        archive_like = _DUP_FOLDER_ALIASES[leaf] == "All Mail"
        if node.get("children") and archive_like:
            return False
        return True

    def _render_compact_folders(self, parent, acct, acct_col, is_all,
                                collapsed, mini_hidden):
        """Draw the non-Inbox standard folders as side-by-side columns."""
        email   = acct["email"]
        base_bg = "#1a1e35" if is_all else C_BG1
        for group in _COMPACT_ROWS:
            cells = [f for f in group
                     if not (collapsed
                             and self._mini_key(email, f) in mini_hidden)]
            if not cells:
                continue
            row = tk.Frame(parent, bg=base_bg)
            row.pack(fill="x")
            tk.Frame(row, bg=(acct_col or base_bg), width=3).pack(side="left",
                                                                  fill="y")
            for folder in cells:
                self._folder_cell(row, folder, acct, is_all, mini_hidden)

    def _folder_cell(self, row, folder, acct, is_all, mini_hidden, expand=True):
        """One compact folder button, packed to share the row width."""
        email  = acct["email"]
        is_sel = (email == self._current_acct and folder == self._current_folder)
        base_bg = "#1a1e35" if is_all else C_BG1
        bg_f = C_FOLD_SEL if is_sel else base_bg
        fg_f = C_FG if is_sel else C_FG_DIM
        fcount = (0 if folder in _VIRTUAL_FOLDERS
                  else self._folder_count(email, folder, is_all=is_all))
        muted = (folder not in _VIRTUAL_FOLDERS
                 and self._is_count_muted(email, folder))
        badge = f" ({fcount})" if fcount else (" 🔕" if muted else "")
        if self._is_protected(email, folder):
            badge += " 🔒"
        icon  = _FOLDER_ICONS.get(folder, "📁")
        mini_mark = " ·" if (not is_all
                             and self._mini_key(email, folder) in mini_hidden) else ""
        lbl = tk.Label(row, text=f" {icon} {folder}{badge}{mini_mark}",
                       bg=bg_f, fg=fg_f, font=("Segoe UI", 8),
                       anchor="w", cursor="hand2")
        lbl.pack(side="left", fill="x", expand=expand, padx=(0, 2))
        lbl.bind("<Button-1>",
                 lambda e, a=email, f=folder: self._select_folder(a, f))
        lbl.bind("<Button-3>",
                 lambda e, a=email, f=folder: self._folder_context_menu(e, a, f))
        lbl.bind("<Enter>",
                 lambda e, w=lbl, s=is_sel: w.configure(bg=C_BG4) if not s else None)
        lbl.bind("<Leave>", lambda e, w=lbl, b=bg_f: w.configure(bg=b))
        self._folder_rows.append((email, folder, lbl))
        return lbl

    def _select_folder(self, account, folder):
        # Leaving a folder drops its ticks (Issu 2026-09-20). A tick is stored
        # as a message id and an id is a per-folder IMAP UID, so carrying them
        # across would mark whatever mail happens to be number 42 in the folder
        # you just opened. Refreshing the folder you are ALREADY in keeps them
        # — that is _carry_selection's job, and it is a different question.
        self._selected_ids = set()
        self._current_acct   = account
        self._current_folder = folder
        self.cfg["last_account"] = account
        self.cfg["last_folder"]  = folder
        self._fetch_limit = FETCH_LIMIT   # start fresh per folder
        # Clicking a folder puts the arrow keys in the LEFT pane, so Up/Down
        # walks the folder list from where you clicked (DEL 09f).
        self._nav_zone = "folders"
        self._populate_sidebar(self.sidebar_inner)
        self._paint_nav_zone()
        self._sync_trash_button()
        self._refresh_messages()

    def _folder_display_name(self, folder):
        """Human-readable name for the folder title bar. Custom folders keep a
        raw (possibly IMAP-UTF7) mailbox name internally; show the decoded path
        instead. Standard/virtual folders are returned unchanged."""
        for lst in self._user_folders.values():
            for uf in lst:
                if uf["mailbox"] == folder:
                    return uf["full"]
        return folder

    # ── Custom-folder tree: build, seed defaults, expand/collapse (DEL 09c) ────
    def _build_folder_tree(self, ufolders):
        """Turn a flat folder list into a nested tree.

        Returns (inbox_children, toplevel_nodes):
          • inbox_children  — nodes that live under INBOX, so they render
            directly beneath the standard Inbox row (Issu's "under Inbox").
          • toplevel_nodes  — every other top-level label, as its own subtree.
        Each node: {seg, disp, mailbox(None if only a container), path,
                    children:[...]}. Intermediate levels are synthesised even
        when the server did not list the parent on its own."""
        index = {}     # raw path -> node
        roots = {}     # raw top segment -> node

        def _node(path, seg, disp):
            n = index.get(path)
            if n is None:
                n = {"seg": seg, "disp": disp, "mailbox": None,
                     "path": path, "children": {}}
                index[path] = n
            return n

        for uf in sorted(ufolders, key=lambda u: u.get("full", "").lower()):
            raw_parts  = uf.get("raw_parts")  or [uf["mailbox"]]
            disp_parts = uf.get("disp_parts") or [uf.get("display", uf["mailbox"])]
            delim = uf.get("delim", "/")
            path = ""
            parent_children = roots
            node = None
            for i, rseg in enumerate(raw_parts):
                dseg = disp_parts[i] if i < len(disp_parts) else rseg
                path = rseg if i == 0 else path + delim + rseg
                if path not in index:
                    parent_children[rseg] = _node(path, rseg, dseg)
                node = index[path]
                parent_children = node["children"]
            if node is not None:
                node["mailbox"] = uf["mailbox"]   # this exact path is real

        def _to_sorted(children_map):
            nodes = sorted(children_map.values(), key=lambda n: n["disp"].lower())
            for n in nodes:
                n["children"] = _to_sorted(n["children"])
            return nodes

        inbox_children, toplevel = [], []
        for seg, node in roots.items():
            children = _to_sorted(node["children"])
            if seg.upper() == "INBOX":
                inbox_children = children
            else:
                node["children"] = children
                toplevel.append(node)
        toplevel.sort(key=lambda n: n["disp"].lower())
        return inbox_children, toplevel

    def _seed_folder_expansion(self, email, inbox_children, toplevel):
        """First time an account's folders are seen, open the TOP level only —
        so folders directly under Inbox are visible, but their children stay
        folded. A later manual collapse is remembered and never re-opened."""
        seeded = set(self.cfg.get("folders_seeded", []))
        if email in seeded:
            return
        exp = set(self.cfg.get("expanded_folders", []))
        if inbox_children:
            exp.add(f"{email}\t__INBOX__")
        for n in toplevel:
            if n["children"]:
                exp.add(f"{email}\t{n['path']}")
        seeded.add(email)
        self.cfg["expanded_folders"] = sorted(exp)
        self.cfg["folders_seeded"]   = sorted(seeded)

    def _folder_is_expanded(self, email, key):
        return f"{email}\t{key}" in set(self.cfg.get("expanded_folders", []))

    def _toggle_folder_expand(self, email, key):
        full = f"{email}\t{key}"
        exp = set(self.cfg.get("expanded_folders", []))
        if full in exp:
            exp.discard(full)
        else:
            exp.add(full)
        self.cfg["expanded_folders"] = sorted(exp)
        self._populate_sidebar(self.sidebar_inner)

    def _reveal_folder(self, email, name, redraw=True):
        """Unfold the sidebar so a folder is actually VISIBLE (Issu 2026-08-03:
        "ska då inte Freemail hämta hem samma struktur?").

        It always did. The structure was there and the mail was in it — but
        `_seed_folder_expansion` only ever opens the TOP level, so a
        destination two levels down (Inbox → Temporär → 0---Frakt & Kvitto)
        sat inside a folded parent. Mail vanished from the Inbox and appeared
        nowhere you could see, which looks exactly like mail going missing.

        `name` may be the DECODED path a rule stores ("INBOX/Temporär/0---Frakt
        & Kvitto") or the raw IMAP name; both are matched. Every ANCESTOR is
        expanded, never the leaf itself — opening a folder should not also
        unfold whatever happens to live under it."""
        name = (name or "").strip()
        if not name:
            return False
        entries = (self._user_folders or {}).get(email, [])
        raw = None
        low = name.lower()
        for uf in entries:
            if low in ((uf.get("mailbox") or "").lower(),
                       (uf.get("full") or "").lower()):
                raw = uf.get("mailbox")
                break
        if raw is None:                      # not discovered yet — nothing to open
            return False
        delim = next((uf.get("delim", "/") for uf in entries
                      if uf.get("mailbox") == raw), "/")
        parts = raw.split(delim)
        exp = set(self.cfg.get("expanded_folders", []))
        before = len(exp)
        if parts and parts[0].upper() == "INBOX":
            exp.add(f"{email}\t__INBOX__")   # the twisty on the Inbox row
        for i in range(1, len(parts)):       # every parent, never the leaf
            exp.add(f"{email}\t{delim.join(parts[:i])}")
        if len(exp) == before:
            return False                     # already open — leave it alone
        self.cfg["expanded_folders"] = sorted(exp)
        _save_settings(self.cfg)
        log.info("Revealed folder %r for %s in the sidebar", raw, email)
        if redraw:
            self._populate_sidebar(self.sidebar_inner)
        return True

    def _render_folder_node(self, parent, node, acct, acct_col, depth,
                            collapsed=False, mini_hidden=frozenset()):
        """Draw one tree node (a custom folder) and, if it is open, its
        children. A node with children carries a ▸/▾ twisty (click = fold);
        clicking the NAME opens the folder, or folds a name-only container.
        Right-click sets whether it shows while the account is collapsed.

        When the account is collapsed, a node the user has marked
        "only when expanded" (in mini_hidden) is skipped along with its whole
        subtree — you cannot show children of a hidden parent."""
        email = acct["email"]
        if collapsed and self._mini_key(email, node["path"]) in mini_hidden:
            return
        has_children = bool(node["children"])
        expanded     = (self._folder_is_expanded(email, node["path"])
                        if has_children else False)
        is_sel = (node["mailbox"] is not None
                  and email == self._current_acct
                  and node["mailbox"] == self._current_folder)
        bg_f = C_FOLD_SEL if is_sel else C_BG1
        fg_f = C_FG if is_sel else C_FG_DIM

        row = tk.Frame(parent, bg=bg_f)
        row.pack(fill="x")
        tk.Frame(row, bg=(acct_col or bg_f), width=3).pack(side="left", fill="y")
        if depth:
            tk.Frame(row, bg=bg_f, width=14 * depth).pack(side="left")

        if has_children:
            tw = tk.Label(row, text=("▾" if expanded else "▸"), bg=bg_f,
                          fg=C_ACCENT, font=("Segoe UI", 8), width=2,
                          cursor="hand2")
            tw.pack(side="left")
            tw.bind("<Button-1>", lambda e, em=email, k=node["path"]:
                    self._toggle_folder_expand(em, k))
        else:
            tk.Label(row, text="", bg=bg_f, width=2).pack(side="left")

        icon = ("📂" if expanded else "📁")
        # A "·" marks a folder set to appear only when the account is expanded,
        # so while expanded you can see which ones will vanish on collapse.
        mini_mark = " ·" if self._mini_key(email, node["path"]) in mini_hidden else ""
        cnt = self._folder_count(email, node["path"])
        muted = self._is_count_muted(email, node["path"])
        cnt_txt = f"  ({cnt})" if cnt else ("  🔕" if muted else "")
        if node["mailbox"] and self._is_protected(email, node["mailbox"]):
            cnt_txt += "  🔒"
        name = tk.Label(row, text=f"{icon}  {node['disp']}{cnt_txt}{mini_mark}",
                        bg=bg_f, fg=(C_FG_UNRD if cnt else fg_f),
                        font=(("Segoe UI", 9, "bold") if cnt else ("Segoe UI", 9)),
                        anchor="w", cursor="hand2")
        name.pack(side="left", fill="x", expand=True)
        if node["mailbox"]:
            name.bind("<Button-1>", lambda e, em=email, mb=node["mailbox"]:
                      self._select_folder(em, mb))
        elif has_children:
            name.bind("<Button-1>", lambda e, em=email, k=node["path"]:
                      self._toggle_folder_expand(em, k))
        # Right-click any custom folder to control whether it appears while the
        # account is collapsed — keyed per account by its mailbox path.
        name.bind("<Button-3>", lambda e, em=email, k=node["path"], d=node["disp"]:
                  self._folder_context_menu(e, em, k, d))
        name.bind("<Enter>",
                  lambda e, w=name, s=is_sel: w.configure(bg=C_BG4) if not s else None)
        name.bind("<Leave>", lambda e, w=name, b=bg_f: w.configure(bg=b))
        if node["mailbox"]:
            self._folder_rows.append((email, node["mailbox"], name))

        if has_children and expanded:
            for child in node["children"]:
                self._render_folder_node(parent, child, acct, acct_col,
                                         depth + 1, collapsed=collapsed,
                                         mini_hidden=mini_hidden)

    # ── Custom folder discovery (DEL 09c) ─────────────────────────────────────
    def _seed_folder_tree_from_cache(self):
        """Fill the sidebar from the folder list saved at the end of the last
        run, before a single byte goes over the wire.

        Issu 2026-08-19: his sub-folders under Main took 60-90 seconds to
        "exist" after a cold start, because _user_folders began empty and
        nothing could be drawn until five sequential LOGIN+LIST round trips had
        finished. Folder names change about twice a month; asking the server
        before showing them was never worth a minute and a half.

        Silent and best-effort: an account with no cache yet simply waits for
        the scan, as before."""
        if self._demo_mode:
            return
        seeded = 0
        for a in self._accounts:
            if a.get("virtual"):
                continue
            try:
                lst = _folderlist_cache_load(a["email"])
            except Exception:
                lst = []
            if lst:
                self._user_folders[a["email"]] = lst
                seeded += len(lst)
        if not seeded:
            return
        try:
            self._populate_sidebar(self.sidebar_inner)
        except Exception as e:
            log.debug("Sidebar seed from cache failed: %s", e)
            return
        log.info("Sidebar drawn from the saved folder list (%d folder(s)) — "
                 "the scan will correct it in the background", seeded)

    def _refresh_folder_tree(self, announce=False):
        """Discover each real account's custom folders/labels off the main
        thread, then redraw the sidebar so they appear under the standard set.

        `announce=True` gives a flash when done (used by the manual refresh);
        the automatic start-up call stays silent."""
        if self._demo_mode:
            # Demo mode: invent a small tree so the feature is visible without
            # an account. Mirrors the real case: folders nested under INBOX
            # (they appear under the Inbox row) plus a couple of top-level
            # labels. Never fetched — clicking one just shows empty.
            def _demo(path):
                parts = path.split("/")
                return {"mailbox": path, "display": parts[-1], "full": path,
                        "depth": len(parts) - 1, "delim": "/",
                        "raw_parts": parts, "disp_parts": parts}
            demo_paths = [
                "INBOX/Spara",
                "INBOX/Spara/Receipts",
                "INBOX/Spara/Warranties",
                "INBOX/Travel",
                "Projects",
                "Projects/2024",
            ]
            self._user_folders = {
                a["email"]: [_demo(p) for p in demo_paths]
                for a in self._accounts if not a.get("virtual")
            }
            self._populate_sidebar(self.sidebar_inner)
            if announce:
                self._flash("Demo folders shown")
            return

        reals = [a for a in self._accounts if not a.get("virtual")]
        if not reals or self._folders_loading:
            return
        self._folders_loading = True
        if announce:
            self._flash("Loading folder list…")

        def worker():
            result, errors = {}, []
            # ── ONE THREAD PER ACCOUNT, ONE SHARED DEADLINE (Issu 2026-08-19) ─
            # This was a plain sequential loop, and _list_user_folders opens its
            # OWN connection (it is not on the pool): a fresh TLS handshake, a
            # LOGIN, the LIST and a LOGOUT — five times over, one after another.
            # Worse, Loss.THN@gmail.com times out at the full 30-second socket
            # limit several times an hour, and every account listed after it
            # waited that out. That is most of the 60-90 seconds his sub-folders
            # took to appear.
            #
            # Same shape as the message fetch: a thread each, one deadline for
            # the round. An account that does not answer in time keeps whatever
            # it already had — the seeded cache, or its previous answer — rather
            # than being emptied, which is why `result` is only written by a
            # thread that actually succeeded.
            lock = threading.Lock()

            def list_one(a):
                try:
                    pwd = _decrypt_secret(a.get("secret", ""))
                    lst = _list_user_folders(a["email"], pwd)
                    if lst:
                        with lock:
                            result[a["email"]] = lst
                    else:
                        log.debug("Folder list for %s came back empty — "
                                  "keeping what we had", a["email"])
                except Exception as e:
                    with lock:
                        errors.append((a["email"], str(e)))
                    log.warning("Folder list failed for %s: %s", a["email"], e)

            threads = [threading.Thread(target=list_one, args=(a,), daemon=True)
                       for a in reals]
            for t in threads:
                t.start()
            deadline = time.monotonic() + FETCH_DEADLINE_SEC
            for t in threads:
                t.join(timeout=max(0.2, deadline - time.monotonic()))
            late = [a["email"] for a in reals
                    if a["email"] not in result
                    and a["email"] not in {e for e, _ in errors}]
            if late:
                log.info("Folder list drawn without %s — still listing after "
                         "%d s; their folders stay as they were",
                         ", ".join(late), FETCH_DEADLINE_SEC)

            def done():
                self._folders_loading = False
                # A folder deleted a moment ago can still be in Gmail's LIST
                # answer for a while. Keep it out of the sidebar until the
                # server agrees it is gone, then stop remembering it — that is
                # the "hide it in Freemail until Gmail has caught up" Issu
                # asked for, and it expires by itself.
                hidden = set(self.cfg.get("hidden_folders", []) or [])
                if hidden:
                    still, cleaned = set(), False
                    for email, lst in result.items():
                        names = {uf.get("mailbox") for uf in lst}
                        keep = []
                        for uf in lst:
                            if f"{email}\t{uf.get('mailbox')}" in hidden:
                                still.add(f"{email}\t{uf.get('mailbox')}")
                                continue
                            keep.append(uf)
                        result[email] = keep
                        for key in list(hidden):
                            acct, _, mb = key.partition("\t")
                            if acct == email and mb not in names:
                                hidden.discard(key)   # really gone now
                                cleaned = True
                    if cleaned:
                        self.cfg["hidden_folders"] = sorted(hidden)
                        _save_settings(self.cfg)
                    if still:
                        log.info("Still hiding %d just-deleted folder(s) that "
                                 "Gmail is slow to forget", len(still))
                self._user_folders.update(result)
                # Write it down for the next cold start. Only accounts that
                # actually answered are in `result`, so a failed or timed-out
                # listing can never overwrite a good saved list with nothing.
                for email, lst in result.items():
                    _folderlist_cache_save(email, lst)
                try:
                    self._populate_sidebar(self.sidebar_inner)
                except Exception:
                    pass
                # Now that we know the custom folders, count their unread too.
                self._refresh_unread_counts()
                if announce:
                    total = sum(len(v) for v in result.values())
                    self._flash(f"Found {total} custom folder(s)")
            try:
                self.root.after(0, done)
            except Exception:
                pass

        threading.Thread(target=worker, daemon=True).start()

    # ── Unread counts: per-folder "(N)" badges + taskbar signal (DEL 09c) ──────
    def _maybe_refresh_counts(self, force=False):
        """Kick off an unread-count pass, throttled so rapid folder-clicking
        does not open a new IMAP connection every time. Auto-check and the
        manual Refresh effectively force it (they are ≥ the throttle apart)."""
        import time as _t
        if not force and (_t.monotonic() - self._counts_last) < 20:
            return
        self._counts_last = _t.monotonic()
        self._refresh_unread_counts()

    def _refresh_unread_counts(self):
        """Discover each account's per-folder UNSEEN counts off the main thread
        (IMAP STATUS), then repaint the sidebar and the taskbar/title."""
        if self._demo_mode:
            self._folder_unread = {
                a["email"]: {"Inbox": sum(
                    1 for m in _mock_messages("Inbox", a["email"])
                    if m.get("unread"))}
                for a in self._accounts if not a.get("virtual")
            }
            self._populate_sidebar(self.sidebar_inner)
            self._update_unread_ui()
            return

        reals = [a for a in self._accounts if not a.get("virtual")]
        if not reals or self._counts_loading:
            return
        self._counts_loading = True
        std = ["Inbox", "Spam", "All Mail", "Sent", "Drafts", "Trash", "Starred"]

        # ── Walk the CUSTOM labels only occasionally (Issu 2026-08-08) ───────
        # This pass runs with every auto-check, i.e. about once a minute, and
        # on his main account it means 21 STATUS commands (7 standard + 14 of
        # his own labels) down one connection. The standard folders are what
        # the badges are actually watched for; a label that collects filtered
        # receipts does not need re-counting sixty times an hour. Every fifth
        # pass covers the lot, the other four are quick.
        self._count_pass = getattr(self, "_count_pass", 0) + 1
        wide = (self._count_pass % 5 == 1)

        def worker():
            result = {}
            for a in reals:
                _background_yield()
                # An account that is standing down is skipped here too — the
                # badge pass is as automatic as it gets, and a 30-second STATUS
                # timeout inside it holds up every account after it in the loop
                # (Issu 2026-08-17). Last known counts are kept below.
                if _stall_left(a["email"]) > 0:
                    keep = self._folder_unread.get(a["email"])
                    if keep:
                        result[a["email"]] = dict(keep)
                    continue
                try:
                    pwd = _decrypt_secret(a.get("secret", ""))
                    customs = []
                    if wide:
                        customs = [
                            uf["mailbox"]
                            for uf in self._user_folders.get(a["email"], [])
                            # A folder whose count is muted contributes no
                            # badge at all, so asking the server for it is
                            # pure waste.
                            if not self._is_count_muted(a["email"],
                                                        uf["mailbox"])]
                    fresh = _folder_unread_counts(a["email"], pwd, std, customs)
                    if not wide:
                        # Keep the label counts from the last wide pass rather
                        # than dropping them to nothing.
                        keep = dict(self._folder_unread.get(a["email"], {}))
                        keep.update(fresh)
                        fresh = keep
                    result[a["email"]] = fresh
                except Exception as e:
                    log.warning("Unread counts failed for %s: %s", a["email"], e)

            def done():
                self._counts_loading = False
                # Add the "kept" (always-unread senders you've already read)
                # Inbox count back on top of the server UNSEEN numbers. Gmail
                # reports those messages as \Seen, so IMAP STATUS never counts
                # them — which is exactly why the blue-purple badge kept
                # vanishing a moment after it appeared. _folder_kept is set from
                # the real message list in _reconcile_folder_badge.
                merged = {}
                for email, folders in result.items():
                    kept = int(self._folder_kept.get(email, {})
                               .get("Inbox", 0) or 0)
                    folders = dict(folders)
                    if kept:
                        folders["Inbox"] = int(folders.get("Inbox", 0) or 0) + kept
                    merged[email] = folders
                # Only repaint if something actually CHANGED. Rebuilding the
                # sidebar on every background check — even when the counts are
                # identical — is a visible flicker, and Issu is sensitive to
                # blinking, so a no-op check must stay silent.
                changed = any(self._folder_unread.get(k) != v
                              for k, v in merged.items())
                self._folder_unread.update(merged)
                if changed:
                    try:
                        self._populate_sidebar(self.sidebar_inner)
                    except Exception:
                        pass
                    self._update_unread_ui()
            try:
                self.root.after(0, done)
            except Exception:
                pass
        threading.Thread(target=worker, daemon=True).start()

    def _is_count_muted(self, email, folder) -> bool:
        """Whether a folder's unread NUMBER is muted (Issu 2026-08-03).

        A muted folder still shows its unread messages as unread when you open
        it — the bold rows are unchanged — but it contributes no "(N)" badge to
        the sidebar and nothing to the taskbar total. It is for a folder that
        collects filtered mail (receipts, shipping labels) where a running
        unread count is just noise. Keyed per account, like the mini-hide set.

        An AUTO-READ folder is muted too, without having to say so twice: its
        mail is read on arrival, so a count would always be zero anyway, and
        asking the server for it every pass is pure waste (Issu 2026-08-17)."""
        if self._is_auto_read(email, folder):
            return True
        return self._mini_key(email, folder) in set(
            self.cfg.get("muted_count_folders", []) or [])

    def _account_inbox_unread(self, email):
        if self._is_count_muted(email, "Inbox"):
            return 0
        return int(self._folder_unread.get(email, {}).get("Inbox", 0) or 0)

    def _folder_count(self, email, key, is_all=False):
        """Unread count for one folder. For the All-Accounts view, sum the same
        folder across every real account. A folder whose count is muted
        contributes 0 (its mail still shows as unread when opened)."""
        if is_all:
            return sum(int(self._folder_unread.get(a["email"], {}).get(key, 0) or 0)
                       for a in self._accounts
                       if not a.get("virtual")
                       and not self._is_count_muted(a["email"], key))
        if self._is_count_muted(email, key):
            return 0
        return int(self._folder_unread.get(email, {}).get(key, 0) or 0)

    def _badge_adjust(self, msg, delta):
        """Optimistically nudge one folder's unread badge so it reacts the
        instant you read/unread a message, instead of waiting up to a minute
        for the next server STATUS pass (which then confirms it)."""
        acct   = msg.get("account_email")
        folder = msg.get("_folder")
        if not acct or not folder or folder in _VIRTUAL_FOLDERS:
            return
        d = self._folder_unread.setdefault(acct, {})
        d[folder] = max(0, int(d.get(folder, 0) or 0) + delta)

    def _reconcile_folder_badge(self):
        """Make the CURRENT folder's badge match what is actually SHOWN, so a
        stale server count — e.g. 'Drafts (2)' when the folder opens empty —
        cannot linger. Only for a concrete account + server-backed folder.

        Also records how many of those unread are "kept" (always-unread
        senders), so the taskbar badge can be blue-purple when the only unread
        left is kept, and red when there is genuine new mail (see _unread_kind).
        """
        acct   = self._current_acct
        folder = self._current_folder
        if acct == ALL_ACCOUNTS_ID or folder in _VIRTUAL_FOLDERS:
            return
        if folder in _COUNT_BY_MESSAGES:
            # Drafts counts messages, not unread — so reconciling it against
            # the visible list means counting the SAME thing the background
            # pass counts. Mixing the two is what made the number flip between
            # (2) and nothing every minute (Issu 2026-08-07).
            self._folder_unread.setdefault(acct, {})[folder] = len(self._messages)
            self._folder_kept.setdefault(acct, {})[folder]   = 0
            return
        unread = sum(1 for m in self._messages if m.get("unread"))
        kept   = sum(1 for m in self._messages
                     if m.get("unread") and m.get("_always_unread"))
        self._folder_unread.setdefault(acct, {})[folder] = unread
        self._folder_kept.setdefault(acct, {})[folder]   = kept

    def _unread_kind(self):
        """Decide the taskbar badge: (colour_key, count).

          • count       — the total unread shown (genuine + kept), or 0.
          • colour_key  — "red" when at least one GENUINE (not always-unread)
                          message is unread anywhere, else "purple" when the
                          only unread left is kept (always-unread senders).

        Kept mail is \\Seen on Gmail, so any server-unseen count is genuine;
        the kept ones are added back locally in _reconcile_folder_badge and
        tracked in _folder_kept, so genuine = _folder_unread − _folder_kept."""
        count = self._total_unread()
        if count <= 0:
            return (None, 0)
        if self._folder_unread:
            genuine = 0
            for a in self._accounts:
                if a.get("virtual"):
                    continue
                email = a["email"]
                if self._is_count_muted(email, "Inbox"):
                    continue          # a muted Inbox nags with no number
                tot  = int(self._folder_unread.get(email, {}).get("Inbox", 0) or 0)
                kept = int(self._folder_kept.get(email, {}).get("Inbox", 0) or 0)
                genuine += max(0, tot - kept)
        else:
            # Before the first count pass: judge from the loaded view.
            genuine = sum(1 for m in self._messages
                          if m.get("unread") and not m.get("_always_unread"))
        return ("red" if genuine > 0 else "purple", count)

    def _repaint_badges(self):
        try:
            self._populate_sidebar(self.sidebar_inner)
        except Exception:
            pass
        self._update_unread_ui()

    def _total_unread(self):
        """Sum of INBOX unread across real accounts — the one number for the
        title and the taskbar. Inbox only, so Gmail's overlapping All Mail
        label cannot double-count. Falls back to the loaded view before the
        first count pass has returned."""
        if self._folder_unread:
            return sum(self._account_inbox_unread(a["email"])
                       for a in self._accounts if not a.get("virtual"))
        return sum(1 for m in self._messages if m.get("unread"))

    def _update_unread_ui(self):
        """Refresh the parts of the UI that carry the global unread total: the
        window title (so the taskbar/Alt-Tab show it) and the taskbar icon."""
        self._update_title()
        try:
            colour_key, count = self._unread_kind()
            self._apply_taskbar_icon(count, colour_key)
        except Exception as e:
            log.debug("taskbar icon update failed: %s", e)

    # ── Taskbar icon: swap to a badged variant while there is unread mail ──────
    # Badge fill per kind: red = genuine new mail, blue-purple = only "kept"
    # (always-unread senders you've already read). White outline + white digits.
    _BADGE_COLOURS = {"red":    (220, 40, 40, 255),
                      "purple": (124, 77, 214, 255)}   # blålila / blue-violet

    def _make_badged_icon_file(self, src_ico, dst_ico, count,
                               colour_key="red") -> bool:
        """Draw the user's icon with a small unread-count badge and save it as a
        multi-size .ico. The badge fill depends on colour_key (red = genuine new
        mail, purple = only kept always-unread). Needs Pillow; returns False if
        it is unavailable so the caller can fall back to the plain icon."""
        try:
            from PIL import Image, ImageDraw, ImageFont
        except Exception:
            return False
        try:
            fill = self._BADGE_COLOURS.get(colour_key, self._BADGE_COLOURS["red"])
            base = Image.open(src_ico).convert("RGBA").resize(
                (64, 64), Image.LANCZOS)
            d = ImageDraw.Draw(base)
            r = 34
            box = [64 - r, 64 - r, 63, 63]
            d.ellipse(box, fill=fill,
                      outline=(255, 255, 255, 255), width=3)
            txt = str(count) if count < 100 else "99+"
            try:
                font = ImageFont.truetype("segoeui.ttf", 26 if len(txt) < 3 else 20)
            except Exception:
                font = ImageFont.load_default()
            tb = d.textbbox((0, 0), txt, font=font)
            tw, th = tb[2] - tb[0], tb[3] - tb[1]
            cx, cy = (box[0] + box[2]) / 2, (box[1] + box[3]) / 2
            d.text((cx - tw / 2 - tb[0], cy - th / 2 - tb[1]), txt,
                   fill=(255, 255, 255, 255), font=font)
            base.save(dst_ico, format="ICO",
                      sizes=[(16, 16), (32, 32), (48, 48), (64, 64)])
            return True
        except Exception as e:
            log.debug("badged icon build failed: %s", e)
            return False

    def _apply_taskbar_icon(self, count, colour_key="red"):
        """Show the badged icon when count>0, the plain icon when 0. This is
        the 'two icons it switches between' Issu asked for — done as a real
        icon swap via WM_SETICON, so the taskbar and Alt-Tab both pick it up.

        colour_key picks the badge fill (red = genuine new mail, purple = only
        kept always-unread mail)."""
        if platform.system() != "Windows":
            return
        hwnd = self._get_hwnd()
        src = _icon_path()
        if not hwnd or not os.path.isfile(src):
            return
        # Skip if nothing changed since last time (avoids needless GDI churn).
        # Keyed on BOTH the number and the colour, so a red→purple flip with the
        # same count still redraws.
        state = (count, colour_key if count > 0 else None)
        if getattr(self, "_icon_badge_shown", None) == state:
            return
        path = src
        if count > 0:
            # Separate temp file per colour so the two never overwrite each
            # other mid-swap.
            dst = os.path.join(tempfile.gettempdir(),
                               f"freemail_unread_{colour_key}.ico")
            if self._make_badged_icon_file(src, dst, count, colour_key):
                path = dst
        try:
            user32 = ctypes.windll.user32
            LR_LOADFROMFILE = 0x0010
            LR_DEFAULTSIZE  = 0x0040
            IMAGE_ICON      = 1
            WM_SETICON      = 0x0080
            hbig = user32.LoadImageW(None, path, IMAGE_ICON, 0, 0,
                                     LR_LOADFROMFILE | LR_DEFAULTSIZE)
            hsml = user32.LoadImageW(None, 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)
            self._icon_badge_shown = state
        except Exception as e:
            log.debug("WM_SETICON badge failed: %s", e)

    def _windows_toast(self, title, body) -> bool:
        """Show a real Windows (Action Center) toast. Best-effort: uses the
        built-in WinRT API through a hidden PowerShell call, so no third-party
        package is needed. Returns True if it was launched, False otherwise —
        the caller then falls back to the in-app toast."""
        if platform.system() != "Windows":
            return False
        try:
            import base64 as _b64
            import subprocess

            def esc(s):
                return (str(s).replace("&", "&amp;").replace("<", "&lt;")
                        .replace(">", "&gt;").replace('"', "&quot;"))
            xml = ('<toast><visual><binding template="ToastGeneric">'
                   f'<text>{esc(title)}</text>'
                   f'<text>{esc(body)}</text>'
                   '</binding></visual></toast>')
            xml_ps = xml.replace("'", "''")          # for a PS single-quoted string
            ps = (
                "$ErrorActionPreference='Stop';"
                "[void][Windows.UI.Notifications.ToastNotificationManager,"
                "Windows.UI.Notifications,ContentType=WindowsRuntime];"
                "[void][Windows.Data.Xml.Dom.XmlDocument,"
                "Windows.Data.Xml.Dom,ContentType=WindowsRuntime];"
                "$d=[Windows.Data.Xml.Dom.XmlDocument]::new();"
                f"$d.LoadXml('{xml_ps}');"
                "$t=[Windows.UI.Notifications.ToastNotification]::new($d);"
                "[Windows.UI.Notifications.ToastNotificationManager]::"
                "CreateToastNotifier('IssuOrg.Freemail.1').Show($t);"
            )
            enc = _b64.b64encode(ps.encode("utf-16-le")).decode("ascii")
            CREATE_NO_WINDOW = 0x08000000
            subprocess.Popen(
                ["powershell", "-NoProfile", "-NonInteractive",
                 "-EncodedCommand", enc],
                creationflags=CREATE_NO_WINDOW,
                stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                stdin=subprocess.DEVNULL)
            return True
        except Exception as e:
            log.debug("Windows toast failed: %s", e)
            return False

    # ── Sidebar collapse + "mini" folder hiding (DEL 09c) ─────────────────────
    def _toggle_account_collapse(self, email):
        """Fold or unfold one account's folder list. Persisted so the sidebar
        opens next time exactly as you left it."""
        s = set(self.cfg.get("collapsed_accounts", []))
        if email in s:
            s.discard(email)
        else:
            s.add(email)
        self.cfg["collapsed_accounts"] = sorted(s)
        self._populate_sidebar(self.sidebar_inner)

    def _mini_key(self, email, folder):
        """The key stored in mini_hidden_folders. Now PER ACCOUNT, so the same
        folder name (or path) can be shown-on-collapse for one account and
        hidden for another (Issu's request)."""
        return f"{email}\t{folder}"

    def _is_mini_hidden(self, email, folder):
        return self._mini_key(email, folder) in set(
            self.cfg.get("mini_hidden_folders", []))

    # ── Right-click an ACCOUNT → its own menu (DEL 09c) ────────────────────────
    #
    # Everything account-specific in one place, found where you would look for
    # it: how often THIS account is auto-checked, whether it is the default
    # sender, its colour, fold/unfold, remove. The "All Accounts" header gets a
    # matching menu for the shared default interval + "check everything now".

    # Interval choices offered in the right-click submenu (label, minutes).
    _CTX_INTERVALS = [("Off", 0), ("Every 1 minute", 1), ("Every 5 minutes", 5),
                      ("Every 10 minutes", 10), ("Every 15 minutes", 15),
                      ("Every 30 minutes", 30), ("Every 60 minutes", 60)]

    def _account_context_menu(self, event, email, is_all):
        m = tk.Menu(self.root, tearoff=0, bg=C_BG2, fg=C_FG,
                    activebackground=C_BG4, activeforeground=C_FG)

        if is_all:
            # ── The virtual "All Accounts" header ────────────────────────────
            m.add_command(label="Check all accounts now",
                          command=self._check_all_now)
            sub = tk.Menu(m, tearoff=0, bg=C_BG2, fg=C_FG,
                          activebackground=C_BG4, activeforeground=C_FG)
            self._ctx_int_var = tk.IntVar(
                value=int(self.cfg.get("check_interval_min", 0) or 0))
            for lab, mins in self._CTX_INTERVALS:
                sub.add_radiobutton(label=lab, value=mins,
                                    variable=self._ctx_int_var,
                                    command=lambda v=mins:
                                        self._set_default_interval(v))
            m.add_cascade(label="Default auto-check (all accounts)", menu=sub)
            m.add_separator()
            m.add_command(label="Auto-check settings…",
                          command=self._autocheck_dialog)
        else:
            # ── One real account ─────────────────────────────────────────────
            # Show the bare address at the top (Issu asked to be able to see
            # which address a sidebar entry actually is) and let it be copied.
            m.add_command(label=f"✉  {email}", state="disabled")
            m.add_command(label="Copy address",
                          command=lambda e=email: self._copy_to_clipboard(
                              e, "Address copied"))
            m.add_separator()
            m.add_command(label="Check this account now",
                          command=lambda e=email: self._poll_account(e))

            sub = tk.Menu(m, tearoff=0, bg=C_BG2, fg=C_FG,
                          activebackground=C_BG4, activeforeground=C_FG)
            per = self.cfg.get("account_intervals", {}) or {}
            # -1 is the sentinel for "no override — follow the default".
            cur = per.get(email, None)
            self._ctx_int_var = tk.IntVar(value=(int(cur) if cur is not None else -1))
            sub.add_radiobutton(label="Use default", value=-1,
                                variable=self._ctx_int_var,
                                command=lambda e=email:
                                    self._set_account_interval(e, None))
            sub.add_separator()
            for lab, mins in self._CTX_INTERVALS:
                sub.add_radiobutton(label=lab, value=mins,
                                    variable=self._ctx_int_var,
                                    command=lambda e=email, v=mins:
                                        self._set_account_interval(e, v))
            eff = self._account_interval(email)
            src = "own" if email in per else "default"
            m.add_cascade(
                label=f"Auto-check for this account   "
                      f"[{('off' if eff == 0 else str(eff)+' min')}, {src}]",
                menu=sub)

            m.add_separator()
            is_def = (self._account_store.get("default_sender") == email)
            if is_def:
                m.add_command(label="✓  Default sender for new mail",
                              state="disabled")
            else:
                m.add_command(label="Set as default sender for new mail",
                              command=lambda e=email: self._set_default_sender(e))
            m.add_command(label="Account colours…",
                          command=self._account_colours_dialog)

            # Signature this account signs new mail with.
            sig_sub = tk.Menu(m, tearoff=0, bg=C_BG2, fg=C_FG,
                              activebackground=C_BG4, activeforeground=C_FG)
            cur_sig = (self._signature_store.get("assign") or {}).get(email, "")
            self._ctx_sig_var = tk.StringVar(value=cur_sig or "__none__")
            sig_sub.add_radiobutton(
                label="None", value="__none__", variable=self._ctx_sig_var,
                command=lambda e=email: self._set_account_signature(e, ""))
            sigs = [s for s in self._signature_store.get("signatures", [])
                    if s.get("name")]
            if sigs:
                sig_sub.add_separator()
                for s in sigs:
                    nm = s["name"]
                    sig_sub.add_radiobutton(
                        label=nm, value=nm, variable=self._ctx_sig_var,
                        command=lambda e=email, n=nm:
                            self._set_account_signature(e, n))
            sig_sub.add_separator()
            sig_sub.add_command(label="Edit signatures…",
                                command=self._signatures_dialog)
            m.add_cascade(label="Signature for this account", menu=sig_sub)

            m.add_separator()
            collapsed = email in set(self.cfg.get("collapsed_accounts", []))
            m.add_command(label=("Expand folder list" if collapsed
                                 else "Collapse folder list"),
                          command=lambda e=email: self._toggle_account_collapse(e))
            m.add_command(label="Remove account…",
                          command=self._remove_account_dialog)

            m.add_separator()
            m.add_command(label="Auto-check settings (all accounts)…",
                          command=self._autocheck_dialog)

        try:
            m.tk_popup(event.x_root, event.y_root)
        finally:
            m.grab_release()

    def _set_account_interval(self, email, minutes):
        """Set (minutes=int) or clear (minutes=None → follow default) this one
        account's auto-check interval, then re-arm its timer."""
        per = dict(self.cfg.get("account_intervals", {}) or {})
        if minutes is None:
            per.pop(email, None)
            msg = "Auto-check: follows the default"
        else:
            per[email] = int(minutes)
            msg = ("Auto-check off for this account" if minutes == 0
                   else f"Auto-check this account every {minutes} min")
        self.cfg["account_intervals"] = per
        _save_settings(self.cfg)
        self._reschedule_autocheck()
        self._flash(msg)

    def _set_default_interval(self, minutes):
        """Set the shared default interval (used by every account without its
        own override), then re-arm all timers."""
        self.cfg["check_interval_min"] = int(minutes)
        _save_settings(self.cfg)
        self._reschedule_autocheck()
        self._flash("Default auto-check off" if minutes == 0
                    else f"Default auto-check every {minutes} min")

    def _set_default_sender(self, email):
        """Make this account the From: address new messages start with."""
        self._account_store["default_sender"] = email
        try:
            _save_account_store(self._account_store)
        except Exception as e:
            log.error("Could not save default sender: %s", e)
        self._rebuild_accounts()
        self._populate_sidebar(self.sidebar_inner)
        self._flash("Default sender set")

    def _set_account_signature(self, email, name):
        """Assign (name) or clear (name='') the signature this account signs
        new mail with. Shared by name, so two accounts on the same signature
        both change when it is edited."""
        store  = self._signature_store
        assign = store.setdefault("assign", {})
        if name:
            assign[email] = name
        else:
            assign.pop(email, None)
        _save_signatures(store)
        self._flash(f"Signature: {name or 'none'}")

    def _check_all_now(self):
        """Background-check every real account's Inbox right now."""
        for a in self._accounts:
            if not a.get("virtual"):
                self._poll_account(a["email"])
        self._flash("Checking all accounts…")

    def _folder_context_menu(self, event, email, folder, display=None):
        """Right-click a folder (standard OR custom) → show/hide it while THIS
        account is collapsed. `folder` is a standard name or a custom mailbox
        path; `display` is what the menu text shows the human."""
        name = display or folder
        hidden = self._is_mini_hidden(email, folder)
        m = tk.Menu(self.root, tearoff=0, bg=C_BG2, fg=C_FG,
                    activebackground=C_BG4, activeforeground=C_FG)
        # The Deleted archive gets its own housekeeping actions.
        if folder == "Deleted":
            m.add_command(label="Empty the Deleted archive…",
                          command=self._empty_deleted)
            m.add_command(label="Keep deleted copies for…  (days)",
                          command=self._set_deleted_keep_days)
            m.add_separator()
        if hidden:
            m.add_command(label=f'Show "{name}" when collapsed',
                          command=lambda: self._toggle_mini_folder(email, folder, name))
        else:
            m.add_command(label=f'Show "{name}" only when expanded',
                          command=lambda: self._toggle_mini_folder(email, folder, name))
        # ── Mark the whole folder read (Issu 2026-08-03) ─────────────────────
        if folder not in _VIRTUAL_FOLDERS and not self._demo_mode:
            m.add_separator()
            m.add_command(label=f'Mark everything in "{name}" as read',
                          command=lambda: self._mark_folder_read(email, folder,
                                                                 name))
        # ── Mute / show the unread count for this folder ─────────────────────
        if folder not in _VIRTUAL_FOLDERS:
            if self._is_count_muted(email, folder):
                m.add_command(label=f'Show an unread count for "{name}"',
                              command=lambda: self._toggle_count_mute(email,
                                                                      folder, name))
            else:
                m.add_command(label=f"Don't show an unread count for "
                                    f'"{name}"',
                              command=lambda: self._toggle_count_mute(email,
                                                                      folder, name))
            # …and the same for the folder AND everything under it, which is
            # what you actually want on a parent like "Temporär" that has a
            # dozen labels beneath it (Issu 2026-08-08).
            kids = self._subfolders_of(email, folder)
            if kids:
                if self._is_count_muted(email, folder) and all(
                        self._is_count_muted(email, k) for k in kids):
                    m.add_command(
                        label=f'Show unread counts for "{name}" and its '
                              f'{len(kids)} sub-folder(s)',
                        command=lambda: self._toggle_count_mute_tree(
                            email, folder, name, mute=False))
                else:
                    m.add_command(
                        label=f'Don\'t show unread counts for "{name}" and '
                              f'its {len(kids)} sub-folder(s)',
                        command=lambda: self._toggle_count_mute_tree(
                            email, folder, name, mute=True))

        # ── Mail that lands here reads itself (Issu 2026-08-17) ──────────────
        # The whole point of a folder a rule files receipts into: no toast, no
        # badge, nothing to dismiss. One tick instead of "mute the count" plus
        # a "mark read" action on every rule that aims here.
        if folder not in _VIRTUAL_FOLDERS:
            m.add_separator()
            if self._is_auto_read(email, folder):
                m.add_command(
                    label=f'✓  Stop marking mail in "{name}" read on arrival',
                    command=lambda: self._toggle_auto_read(email, folder, name))
            else:
                m.add_command(
                    label=f'✓  Mail that lands in "{name}" reads itself  '
                          f'(no alert, no count)',
                    command=lambda: self._toggle_auto_read(email, folder, name))
            kids_ar = self._subfolders_of(email, folder)
            if kids_ar and not self._is_auto_read(email, folder):
                m.add_command(
                    label=f'✓  …in "{name}" and its {len(kids_ar)} '
                          f'sub-folder(s)',
                    command=lambda: self._toggle_auto_read(email, folder, name,
                                                           tree=True))

        # ── Never auto-merge in here (Issu 2026-08-19) ───────────────────────
        # For a folder full of look-alikes: two Tradera shipping receipts share
        # a subject, a sender and therefore a Gmail conversation id, and two
        # separate QR codes were arriving as one row.
        if folder not in _VIRTUAL_FOLDERS:
            m.add_separator()
            if self._is_no_merge(email, folder):
                m.add_command(
                    label=f'🔗  Auto-merge conversations in "{name}" again',
                    command=lambda: self._toggle_no_merge(email, folder, name))
            else:
                m.add_command(
                    label=f'🔗  Don\'t auto-merge in "{name}" — one row per '
                          f'message',
                    command=lambda: self._toggle_no_merge(email, folder, name))
            kids_nm = self._subfolders_of(email, folder)
            if kids_nm and not self._is_no_merge(email, folder):
                m.add_command(
                    label=f'🔗  …in "{name}" and its {len(kids_nm)} '
                          f'sub-folder(s)',
                    command=lambda: self._toggle_no_merge(email, folder, name,
                                                          tree=True))

        # ── Protect against automatic moves (Issu 2026-08-08) ────────────────
        if folder not in _VIRTUAL_FOLDERS and not self._demo_mode:
            m.add_separator()
            if self._is_protected(email, folder):
                m.add_command(label=f'🔓  Stop protecting "{name}"',
                              command=lambda: self._toggle_protect(email,
                                                                   folder, name))
            else:
                m.add_command(label=f'🔒  Protect "{name}" — nothing automatic '
                                    f'may move mail out of it',
                              command=lambda: self._toggle_protect(email,
                                                                   folder, name))

        # ── Ageing: what happens to mail in here as it gets old (2026-09-09) ─
        # "Delete later" is a real folder with a real promise in its name, and
        # this is the promise being kept: filter rules ask who sent it, this
        # asks how old it is, and keeps asking. DEL 04r.
        if folder not in _VIRTUAL_FOLDERS and not self._demo_mode:
            m.add_separator()
            rule = self._age_rule_on(email, folder)
            if rule is None:
                m.add_command(
                    label=f'⏳  Age the mail in "{name}"…  (read it after N '
                          f'hours, bin it after M)',
                    command=lambda: self._folderage_dialog(email, folder, name))
            else:
                on = bool(rule.get("enabled"))
                m.add_command(
                    label=f'⏳  Ageing{"" if on else " (off)"}:  '
                          f'{_age_describe(rule)}',
                    command=lambda: self._folderage_dialog(email, folder, name))
                m.add_command(
                    label=('⏸  Stop ageing this folder' if on
                           else '▶  Switch ageing on for this folder'),
                    command=lambda r=rule: self._age_toggle_enabled(r, name))
                m.add_command(label='👁  Show me what ageing would do now',
                              command=lambda r=rule: self._age_preview(
                                  r, self.root))
                m.add_command(label='▶  Age this folder now',
                              command=lambda r=rule: self._age_run_now(r))

        # ── Folder housekeeping: make one, make a year's worth ───────────────
        if folder not in _VIRTUAL_FOLDERS and not self._demo_mode:
            m.add_separator()
            m.add_command(label=f'📁  New folder inside "{name}"…',
                          command=lambda: self._create_subfolder(email, folder,
                                                                 name))
            m.add_command(label=f'📅  Month folders in "{name}"…',
                          command=lambda: self._date_folders_dialog(email,
                                                                    folder, name))
            # Filing on its own, without going through "create" again — it is
            # the half you repeat every month (Issu 2026-08-08: "det finns
            # ingen flytta").
            m.add_command(label=f'📅  File the mail in "{name}" into its '
                                f'month folders…',
                          command=lambda: self._file_into_month_folders(
                              email, folder, name,
                              self.cfg.get("date_folder_style", "year_month")))

        # ── Delete a CUSTOM folder (never a standard one) ────────────────────
        if self._is_custom_folder(email, folder) and not self._demo_mode:
            m.add_separator()
            m.add_command(label=f'Delete the folder "{name}"…',
                          command=lambda: self._delete_folder(email, folder,
                                                              name))
        try:
            m.tk_popup(event.x_root, event.y_root)
        finally:
            m.grab_release()

    # ── Sub-folders, recursive mute, protection (Issu 2026-08-08) ───────────
    def _subfolders_of(self, email, folder):
        """Every custom mailbox that sits UNDER `folder`, at any depth."""
        out = []
        for uf in (self._user_folders or {}).get(email, []):
            mb = uf.get("mailbox") or ""
            delim = uf.get("delim", "/")
            if mb != folder and mb.startswith(folder + delim):
                out.append(mb)
        return out

    def _toggle_count_mute_tree(self, email, folder, name, mute=True):
        """Mute (or un-mute) the unread count for a folder and everything
        beneath it in one go. A parent like "Temporär" with a dozen labels
        under it is exactly where doing them one at a time is tedious."""
        muted = set(self.cfg.get("muted_count_folders", []) or [])
        targets = [folder] + self._subfolders_of(email, folder)
        for f in targets:
            key = self._mini_key(email, f)
            if mute:
                muted.add(key)
            else:
                muted.discard(key)
        self.cfg["muted_count_folders"] = sorted(muted)
        _save_settings(self.cfg)
        self._repaint_badges()
        self._flash(f"{'Muted' if mute else 'Restored'} the unread count for "
                    f"{len(targets)} folder(s) under “{name}”")

    def _protected_key(self, email, folder) -> str:
        """The comparison key for protected_folders — account plus a NORMALISED
        folder path.

        Issu 2026-08-16, why this is not just _mini_key: the same folder
        reaches this code under two spellings. A rule stores the decoded path
        ("INBOX/Temporär/0---Frakt & Kvitto") while a message carries the raw
        modified-UTF-7 name ("INBOX/Tempor&AOQ-r/0---Frakt &- Kvitto"), and
        his settings.json really does hold both — the parent folders written
        one way, the month folders written the other. A plain string compare
        therefore said "not protected" for every month folder he had protected
        by hand, and automatic moves walked straight back out of them. Which
        is precisely the "mail hoppar omkring" this feature exists to stop.

        _folder_norm decodes and case-folds, so both spellings answer alike."""
        return f"{email}\t{_folder_norm(folder)}"

    def _protected_keys(self) -> set:
        """Every protected folder, normalised. Old entries in either spelling
        are understood without having to rewrite the settings file."""
        return {self._protected_key(*(k.split("\t", 1) + [""])[:2])
                for k in (self.cfg.get("protected_folders", []) or [])
                if "\t" in k}

    def _is_protected(self, email, folder) -> bool:
        """Is this folder protected against AUTOMATIC moves?

        See _toggle_protect for what that means and why it exists."""
        return self._protected_key(email, folder) in self._protected_keys()

    # ── Folders that read themselves (Issu 2026-08-17) ───────────────────────
    def _auto_read_keys(self) -> set:
        """Every auto-read folder, normalised, so both spellings of a name
        answer alike — see _protected_key for why that matters."""
        return {self._protected_key(*(k.split("\t", 1) + [""])[:2])
                for k in (self.cfg.get("auto_read_folders", []) or [])
                if "\t" in k}

    def _is_auto_read(self, email, folder) -> bool:
        """Does mail landing in this folder mark itself read, silently?"""
        if not folder or folder in _VIRTUAL_FOLDERS:
            return False
        return self._protected_key(email, folder) in self._auto_read_keys()

    def _apply_auto_read(self, messages):
        """Mark anything sitting in an auto-read folder as read, and remember
        which ones so nothing announces them.

        Runs inside _apply_local_state, which is the ONE path every fetch goes
        through — the visible list, a background auto-check, and the pass over
        an account you are not even looking at. So a receipt filed by a rule at
        07:03 is already read by the time you next glance at the sidebar,
        whether or not you were in that folder.

        Returns the (account, folder, uid) triples worth flagging on the server;
        the caller dispatches those off the GUI thread."""
        if not self.cfg.get("auto_read_folders"):
            return []
        want_server = (self.cfg.get("auto_read_on_server", True)
                       and self.cfg.get("allow_server_changes", False)
                       and not self._demo_mode)
        server = []
        for m in messages:
            if m.get("_note_path"):
                continue                    # a note is yours, leave it alone
            # Filed by a waiting rule that promised to keep it unread. Two
            # features would otherwise contradict each other silently: the
            # folder says "everything here reads itself", the rule says "these
            # stay unread until he looks at them". The narrower, more recent
            # promise wins — and the rule editor warns when a rule is saved
            # onto an auto-read destination, so it is not a surprise either.
            if m.get("_keep_unread"):
                continue
            folder = m.get("_folder") or ""
            acct   = m.get("account_email") or ""
            if not self._is_auto_read(acct, folder):
                continue
            m["_auto_read"] = True
            # Never notify about it, whatever any rule decided.
            m["_filter_notify"] = "never"
            if m.get("unread"):
                m["unread"] = False
                if want_server and m.get("uid"):
                    server.append((acct, folder, m["uid"]))
        return server

    def _dispatch_auto_read(self, triples):
        """ADD \\Seen on Gmail for auto-read folders, batched per (account,
        folder), on a worker thread. Never removes the flag — the same
        one-directional promise _imap_mark_seen makes everywhere else."""
        if not triples:
            return
        groups = {}
        for acct, folder, uid in triples:
            key = (acct, folder)
            if uid in self._auto_read_done.get(key, set()):
                continue
            groups.setdefault(key, []).append(uid)
            self._auto_read_done.setdefault(key, set()).add(uid)
        if not groups:
            return

        def worker():
            for (acct, folder), uids in groups.items():
                try:
                    pwd = self._secret_for(acct)
                    if not pwd:
                        continue
                    why = _imap_mark_seen(acct, pwd, folder, uids)
                    if why:
                        log.warning("auto-read: could not flag %d message(s) "
                                    "in %s/%s: %s", len(uids), acct, folder, why)
                        # Let them be retried on the next pass.
                        self._auto_read_done.get((acct, folder),
                                                 set()).difference_update(uids)
                    else:
                        log.info("auto-read: marked %d message(s) read on "
                                 "Gmail in %s/%s", len(uids), acct, folder)
                except Exception as e:
                    log.error("auto-read flagging failed for %s/%s: %s",
                              acct, folder, e)
                    self._auto_read_done.get((acct, folder),
                                             set()).difference_update(uids)

        threading.Thread(target=worker, daemon=True).start()

    def _toggle_auto_read(self, email, folder, name, tree=False):
        """Turn "mail that lands here reads itself" on or off for a folder
        (and optionally everything beneath it)."""
        cur = set(self.cfg.get("auto_read_folders", []) or [])
        targets = [folder] + (self._subfolders_of(email, folder) if tree else [])
        now_on = not self._is_auto_read(email, folder)
        for f in targets:
            if now_on:
                cur.add(self._mini_key(email, f))
            else:
                # Off has to remove EVERY spelling, or an entry written in the
                # other encoding keeps it on and the menu lies about it.
                want = self._protected_key(email, f)
                cur = {k for k in cur
                       if "\t" not in k
                       or self._protected_key(*k.split("\t", 1)) != want}
        self.cfg["auto_read_folders"] = sorted(cur)
        _save_settings(self.cfg)
        self._repaint_badges()
        n = len(targets)
        where = f'“{name}”' + (f" and its {n - 1} sub-folder(s)"
                               if tree and n > 1 else "")
        if now_on:
            self._flash(f"✓ Mail that lands in {where} now reads itself — no "
                        f"notification, no unread count")
            self._activity_log("auto-read", account=email,
                               detail=f"{folder} now marks arriving mail read")
        else:
            self._flash(f"{where} keeps its mail unread again")
            self._activity_log("auto-read", account=email,
                               detail=f"{folder} no longer marks mail read")

    # ── Folders that never AUTO-merge (Issu 2026-08-19) ──────────────────────
    #
    # "jag vill ha en don't auto-merge in this directory … så att två mail från
    # Tradera-frakt, inte merge. Inget merge i den katalogen."
    #
    # Every Tradera shipping receipt has the same subject and the same sender,
    # so Gmail gives the lot ONE conversation id: book two shipments and the
    # two mails — two different QR codes — arrive as a single row. The existing
    # "Separate this conversation" fixes one thread at a time, after the fact,
    # which for this folder means doing it again with every booking. This sets
    # it once, on the folder.
    #
    # Normalised with _protected_key for the reason spelled out there: the same
    # folder reaches this code as raw modified-UTF-7 from a message and as a
    # decoded path from the sidebar, and his settings.json genuinely holds both.
    def _no_merge_keys(self) -> set:
        return {self._protected_key(*(k.split("\t", 1) + [""])[:2])
                for k in (self.cfg.get("no_merge_folders", []) or [])
                if "\t" in k}

    def _no_merge_lookup(self) -> set:
        """_no_merge_keys with a cache, because _effective_tid asks this for
        EVERY row on every redraw and the answer only changes when the menu
        item is clicked. Keyed on the stored list itself, so a settings tidy
        (or an edit made anywhere else) invalidates it without help."""
        raw = tuple(self.cfg.get("no_merge_folders", []) or [])
        cached = getattr(self, "_no_merge_cache", None)
        if cached is None or cached[0] != raw:
            cached = (raw, self._no_merge_keys())
            self._no_merge_cache = cached
        return cached[1]

    def _is_no_merge(self, email, folder) -> bool:
        """Does this folder show one row per message, whatever Gmail thinks?"""
        if not folder or folder in _VIRTUAL_FOLDERS:
            return False
        return self._protected_key(email, folder) in self._no_merge_lookup()

    def _toggle_no_merge(self, email, folder, name, tree=False):
        """Turn "never auto-merge here" on or off for a folder (and optionally
        everything beneath it — a month-filed receipt folder has a couple of
        dozen sub-folders that all want the same answer)."""
        cur = set(self.cfg.get("no_merge_folders", []) or [])
        targets = [folder] + (self._subfolders_of(email, folder) if tree else [])
        now_on = not self._is_no_merge(email, folder)
        for f in targets:
            if now_on:
                cur.add(self._mini_key(email, f))
            else:
                # Off has to remove EVERY spelling, or an entry written in the
                # other encoding keeps it on and the menu lies about it.
                want = self._protected_key(email, f)
                cur = {k for k in cur
                       if "\t" not in k
                       or self._protected_key(*k.split("\t", 1)) != want}
        self.cfg["no_merge_folders"] = sorted(cur)
        _save_settings(self.cfg)
        self._no_merge_cache = None
        # The grouping changed under the list — redraw it, and drop the
        # expanded-row memory, whose ids belong to the old grouping.
        self._expanded_rows = set()
        try:
            self._render_msg_list()
        except Exception as e:
            log.debug("redraw after no-merge toggle failed: %s", e)
        n = len(targets)
        where = f'“{name}”' + (f" and its {n - 1} sub-folder(s)"
                               if tree and n > 1 else "")
        if now_on:
            self._flash(f"{where}: one row per message — look-alikes stay "
                        f"apart")
            self._activity_log("no-merge", account=email,
                               detail=f"{folder} no longer auto-merges "
                                      f"conversations")
        else:
            self._flash(f"{where} groups conversations again")
            self._activity_log("no-merge", account=email,
                               detail=f"{folder} auto-merges conversations "
                                      f"again")

    def _ensure_protected(self, email, folder, quiet=True) -> bool:
        """Add (email, folder) to protected_folders if it is not there
        already. Returns True if it just turned protection ON.

        Issu 2026-08-15: the one-way sibling of _toggle_protect, used by
        anything AUTOMATIC — month-folder filing, a filter's own "Protect
        destination folder" option — that wants a folder protected but must
        never accidentally switch protection OFF the way a toggle would if
        called twice. A person clicking the sidebar menu still gets
        _toggle_protect; code acting on its own always calls this instead."""
        if not folder or folder in _VIRTUAL_FOLDERS:
            return False
        if self._is_protected(email, folder):
            return False                      # already on, in either spelling
        prot = set(self.cfg.get("protected_folders", []) or [])
        prot.add(self._mini_key(email, folder))
        self.cfg["protected_folders"] = sorted(prot)
        _save_settings(self.cfg)
        if not quiet:
            try:
                self._populate_sidebar(self.sidebar_inner)
            except Exception:
                pass
        return True

    def _toggle_protect(self, email, folder, name):
        """Protect a folder so nothing automatic can move mail out of it.

        Issu 2026-08-08: "Jag vill bara inte att mail hoppar omkring." Once a
        message has been filed somewhere on purpose, an overlapping rule
        picking it up again and moving it on is the thing that turns finding a
        receipt into a hunt.

        Protection is deliberately about the DESTINATION, not the rule: any
        number of rules may exist, and any of them may be edited later, but a
        protected folder answers "no" to all of them. Mail can still leave it
        by a move YOU make by hand, or by you deleting it — both are things
        you did on purpose, and neither is a surprise.

        It does NOT stop mail arriving. A rule may still file things INTO a
        protected folder; protection only refuses to take mail back out."""
        prot = set(self.cfg.get("protected_folders", []) or [])
        now_on = not self._is_protected(email, folder)
        if now_on:
            prot.add(self._mini_key(email, folder))
        else:
            # Switching protection OFF has to remove EVERY spelling of this
            # folder, or the entry written in the other encoding would quietly
            # keep it protected and the menu would lie about it.
            want = self._protected_key(email, folder)
            prot = {k for k in prot
                    if "\t" not in k
                    or self._protected_key(*k.split("\t", 1)) != want}
        self.cfg["protected_folders"] = sorted(prot)
        _save_settings(self.cfg)
        self._populate_sidebar(self.sidebar_inner)
        if now_on:
            self._flash(f"🔒 “{name}” is protected — no rule may move mail out "
                        f"of it")
            self._activity_log("protected", account=email,
                               detail=f"protected {folder} against automatic "
                                      f"moves")
        else:
            self._flash(f"🔓 “{name}” is no longer protected")
            self._activity_log("protected", account=email,
                               detail=f"removed protection from {folder}")

    # ── Making folders (Issu 2026-08-08: "delete finns, men jag ser inte create")
    def _folder_full_path(self, email, folder) -> str:
        """The DECODED path of a folder, which is what the create/move code
        wants. A standard folder maps to its own name."""
        for uf in (self._user_folders or {}).get(email, []):
            if uf.get("mailbox") == folder:
                return uf.get("full") or folder
        return folder

    def _create_subfolder(self, email, folder, name):
        """Make one new folder inside this one."""
        parent = self._folder_full_path(email, folder)
        leaf = _ask_line(self.root, "New folder",
                         f"Name for the new folder inside “{name}”:",
                         "", ok="Create")
        if not leaf:
            return
        leaf = leaf.strip().strip("/")
        if not leaf:
            return
        path = f"{parent}/{leaf}" if parent.upper() != "INBOX" else f"INBOX/{leaf}"
        pwd = self._secret_for(email)
        if not pwd:
            messagebox.showwarning("New folder",
                                   "No stored password for that account.",
                                   parent=self.root)
            return
        made, skipped, problems = _imap_create_folders(email, pwd, [path])
        if problems:
            messagebox.showerror("New folder", "\n".join(problems),
                                 parent=self.root)
            return
        if skipped:
            self._flash(f"“{leaf}” already exists — nothing changed")
        else:
            self._flash(f"Created “{leaf}”")
            self._activity_log("folder", account=email,
                               detail=f"created folder {path}")
        self._refresh_folder_tree()
        try:
            self._reveal_folder(email, path)
        except Exception:
            pass

    def _date_folders_dialog(self, email, folder, name):
        """Make a month folder per month inside this one, and (optionally) file
        what is already here into them by date.

        Issu 2026-08-08, about 0---Frakt & Kvitto: he keeps 01, 02 … under it
        by hand and wants the program to do it — offering year-prefixed names
        too, because a bare "01" collides the moment a second year arrives.
        Nothing is ever overwritten: a folder that exists is left exactly as it
        is."""
        parent = self._folder_full_path(email, folder)
        top = self._dialog_shell("Month folders", 620, 620)
        tk.Label(top, text=f"📅  Month folders inside “{name}”",
                 bg=C_BG3, fg=C_ACCENT, font=("Segoe UI", 12, "bold"),
                 pady=(8)).pack()
        tk.Label(top,
                 text="Creates one folder per month under this one. A folder "
                      "that already exists is left alone — nothing is ever "
                      "overwritten or emptied.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 wraplength=560, justify="left").pack(padx=18)

        f = tk.Frame(top, bg=C_BG3)
        f.pack(fill="both", expand=True, padx=18, pady=8)

        v_style = tk.StringVar(value=self.cfg.get("date_folder_style",
                                                  "year_month"))
        tk.Label(f, text="Naming:", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 10, "bold"), anchor="w").pack(fill="x",
                                                                 pady=(6, 2))
        for key in ("year_month", "month", "year/month"):
            label, why = _DATE_FOLDER_STYLES[key]
            tk.Radiobutton(f, text=label, value=key, variable=v_style,
                           bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                           activebackground=C_BG3, activeforeground=C_FG,
                           font=("Segoe UI", 10), highlightthickness=0,
                           anchor="w").pack(fill="x")
            tk.Label(f, text=why, bg=C_BG3, fg=C_FG_DIM,
                     font=("Segoe UI", 8), anchor="w", justify="left",
                     wraplength=520).pack(fill="x", padx=26, pady=(0, 4))

        row = tk.Frame(f, bg=C_BG3)
        row.pack(fill="x", pady=(8, 2))
        tk.Label(row, text="How many months:", bg=C_BG3, fg=C_FG_DIM,
                 width=18, anchor="e", font=("Segoe UI", 9)).pack(side="left")
        v_count = tk.StringVar(value="12")
        e_count = tk.Entry(row, textvariable=v_count, bg=C_BG2, fg=C_FG,
                           relief="flat", width=6, font=("Segoe UI", 10),
                           insertbackground=C_ACCENT,
                           insertofftime=0, insertontime=9999999)
        no_blink(e_count)
        e_count.pack(side="left", ipady=3)
        tk.Label(row, text="counting from this month", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(side="left", padx=6)

        v_back = tk.StringVar(value="0")
        row2 = tk.Frame(f, bg=C_BG3)
        row2.pack(fill="x", pady=2)
        tk.Label(row2, text="…and back:", bg=C_BG3, fg=C_FG_DIM, width=18,
                 anchor="e", font=("Segoe UI", 9)).pack(side="left")
        e_back = tk.Entry(row2, textvariable=v_back, bg=C_BG2, fg=C_FG,
                          relief="flat", width=6, font=("Segoe UI", 10),
                          insertbackground=C_ACCENT,
                          insertofftime=0, insertontime=9999999)
        no_blink(e_back)
        e_back.pack(side="left", ipady=3)
        tk.Label(row2, text="earlier months as well  (for mail already here)",
                 bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(side="left", padx=6)

        prev = tk.Label(f, text="", bg=C_BG2, fg=C_ACCENT,
                        font=("Consolas", 9), anchor="w", justify="left",
                        wraplength=540, padx=8, pady=6)
        prev.pack(fill="x", pady=(10, 0))

        def _plan():
            now = datetime.now()
            try:
                fwd  = max(0, min(120, int(v_count.get())))
                back = max(0, min(120, int(v_back.get())))
            except ValueError:
                return []
            y, m = now.year, now.month - back
            while m < 1:
                m += 12
                y -= 1
            return _date_folders_for(v_style.get(), y, m, back + fwd)

        def _refresh_preview(*_a):
            names = _plan()
            if not names:
                prev.configure(text="(nothing to create — check the numbers)")
                return
            shown = names[:6] + (["…"] if len(names) > 6 else [])
            prev.configure(text=f"{len(names)} folder(s) under {parent}/\n\n  "
                                + "\n  ".join(shown))

        v_style.trace_add("write", _refresh_preview)
        for e in (e_count, e_back):
            e.bind("<KeyRelease>", _refresh_preview)
        _refresh_preview()

        def _create(also_file=False):
            names = _plan()
            if not names:
                return
            pwd = self._secret_for(email)
            if not pwd:
                messagebox.showwarning("Month folders",
                                       "No stored password for that account.",
                                       parent=top)
                return
            self.cfg["date_folder_style"] = v_style.get()
            _save_settings(self.cfg)
            paths = [f"{parent}/{n}" for n in names]
            made, skipped, problems = _imap_create_folders(email, pwd, paths)
            msg = f"Created {len(made)} folder(s)."
            if skipped:
                msg += f"\n{len(skipped)} already existed and were left alone."
            if problems:
                msg += "\n\nProblems:\n" + "\n".join(problems[:5])
            self._activity_log("folder", account=email,
                               detail=f"created {len(made)} month folder(s) "
                                      f"under {parent}")
            self._refresh_folder_tree()
            top.destroy()
            if problems:
                messagebox.showwarning("Month folders", msg, parent=self.root)
            else:
                self._flash(msg.replace("\n", "  "))
            if also_file:
                self._file_into_month_folders(email, folder, name,
                                              v_style.get())

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(fill="x", padx=18, pady=(0, 12))
        tk.Button(btns, text="📁  Create the folders", bg=C_BTN_NEW,
                  fg=C_BTN_FG, font=("Segoe UI", 9, "bold"), relief="flat",
                  cursor="hand2", padx=12, pady=4,
                  command=lambda: _create(False)).pack(side="left", padx=4)
        b2 = tk.Button(btns, text="📁  Create, then file what is here",
                       bg="#3a7d5a", fg=C_BTN_FG, font=("Segoe UI", 9),
                       relief="flat", cursor="hand2", padx=12, pady=4,
                       command=lambda: _create(True))
        b2.pack(side="left", padx=4)
        add_tooltip(b2, "After making the folders, look at the mail already in "
                        "this folder and move each message into the month its "
                        "own date falls in. You are shown exactly what will "
                        "move, and asked, before anything happens.")
        tk.Button(btns, text="Cancel", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=12, pady=4, command=top.destroy).pack(side="left", padx=4)
        top.bind("<Return>", lambda e: _create(False))

    def _file_into_month_folders(self, email, folder, name, style):
        """Move the mail in this folder into its month sub-folder, judged by
        each message's OWN date.

        You do NOT have to have the folder open. If it is not the one on
        screen, its list is fetched first (headers only — the date is all this
        needs), because "file last month's mail away" is a thing you do TO a
        folder, not a thing you do while standing in it (Issu 2026-08-08).

        Issu 2026-08-16 — and it must file the WHOLE folder either way. This
        used to take a short cut when the folder happened to be OPEN: it filed
        `self._messages`, which is only the loaded window (~40 rows). His
        0---Frakt & Kvitto held far more, so filing from inside it moved
        thirty and silently left the rest — and because the list then refills
        with older mail, the folder looked barely touched and the job looked
        done. A folder-wide job now always asks the server for the folder."""
        if self._demo_mode:
            messagebox.showinfo("File by month",
                                "No account is set up yet.", parent=self.root)
            return
        pwd = self._secret_for(email)
        if not pwd:
            messagebox.showwarning("File by month",
                                   "No stored password for that account.",
                                   parent=self.root)
            return
        self._flash(f"Reading “{name}” …")

        def worker():
            try:
                # 2000, not 200: this is the "tidy the whole folder" job, and a
                # limit that quietly stops short is the bug this call is fixing.
                # Uncached messages cost only their headers here.
                msgs = _fetch_folder_smart(
                    email, pwd, folder, limit=max(2000, self._fetch_limit),
                    use_cache=self.cfg.get("cache_enabled", True),
                    interactive=True)
            except Exception as e:
                log.error("File by month: could not read %s/%s: %s",
                          email, folder, e)
                msgs = None

            def done():
                if msgs is None:
                    messagebox.showerror(
                        "File by month",
                        f"Could not read “{name}” from the server.",
                        parent=self.root)
                    return
                self._file_month_plan(email, folder, name, style, msgs)
            try:
                self.root.after(0, done)
            except Exception:
                pass

        threading.Thread(target=worker, daemon=True).start()

    def _file_month_plan(self, email, folder, name, style, msgs):
        """Work out where each message goes, show it, ask, then move."""
        parent = self._folder_full_path(email, folder)
        # A message already sitting in a month sub-folder is finished — this
        # only ever looks at what is in the folder ITSELF.
        msgs = [m for m in msgs
                if _folder_norm(m.get("_folder", "")) == _folder_norm(folder)]
        plan = {}
        for m in msgs:
            sub = _month_folder_for_message(m, style)
            if sub:
                plan.setdefault(f"{parent}/{sub}", []).append(m)
        if not msgs:
            messagebox.showinfo(
                "File by month",
                f"There is nothing directly in “{name}” to file — it is either "
                f"empty, or everything in it has already been filed into a "
                f"month folder.", parent=self.root)
            return
        if not plan:
            messagebox.showinfo("File by month",
                                "None of these messages has a usable date.",
                                parent=self.root)
            return
        lines = "\n".join(f"  • {len(v)} → {k}"
                          for k, v in sorted(plan.items())[:12])
        more = "\n  …" if len(plan) > 12 else ""
        if not messagebox.askyesno(
                "File by month",
                f"Move {sum(len(v) for v in plan.values())} message(s) into "
                f"month folders?\n\n{lines}{more}\n\nAny month folder that "
                f"does not exist yet is created first.\n\nThis is a real move "
                f"on Gmail. Nothing is deleted.",
                parent=self.root, default="no"):
            return
        if not self.cfg.get("allow_server_changes", False):
            messagebox.showwarning(
                "File by month",
                "Moving mail changes it on Gmail, so it needs "
                "Tools → Server changes to be on.", parent=self.root)
            return
        # Make sure every destination exists. Filing straight from the
        # right-click menu must work without having pressed "create" first;
        # a folder that is already there is skipped, never touched.
        pwd = self._secret_for(email)
        if pwd:
            try:
                made, _skipped, probs = _imap_create_folders(
                    email, pwd, sorted(plan))
                if made:
                    log.info("File by month: created %d missing month "
                             "folder(s)", len(made))
                    self._refresh_folder_tree()
                if probs:
                    log.warning("File by month: %s", "; ".join(probs[:3]))
            except Exception as e:
                log.warning("File by month: could not create folders: %s", e)
        for target, group in sorted(plan.items()):
            try:
                # enable_prompt=False: Server changes was already confirmed
                # just above, so this must not ask once per month folder.
                self._move_selected_to(group, target, enable_prompt=False)
            except Exception as e:
                log.error("File by month failed for %s: %s", target, e)
        # Protect every month folder just filed into (Issu 2026-08-15: he was
        # doing this by hand, one folder at a time, right after every sweep —
        # "jag vill ha automatiskt Protect på alla kataloger som skapas vid
        # Month folder-skapande"). _ensure_protected is one-way, so re-running
        # the sweep on a folder that is already protected is a no-op, not a
        # toggle-off.
        newly_protected = []
        for target in sorted(plan):
            if self._ensure_protected(email, target):
                newly_protected.append(target)
                self._activity_log(
                    "protected", account=email,
                    detail=f"protected {target} against automatic moves")
        if newly_protected:
            try:
                self._populate_sidebar(self.sidebar_inner)
            except Exception:
                pass
        self._activity_log("moved", account=email,
                           detail=f"filed {sum(len(v) for v in plan.values())} "
                                  f"message(s) into month folders under "
                                  f"{parent}")

    def _is_custom_folder(self, email, folder) -> bool:
        """True only for a label the USER made — never Inbox/Sent/Trash/… and
        never one of this program's virtual folders. The delete offer is gated
        on this, so a standard mailbox can't be removed by a slip of the
        mouse."""
        if not folder or folder in _FOLDERS or folder in _VIRTUAL_FOLDERS:
            return False
        return any(uf.get("mailbox") == folder
                   for uf in (self._user_folders or {}).get(email, []))

    def _mark_current_folder_read(self):
        """Mark the folder you are LOOKING AT as read — the "✓ Read all"
        button. In the All Accounts view every account's copy of that folder
        is done."""
        folder = self._current_folder
        if folder in _VIRTUAL_FOLDERS:
            self._flash("That is a local view — nothing on the server to mark")
            return
        if self._demo_mode:
            for m in self._messages:
                m["unread"] = False
                m["_manually_unread"] = False
            self._render_msg_list()
            self._flash("Marked as read (demo)")
            return
        if self._current_acct == ALL_ACCOUNTS_ID:
            for a in self._accounts:
                if not a.get("virtual"):
                    self._mark_folder_read(a["email"], folder,
                                           quiet=True)
            self._flash(f"Marking “{folder}” read in every account…")
        else:
            self._mark_folder_read(self._current_acct, folder)

    # ── Mark a whole folder read ──────────────────────────────────────────────
    def _mark_folder_read(self, email, folder, display=None, quiet=False):
        """Mark every unread message in one folder as read, on Gmail and here.

        Additive only (it adds \\Seen, never removes it), but it IS a server
        change, so it is gated like every other one."""
        name = display or folder
        if not self.cfg.get("allow_server_changes", False):
            # In quiet mode (the All Accounts loop) we must not pop one dialog
            # per account: if Server changes is off, just do nothing quietly.
            if quiet:
                return
            if not messagebox.askyesno(
                    "Mark everything as read",
                    f"Marking “{name}” as read changes it on Gmail, and "
                    f"“Server changes” is currently OFF.\n\nTurn it on and "
                    f"continue?", parent=self.root, default="no"):
                return
            self.cfg["allow_server_changes"] = True
            _save_settings(self.cfg)
            log.info("allow_server_changes enabled from Mark folder read")
        pwd = self._secret_for(email)
        if not pwd:
            return
        if not quiet:
            self._flash(f"Marking “{name}” as read…")

        def worker():
            try:
                n, problems = _imap_mark_folder_read(email, pwd, folder)
            except Exception as e:
                n, problems = 0, [str(e)]
                log.error("Mark folder read failed %s/%s: %s", email, folder, e)

            def done():
                if problems and not quiet:
                    messagebox.showwarning(
                        "Mark everything as read",
                        "\n".join(f"• {p}" for p in problems[:5]),
                        parent=self.root)
                elif quiet:
                    pass
                elif not n:
                    self._flash(f"“{name}” had nothing unread")
                else:
                    self._flash(f"{n} message(s) in “{name}” marked as read")
                # Reflect it locally at once, so the list and the badges do not
                # disagree with Gmail until the next fetch.
                for mm in list(self._all_messages) + list(self._messages):
                    if (mm.get("account_email") == email
                            and mm.get("_folder") == folder
                            and not mm.get("_always_unread")):
                        mm["unread"] = False
                        mm["_manually_unread"] = False
                self._render_msg_list()
                self._maybe_refresh_counts(force=True)
            try:
                self.root.after(0, done)
            except Exception:
                pass
        threading.Thread(target=worker, daemon=True).start()

    # ── Folder ageing: what happens here as mail gets old (Issu 2026-09-09) ───
    #
    # The engine is in DEL 04r; this half is the folder's right-click menu, the
    # editor, the preview, and the quarter-hourly pass. Read DEL 04r first —
    # what will and will not be done, and why, is written down there.

    def _age_rule_on(self, email, folder):
        """The rule saved for exactly THIS folder, enabled or not.

        Not _age_rules_for: that one answers "what governs this folder",
        inherited parents included, which is the right question at run time and
        the wrong one for a menu. Right-clicking a sub-folder must not offer to
        edit its parent's rule as though it were its own."""
        want = _folder_norm(folder)
        for r in (self._folderage_store.get("rules") or []):
            if (r.get("account") or "") == email and \
                    _folder_norm(r.get("folder") or "") == want:
                return r
        return None

    def _age_toggle_enabled(self, rule, name):
        """The one-click switch from the folder menu — on, or off, no dialog."""
        rule["enabled"] = not rule.get("enabled")
        _save_folder_ages(self._folderage_store)
        if rule["enabled"]:
            self._flash(f"⏳ Ageing is on for “{name}”:  {_age_describe(rule)}")
            self._activity_log("folder-ageing", account=rule.get("account", ""),
                               detail=f"{rule.get('folder')} — on "
                                      f"({_age_describe(rule)})")
        else:
            self._flash(f"⏳ Ageing is off for “{name}”")
            self._activity_log("folder-ageing", account=rule.get("account", ""),
                               detail=f"{rule.get('folder')} — off")

    def _age_can_run(self, rule, parent=None, quiet=False) -> bool:
        """Every reason a rule must NOT run, asked in one place.

        Demo mode, a protected folder, a missing password, and the server-
        changes switch. In `quiet` mode (the timer) it answers False without a
        single dialog: a background pass must never pop a question at a man who
        is reading his mail."""
        acct   = rule.get("account") or ""
        folder = rule.get("folder") or ""
        if self._demo_mode:
            if not quiet:
                messagebox.showinfo(
                    "Folder ageing",
                    "This works on your real mailbox, so it needs an "
                    "account.\n\nAccounts → Add Gmail account…",
                    parent=parent or self.root)
            return False
        if self._is_protected(acct, folder):
            if not quiet:
                messagebox.showinfo(
                    "Folder ageing",
                    f"“{folder}” is protected — you have told this program "
                    f"that nothing automatic may move mail out of it, and an "
                    f"ageing rule is exactly that kind of automatic.\n\n"
                    f"Un-protect the folder first (right-click it → 🔓) if you "
                    f"really do want mail aged out of here.",
                    parent=parent or self.root)
            else:
                log.info("Folder ageing: %s/%s is protected — skipped",
                         acct, folder)
            return False
        if not self._secret_for(acct):
            if not quiet:
                messagebox.showwarning(
                    "Folder ageing",
                    f"There is no stored password for {acct}.",
                    parent=parent or self.root)
            return False
        if not self.cfg.get("allow_server_changes", False):
            if quiet:
                return False              # silently do nothing, as promised
            if not messagebox.askyesno(
                    "Server changes are off",
                    "Ageing mail marks it read, moves it or puts it in the "
                    "Trash on Gmail, and that switch is currently OFF.\n\n"
                    "Turn it on now and continue?\n\n"
                    "(Nothing is ever erased — “delete” here means the Trash, "
                    "where Gmail keeps it for 30 days.)",
                    parent=parent or self.root, default="no"):
                return False
            self.cfg["allow_server_changes"] = True
            _save_settings(self.cfg)
            log.info("allow_server_changes enabled from folder ageing")
        return True

    def _age_scan_async(self, rule, then):
        """Scan every folder this rule covers and hand `then` the plans.

        Read-only, on a worker thread, and the result is marshalled back to the
        GUI thread — `then(plans, problems)` where plans is
        [(folder, plan_dict), …]. The preview button and the real run share
        this, so what you are shown is what will happen, by construction."""
        acct = rule.get("account") or ""
        pwd  = self._secret_for(acct)
        steps = _age_steps(rule)
        min_h = min([_age_hours(s) for s in steps], default=0.0)
        known = [e.get("full") or e.get("display") or ""
                 for e in (self._user_folders or {}).get(acct, [])]
        folders = _age_folders_of(rule, known)

        def worker():
            plans, problems = [], []
            try:
                for f in folders:
                    items, probs = _imap_age_scan(acct, pwd, f, min_hours=min_h)
                    problems.extend(probs)
                    plan = _age_plan(rule, items)
                    problems.extend(plan["problems"])
                    plans.append((f, plan))
            except Exception as e:
                # `then` must be called whatever happens: the timer marks a
                # rule busy before the scan and only un-marks it in there, so a
                # scan that died silently would switch the rule off for the
                # rest of the session.
                log.error("Folder ageing scan failed for %s/%s: %s",
                          acct, rule.get("folder"), e)
                problems.append(str(e))
            try:
                self.root.after(0, lambda: then(plans, problems))
            except Exception:
                pass

        threading.Thread(target=worker, daemon=True).start()

    def _age_apply(self, rule, plans, quiet=False, parent=None, after=None):
        """Do it. `plans` is what _age_scan_async produced.

        Work is grouped per (folder, action, destination) so one connection
        does a whole batch — the same reason _imap_trash_uids exists at all."""
        acct = rule.get("account") or ""
        pwd  = self._secret_for(acct)
        groups = {}
        for folder, plan in plans:
            for it, st in plan["act"]:
                key = (folder, st.get("action"),
                       (st.get("target") or "").strip())
                groups.setdefault(key, []).append(it.get("uid"))
        total = sum(len(v) for v in groups.values())
        if not total:
            if not quiet:
                self._flash(f"⏳ Nothing in “{rule.get('folder')}” is old "
                            f"enough yet")
            if after:
                after(0, [])
            return

        cap = int(rule.get("ask_over") or AGE_ASK_OVER)
        if total > cap:
            # The typo guard. A rule that suddenly wants to touch far more than
            # you expected is either right — in which case say so once — or it
            # is the "2 hours" you meant to type as "200", and this is the last
            # moment anyone can catch that.
            if quiet:
                log.warning("Folder ageing %s/%s: %d message(s) is over the "
                            "limit of %d — waiting to be asked",
                            acct, rule.get("folder"), total, cap)
                NotifyToast(self.root, "⏳  Folder ageing is waiting",
                            [f"{rule.get('folder')}",
                             f"{total} messages, more than the {cap} you "
                             f"allowed",
                             "Right-click the folder → Run now"])
                if after:
                    after(0, [])
                return
            if not messagebox.askyesno(
                    "That is a lot of mail",
                    f"This run would touch {total} message(s) in "
                    f"“{rule.get('folder')}” — more than the {cap} you said to "
                    f"ask about.\n\n{self._age_summary(plans)}\n\nGo ahead?",
                    parent=parent or self.root, default="no"):
                if after:
                    after(0, [])
                return

        def worker():
            did, problems = 0, []
            for (folder, action, target), uids in groups.items():
                uids = [u for u in uids if u]
                if not uids:
                    continue
                try:
                    if action == "read":
                        err = _imap_mark_seen(acct, pwd, folder, uids)
                        if err:
                            problems.append(f"{folder}: {err}")
                        else:
                            did += len(uids)
                    elif action == "trash":
                        n, probs = _imap_trash_uids(acct, pwd, folder, uids)
                        did += n
                        problems.extend(probs)
                    elif action == "move":
                        n, probs = _imap_move_uids(acct, pwd, folder, uids,
                                                   target)
                        did += n
                        problems.extend(probs)
                except Exception as e:
                    problems.append(f"{folder}: {e}")
                    log.error("Folder ageing %s %s/%s failed: %s",
                              action, acct, folder, e)

            def done():
                try:
                    _done()
                finally:
                    # Whatever happened on screen, the rule must stop counting
                    # as busy — see the note in _age_scan_async's worker.
                    if after:
                        after(did, problems)

            def _done():
                log.info("Folder ageing '%s': %d message(s) handled%s",
                         rule.get("folder"), did,
                         f" ({len(problems)} problem(s))" if problems else "")
                self._activity_log(
                    "folder-ageing", account=acct,
                    detail=f"{rule.get('folder')}: {did} message(s) — "
                           f"{_age_describe(rule)}")
                # Marking read is reflected here at once, so the badges do not
                # argue with Gmail until the next fetch. A move or a trash
                # changes which folder a message is IN, and only a refresh can
                # tell the list that honestly.
                read_uids = {u for (f, a, t), us in groups.items()
                             if a == "read" for u in us}
                if read_uids:
                    for mm in list(self._all_messages) + list(self._messages):
                        if (mm.get("account_email") == acct
                                and mm.get("uid") in read_uids
                                and not mm.get("_always_unread")):
                            mm["unread"] = False
                            mm["_manually_unread"] = False
                if any(a in ("move", "trash")
                       for (_f, a, _t) in groups.keys()):
                    self._refresh_messages()
                self._render_msg_list()
                self._maybe_refresh_counts(force=True)
                if problems and not quiet:
                    messagebox.showwarning(
                        "Folder ageing",
                        f"{did} message(s) were handled, but some had "
                        f"problems:\n\n"
                        + "\n".join(f"• {p}" for p in problems[:8]),
                        parent=parent or self.root)
                elif quiet and did:
                    NotifyToast(self.root, "⏳  Folder ageing",
                                [rule.get("folder", ""),
                                 f"{did} message(s) handled"])
                elif not quiet:
                    self._flash(f"⏳ {did} message(s) in "
                                f"“{rule.get('folder')}” handled")
            try:
                self.root.after(0, done)
            except Exception:
                pass

        threading.Thread(target=worker, daemon=True).start()

    def _age_summary(self, plans) -> str:
        """What a scan found, in the words you would use out loud."""
        counts, kept = {}, {}
        for _folder, plan in plans:
            for _it, st in plan["act"]:
                lbl = _age_step_describe(st).split(" — ", 1)[-1]
                counts[lbl] = counts.get(lbl, 0) + 1
            for why, n in plan["kept"].items():
                kept[why] = kept.get(why, 0) + n
        if not counts:
            lines = ["Nothing is old enough yet."]
        else:
            lines = [f"  • {n} × {lbl}" for lbl, n in sorted(counts.items())]
        if kept:
            lines.append("")
            lines.append("Left alone:")
            lines += [f"  • {n} — {why}" for why, n in sorted(kept.items())]
        return "\n".join(lines)

    def _age_preview(self, rule, parent):
        """Show, message by message, exactly what a run would do right now.

        Read-only. This is the button to press before the switch is ever turned
        on — the same "preview before anything happens" the dated folders make
        (DEL 04l), for the same reason: nobody should have to find out what a
        rule means by watching it happen to real mail."""
        if self._demo_mode or not self._secret_for(rule.get("account") or ""):
            messagebox.showinfo("Folder ageing",
                                "This needs a real account with a stored "
                                "password.", parent=parent)
            return
        win = self._dialog_shell("What would happen right now", 780, 560)
        tk.Label(win, text="Nothing below has been done — this is read-only.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 pady=4).pack(fill="x", padx=12)
        box = tk.Frame(win, bg=C_BG3)
        box.pack(fill="both", expand=True, padx=12, pady=6)
        sb = tk.Scrollbar(box)
        sb.pack(side="right", fill="y")
        lb = tk.Listbox(box, bg=C_BG2, fg=C_FG, relief="flat",
                        highlightthickness=0, activestyle="none",
                        font=("Consolas", 9), yscrollcommand=sb.set)
        lb.pack(side="left", fill="both", expand=True)
        sb.config(command=lb.yview)
        lb.insert("end", "  Asking Gmail…")
        tk.Button(win, text="Close", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=14, pady=4, command=win.destroy).pack(pady=8)

        def show(plans, problems):
            if not win.winfo_exists():
                return
            lb.delete(0, "end")
            now = time.time()
            n = 0
            for folder, plan in plans:
                if not plan["act"]:
                    continue
                lb.insert("end", f"  {folder}")
                for it, st in sorted(plan["act"],
                                     key=lambda p: p[0].get("ts") or 0):
                    age = (now - (it.get("ts") or now)) / 3600.0
                    what = _age_step_describe(st).split(" — ", 1)[-1]
                    subj = (it.get("subject") or "(no subject)")[:52]
                    lb.insert("end", f"      {age:6.1f} h   {what:<28} {subj}")
                    n += 1
                lb.insert("end", "")
            if not n:
                lb.insert("end", "  Nothing is old enough yet.")
                lb.insert("end", "")
            for line in self._age_summary(plans).splitlines():
                lb.insert("end", f"  {line}")
            for p in problems:
                lb.insert("end", f"  ⚠ {p}")

        self._age_scan_async(rule, show)

    def _age_run_now(self, rule, parent=None):
        """Run one rule this second, with the confirmations a hand-pressed
        action gets."""
        if not self._age_can_run(rule, parent=parent):
            return
        self._flash(f"⏳ Looking at “{rule.get('folder')}”…")

        def then(plans, problems):
            if problems:
                log.warning("Folder ageing scan problems: %s", problems)
            _age_mark_run(self._folderage_store, rule)
            self._age_apply(rule, plans, quiet=False, parent=parent)

        self._age_scan_async(rule, then)

    def _folderage_tick(self):
        """The quarter-hourly pass, called from the 30-second ticker.

        Deliberately meek: it runs only rules that are switched on, only when
        their quarter of an hour is up, only one rule at a time, and it never
        asks a question — anything that would need one is left for the folder
        menu's "Run now". A background job that pops dialogs is a background
        job nobody keeps switched on."""
        try:
            for rule in list(self._folderage_store.get("rules") or []):
                if rule.get("id") in self._folderage_busy:
                    continue
                if not _age_due(rule):
                    continue
                if not self._age_can_run(rule, quiet=True):
                    # Still stamp it, or a rule blocked by (say) the server
                    # switch is re-examined every 30 seconds for ever.
                    _age_mark_run(self._folderage_store, rule)
                    continue
                self._folderage_busy.add(rule.get("id"))
                _age_mark_run(self._folderage_store, rule)

                def then(plans, problems, _r=rule):
                    if problems:
                        log.warning("Folder ageing %s: %s", _r.get("folder"),
                                    problems)
                    self._age_apply(
                        _r, plans, quiet=True,
                        after=lambda *_a, _rid=_r.get("id"):
                            self._folderage_busy.discard(_rid))

                self._age_scan_async(rule, then)
                return          # one rule per tick — this is not a race
        except Exception as e:
            log.error("Folder ageing tick failed: %s", e)

    def _folderage_dialog(self, email=None, folder=None, display=None):
        """The editor: every ageing rule on the left, the selected one's ladder
        of steps on the right.

        Opened from a folder's right-click menu it selects (or starts) that
        folder's rule; opened from Accounts it is the overview of the lot."""
        store = self._folderage_store
        top = self._dialog_shell("Folder ageing", 900, 660)
        tk.Label(top,
                 text="A rule on a FOLDER, not on a sender: it asks only how "
                      "old the mail in there is, and keeps asking. Build a "
                      "ladder — “mark it read after 24 h, move it to the Trash "
                      "after 48 h” — and mail you file here tidies itself away. "
                      "Nothing is ever erased: “delete” means the Trash, where "
                      "Gmail keeps it for 30 days. Runs about every quarter of "
                      "an hour while the program is open.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 wraplength=860, justify="left", pady=4).pack(fill="x", padx=12)

        body = tk.Frame(top, bg=C_BG3)
        body.pack(fill="both", expand=True, padx=12, pady=4)
        left = tk.Frame(body, bg=C_BG3)
        left.pack(side="left", fill="y")
        lb = self._listbox(left, width=34)
        lb.pack(fill="y", expand=True, pady=4)
        right = tk.Frame(body, bg=C_BG3)
        right.pack(side="left", fill="both", expand=True, padx=(12, 0))

        state = {"i": -1}            # index into store["rules"], -1 = nothing

        # ── the editor's widgets ──────────────────────────────────────────
        head = tk.Label(right, text="", bg=C_BG3, fg=C_ACCENT,
                        font=("Segoe UI", 10, "bold"), anchor="w",
                        justify="left", wraplength=470)
        head.pack(fill="x", pady=(6, 2))

        v_sub    = tk.BooleanVar(value=False)
        v_star   = tk.BooleanVar(value=True)
        v_on     = tk.BooleanVar(value=False)
        v_ask    = tk.StringVar(value=str(AGE_ASK_OVER))

        tk.Checkbutton(right, variable=v_sub,
                       text="…and every folder nested under it",
                       bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       highlightthickness=0, relief="flat",
                       font=("Segoe UI", 9), anchor="w").pack(fill="x")

        tk.Label(right, text="Steps — the LAST one whose time has come is the "
                             "one that runs:",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9), anchor="w"
                 ).pack(fill="x", pady=(10, 2))
        slb = self._listbox(right, width=52)
        slb.configure(height=6, font=("Consolas", 9))
        slb.pack(fill="x")

        erow = tk.Frame(right, bg=C_BG3)
        erow.pack(fill="x", pady=6)
        tk.Label(erow, text="after", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left")
        e_h = tk.Entry(erow, bg=C_BG2, fg=C_FG, relief="flat", width=6,
                       insertbackground=C_ACCENT, font=("Segoe UI", 10),
                       insertofftime=0, insertontime=9999999)
        no_blink(e_h)
        e_h.pack(side="left", padx=4, ipady=2)
        tk.Label(erow, text="hours", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left", padx=(0, 8))
        v_act = tk.StringVar(value=_AGE_ACTIONS[0][1])
        # tk.OptionMenu, not a ttk Combobox: three choices fit a menu, and an
        # editable Combobox blinks a cursor at you that cannot be turned off.
        om_act = tk.OptionMenu(erow, v_act, *[lbl for _k, lbl in _AGE_ACTIONS])
        om_act.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                         activeforeground=C_FG, highlightthickness=0,
                         relief="flat", font=("Segoe UI", 9), anchor="w",
                         padx=6, pady=2, width=34)
        om_act["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                                 activeforeground=C_FG, font=("Segoe UI", 9))
        om_act.pack(side="left")
        v_tgt = tk.StringVar(value="")
        b_tgt = tk.Button(erow, text="folder…", bg=C_BTN_STD, fg=C_BTN_FG,
                          font=("Segoe UI", 8), relief="flat", cursor="hand2",
                          padx=8, pady=2)
        b_tgt.pack(side="left", padx=6)
        lbl_tgt = tk.Label(erow, textvariable=v_tgt, bg=C_BG3, fg=C_ACCENT,
                           font=("Segoe UI", 9))
        lbl_tgt.pack(side="left")

        v_onlyread = tk.BooleanVar(value=False)
        tk.Checkbutton(right, variable=v_onlyread,
                       text="…but only if I have already read it  (a guard "
                            "worth having on the step that throws things away)",
                       bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       highlightthickness=0, relief="flat",
                       font=("Segoe UI", 9), anchor="w", wraplength=460,
                       justify="left").pack(fill="x")

        srow = tk.Frame(right, bg=C_BG3)
        srow.pack(fill="x", pady=4)

        def _sel_step():
            sel = slb.curselection()
            return sel[0] if sel else -1

        def _cur_rule():
            if 0 <= state["i"] < len(store.get("rules", [])):
                return store["rules"][state["i"]]
            return None

        def _step_from_form():
            try:
                hours = float((e_h.get() or "0").replace(",", "."))
            except ValueError:
                messagebox.showwarning("Folder ageing",
                                       "The hours must be a number.",
                                       parent=top)
                return None
            if hours <= 0:
                messagebox.showwarning("Folder ageing",
                                       "“After 0 hours” would act on mail the "
                                       "moment it arrives. Use a filter rule "
                                       "for that — this is about age.",
                                       parent=top)
                return None
            action = next((k for k, lbl in _AGE_ACTIONS if lbl == v_act.get()),
                          "read")
            if action == "move" and not v_tgt.get().strip():
                messagebox.showwarning("Folder ageing",
                                       "Pick the folder to move it to.",
                                       parent=top)
                return None
            return {"after_hours": hours, "action": action,
                    "target": v_tgt.get().strip(),
                    "only_read": bool(v_onlyread.get())}

        def _redraw_steps():
            r = _cur_rule()
            slb.delete(0, "end")
            for s in _age_steps(r or {}):
                slb.insert("end", "  " + _age_step_describe(s))

        def _add_step():
            r = _cur_rule()
            if r is None:
                return
            st = _step_from_form()
            if st is None:
                return
            r.setdefault("steps", []).append(st)
            r["steps"] = _age_steps(r)
            _redraw_steps()

        def _replace_step():
            r, i = _cur_rule(), _sel_step()
            if r is None or i < 0:
                messagebox.showinfo("Folder ageing",
                                    "Pick the step to change first.",
                                    parent=top)
                return
            st = _step_from_form()
            if st is None:
                return
            steps = _age_steps(r)
            steps[i] = st
            r["steps"] = sorted(steps, key=_age_hours)
            _redraw_steps()

        def _del_step():
            r, i = _cur_rule(), _sel_step()
            if r is None or i < 0:
                return
            steps = _age_steps(r)
            del steps[i]
            r["steps"] = steps
            _redraw_steps()

        def _load_step(_e=None):
            r, i = _cur_rule(), _sel_step()
            if r is None or i < 0:
                return
            st = _age_steps(r)[i]
            e_h.delete(0, "end")
            e_h.insert(0, f"{_age_hours(st):g}")
            v_act.set(_AGE_ACTION_LABEL.get(st.get("action"),
                                            _AGE_ACTIONS[0][1]))
            v_tgt.set(st.get("target") or "")
            v_onlyread.set(bool(st.get("only_read")))

        slb.bind("<<ListboxSelect>>", _load_step)

        def _pick_tgt():
            nm = self._pick_target_folder("Move aged mail into…")
            if nm:
                v_tgt.set(nm)
                v_act.set(_AGE_ACTION_LABEL["move"])
        b_tgt.configure(command=_pick_tgt)

        for txt, cmd, col in (("+ Add step", _add_step, C_BTN_NEW),
                              ("Change the picked step", _replace_step,
                               C_BTN_STD),
                              ("Remove step", _del_step, C_BTN_STD)):
            tk.Button(srow, text=txt, bg=col, fg=C_BTN_FG,
                      font=("Segoe UI", 9), relief="flat", cursor="hand2",
                      padx=10, pady=3, command=cmd).pack(side="left", padx=3)

        tk.Checkbutton(right, variable=v_star,
                       text="Never touch a starred message  (a star is you "
                            "saying “not this one”)",
                       bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       highlightthickness=0, relief="flat",
                       font=("Segoe UI", 9), anchor="w", wraplength=460,
                       justify="left").pack(fill="x", pady=(10, 0))
        arow = tk.Frame(right, bg=C_BG3)
        arow.pack(fill="x", pady=2)
        tk.Label(arow, text="Ask me first if one run would touch more than",
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 9)).pack(side="left")
        e_ask = tk.Entry(arow, textvariable=v_ask, bg=C_BG2, fg=C_FG,
                         relief="flat", width=6, insertbackground=C_ACCENT,
                         font=("Segoe UI", 10), insertofftime=0,
                         insertontime=9999999)
        no_blink(e_ask)
        e_ask.pack(side="left", padx=4, ipady=2)
        tk.Label(arow, text="messages", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left")

        tk.Checkbutton(right, variable=v_on,
                       text="⏳  This rule is ON",
                       bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       highlightthickness=0, relief="flat",
                       font=("Segoe UI", 10, "bold"), anchor="w"
                       ).pack(fill="x", pady=(8, 0))
        warn = tk.Label(right, text="", bg=C_BG3, fg="#e6b800",
                        font=("Segoe UI", 8), anchor="w", justify="left",
                        wraplength=470)
        warn.pack(fill="x")

        # ── the list on the left ──────────────────────────────────────────
        def _redraw_list(select=None):
            lb.delete(0, "end")
            for r in store.get("rules", []):
                mark = "⏳" if r.get("enabled") else "  "
                lb.insert("end", f"{mark} {r.get('folder','')}")
            if select is not None and 0 <= select < lb.size():
                lb.selection_clear(0, "end")
                lb.selection_set(select)
                lb.see(select)

        def _show(i):
            state["i"] = i
            r = _cur_rule()
            if r is None:
                head.configure(text="No rule selected.")
                return
            head.configure(text=f"{r.get('folder','')}\n{r.get('account','')}")
            v_sub.set(bool(r.get("include_sub")))
            v_star.set(bool(r.get("keep_starred", True)))
            v_on.set(bool(r.get("enabled")))
            v_ask.set(str(r.get("ask_over") or AGE_ASK_OVER))
            _redraw_steps()
            bits = []
            if self._is_protected(r.get("account", ""), r.get("folder", "")):
                bits.append("🔒 This folder is protected, so the rule will "
                            "never run. Un-protect it first.")
            if not self.cfg.get("allow_server_changes", False):
                bits.append("⚠ “Server changes” is off, so nothing will happen "
                            "in the background. Run now will offer to turn it "
                            "on.")
            warn.configure(text="\n".join(bits))

        def _on_pick(_e=None):
            sel = lb.curselection()
            if sel:
                _show(sel[0])
        lb.bind("<<ListboxSelect>>", _on_pick)

        def _collect_into(r):
            """Copy the form back onto the rule. Steps are already on it —
            they are edited in place, which is what makes Add/Change/Remove
            feel immediate."""
            r["include_sub"]  = bool(v_sub.get())
            r["keep_starred"] = bool(v_star.get())
            r["enabled"]      = bool(v_on.get())
            try:
                r["ask_over"] = max(1, int(v_ask.get() or AGE_ASK_OVER))
            except ValueError:
                r["ask_over"] = AGE_ASK_OVER

        def _save(quiet=False):
            r = _cur_rule()
            if r is None:
                return False
            _collect_into(r)
            if r["enabled"] and not _age_steps(r):
                messagebox.showwarning("Folder ageing",
                                       "A rule with no steps does nothing. "
                                       "Add at least one.", parent=top)
                r["enabled"] = False
                v_on.set(False)
                return False
            _save_folder_ages(store)
            _redraw_list(select=state["i"])
            if not quiet:
                self._flash(f"⏳ Saved:  {r.get('folder')} — "
                            f"{_age_describe(r)}")
            return True

        def _delete_rule():
            r = _cur_rule()
            if r is None:
                return
            if not messagebox.askyesno(
                    "Folder ageing",
                    f"Remove the ageing rule for “{r.get('folder')}”?\n\n"
                    f"The folder and its mail are untouched.",
                    parent=top, default="no"):
                return
            del store["rules"][state["i"]]
            _save_folder_ages(store)
            state["i"] = -1
            _redraw_list()
            head.configure(text="No rule selected.")
            slb.delete(0, "end")

        def _new_rule():
            nm = self._pick_target_folder("Age the mail in which folder?")
            if not nm:
                return
            acct = email or self._current_acct
            if not acct or acct == ALL_ACCOUNTS_ID:
                real = [a["email"] for a in self._accounts
                        if not a.get("virtual")]
                if not real:
                    messagebox.showinfo("Folder ageing", "No account "
                                        "configured.", parent=top)
                    return
                acct = real[0]
            store.setdefault("rules", []).append(_age_new_rule(acct, nm))
            _save_folder_ages(store)
            _redraw_list(select=len(store["rules"]) - 1)
            _show(len(store["rules"]) - 1)

        def _preview():
            if _save(quiet=True):
                self._age_preview(_cur_rule(), top)

        def _run():
            if _save(quiet=True):
                self._age_run_now(_cur_rule(), parent=top)

        brow = tk.Frame(top, bg=C_BG3)
        brow.pack(pady=8)
        for txt, cmd, col, tip in (
                ("👁 Show me what it would do now", _preview, "#3a6a8a",
                 "Read-only: asks Gmail what is in there and lists exactly "
                 "what would happen. Nothing is changed."),
                ("▶ Run now", _run, C_BTN_NEW,
                 "Do it this second, instead of waiting for the next pass."),
                ("Save", lambda: _save(), C_BTN_STD, "Keep these settings."),
                ("+ New rule…", _new_rule, C_BTN_STD,
                 "Add an ageing rule for another folder."),
                ("Remove rule", _delete_rule, C_BTN_DEL,
                 "Forget this rule. The mail is untouched."),
                ("Close", top.destroy, C_BTN_STD, "")):
            b = tk.Button(brow, text=txt, bg=col, fg=C_BTN_FG,
                          font=("Segoe UI", 9), relief="flat", cursor="hand2",
                          padx=12, pady=4, command=cmd)
            b.pack(side="left", padx=4)
            if tip:
                add_tooltip(b, tip)

        # ── open on the folder that was right-clicked ─────────────────────
        _redraw_list()
        want = -1
        if email and folder:
            for i, r in enumerate(store.get("rules", [])):
                if (r.get("account") == email
                        and _folder_norm(r.get("folder", "")) ==
                        _folder_norm(folder)):
                    want = i
                    break
            if want < 0:
                store.setdefault("rules", []).append(
                    _age_new_rule(email, folder))
                _save_folder_ages(store)
                want = len(store["rules"]) - 1
                _redraw_list()
        if want < 0 and store.get("rules"):
            want = 0
        if want >= 0:
            _redraw_list(select=want)
            _show(want)
        else:
            head.configure(text="No rule yet — press “+ New rule…”.")

    # ── Delete a folder (Issu 2026-08-03) ─────────────────────────────────────
    def _delete_folder(self, email, folder, display=None):
        """Delete a user-made folder / label.

        No question at all when it is EMPTY — that was the request, and on
        Gmail it is genuinely cheap: a folder IS a label, so deleting it takes
        the label off, it does not delete mail. A folder that still holds
        messages asks once and says exactly that.

        Gmail's own folder list can lag behind by a minute, so the name is
        parked in `hidden_folders` and the sidebar leaves it out until the
        server stops listing it (Issu: "så kan det döljas i Freemail till dess
        att Gmail har hunnit ikapp")."""
        name = display or folder
        if not self._is_custom_folder(email, folder):
            return
        pwd = self._secret_for(email)
        if not pwd:
            return
        if not self.cfg.get("allow_server_changes", False):
            if not messagebox.askyesno(
                    "Delete folder",
                    f"Deleting “{name}” changes your Gmail account, and "
                    f"“Server changes” is currently OFF.\n\nTurn it on and "
                    f"continue?", parent=self.root, default="no"):
                return
            self.cfg["allow_server_changes"] = True
            _save_settings(self.cfg)
            log.info("allow_server_changes enabled from Delete folder")

        def counter():
            stats = _imap_folder_stats(email, pwd, folder)

            def ask():
                if not stats["exists"]:
                    self._forget_folder(email, folder)
                    self._flash(f"“{name}” was already gone")
                    return
                if stats["children"] > 1:
                    # LIST returns the folder itself plus its children.
                    messagebox.showinfo(
                        "Delete folder",
                        f"“{name}” still has {stats['children'] - 1} "
                        f"sub-folder(s) inside it.\n\nDelete those first — "
                        f"IMAP will not remove a folder that still has "
                        f"children.", parent=self.root)
                    return
                if stats["messages"]:
                    if not messagebox.askyesno(
                            "Delete folder",
                            f"“{name}” still holds {stats['messages']} "
                            f"message(s).\n\nOn Gmail a folder is a LABEL, so "
                            f"deleting it takes the label off — the messages "
                            f"themselves are NOT deleted and stay in All Mail. "
                            f"They just stop being filed here.\n\nDelete the "
                            f"folder?", parent=self.root, default="no"):
                        return
                # Empty → straight through, no popup at all (his request).
                self._do_delete_folder(email, folder, name)
            try:
                self.root.after(0, ask)
            except Exception:
                pass
        threading.Thread(target=counter, daemon=True).start()

    def _do_delete_folder(self, email, folder, name):
        self._flash(f"Deleting “{name}”…")

        def worker():
            try:
                prob = _imap_delete_folder(email, self._secret_for(email),
                                           folder)
            except Exception as e:
                prob = str(e)
                log.error("Delete folder failed %s/%s: %s", email, folder, e)

            def done():
                if prob:
                    messagebox.showwarning("Delete folder", prob,
                                           parent=self.root)
                    return
                self._forget_folder(email, folder)
                self._flash(f"“{name}” deleted")
            try:
                self.root.after(0, done)
            except Exception:
                pass
        threading.Thread(target=worker, daemon=True).start()

    def _forget_folder(self, email, folder):
        """Take a deleted folder out of the sidebar straight away, and remember
        to keep it out until Gmail's folder list catches up."""
        hidden = set(self.cfg.get("hidden_folders", []) or [])
        hidden.add(f"{email}\t{folder}")
        self.cfg["hidden_folders"] = sorted(hidden)
        _save_settings(self.cfg)
        lst = (self._user_folders or {}).get(email, [])
        self._user_folders[email] = [uf for uf in lst
                                     if uf.get("mailbox") != folder]
        if (self._current_acct == email and self._current_folder == folder):
            self._select_folder(email, "Inbox")
        else:
            self._populate_sidebar(self.sidebar_inner)

    def _toggle_count_mute(self, email, folder, display=None):
        """Mute or un-mute a folder's unread NUMBER (Issu 2026-08-03).
        The folder's mail still shows as unread when opened; only the sidebar
        badge and the taskbar total stop counting it."""
        name = display or folder
        key = self._mini_key(email, folder)
        s = list(self.cfg.get("muted_count_folders", []) or [])
        if key in s:
            s.remove(key)
            self._flash(f'"{name}" will show an unread count again')
        else:
            s.append(key)
            self._flash(f'"{name}" will no longer show an unread count')
        self.cfg["muted_count_folders"] = s
        _save_settings(self.cfg)
        self._populate_sidebar(self.sidebar_inner)
        self._update_unread_ui()

    def _toggle_mini_folder(self, email, folder, display=None):
        """Add / remove a folder from the per-account set hidden while collapsed."""
        name = display or folder
        key = self._mini_key(email, folder)
        s = list(self.cfg.get("mini_hidden_folders", []))
        if key in s:
            s.remove(key)
            self._flash(f'"{name}" will show when collapsed')
        else:
            s.append(key)
            self._flash(f'"{name}" shows only when expanded')
        self.cfg["mini_hidden_folders"] = s
        self._populate_sidebar(self.sidebar_inner)

    def _load_more(self):
        """Fetch another page of older messages for the current folder."""
        self._fetch_limit += FETCH_LIMIT
        self._refresh_messages()

    # ── RIGHT: vertical split — message list (top) | reading pane (bottom) ────
    def _build_right_panel(self):
        right_outer = tk.Frame(self.pane, bg=C_BG2)
        self.pane.add(right_outer, minsize=320)

        self.rpane = tk.PanedWindow(right_outer, orient="vertical",
                                    bg=C_SEP, sashwidth=4,
                                    sashrelief="flat", handlesize=0)
        self.rpane.pack(fill="both", expand=True)

        self._build_msg_list()
        self._build_reading_pane()

    # ── RIGHT-TOP: Message list with Thunderbird-style columns ────────────────
    def _build_msg_list(self):
        ml_outer = tk.Frame(self.rpane, bg=C_BG2)
        self.rpane.add(ml_outer, minsize=120)

        # The "arrows are here" edge for the RIGHT pane (see _paint_nav_zone).
        self._nav_edge_messages = tk.Frame(ml_outer, bg=C_ACCENT, height=2)
        self._nav_edge_messages.pack(fill="x")

        # Folder title bar
        self.lbl_folder = tk.Label(ml_outer,
                                   text=f"  {self._current_folder}",
                                   bg=C_BG1, fg=C_FG,
                                   font=("Segoe UI", 10, "bold"),
                                   anchor="w", pady=6)
        self.lbl_folder.pack(fill="x")

        # ── Quick filter bar (DEL 09e) ───────────────────────────────────────
        # One click to narrow the list. Purely local and instant: it filters
        # what is already loaded, it does not go to the server.
        qf = tk.Frame(ml_outer, bg=C_BG1, pady=2)
        qf.pack(fill="x")
        tk.Label(qf, text="  Show:", bg=C_BG1, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(side="left")
        self._quick_btns = {}
        for key, label in (("unread", "● Unread"), ("starred", "★ Starred"),
                           ("attach", "📎 Files"), ("tagged", "🏷 Tagged"),
                           ("followup", "🔔 Follow-up")):
            b = tk.Button(qf, text=label, bg=C_BTN_STD, fg=C_FG_DIM,
                          font=("Segoe UI", 8), relief="flat", cursor="hand2",
                          padx=8, pady=2,
                          command=lambda k=key: self._toggle_quick(k))
            b.pack(side="left", padx=2)
            self._quick_btns[key] = b
        self._quick_count = tk.Label(qf, text="", bg=C_BG1, fg=C_FG_DIM,
                                     font=("Segoe UI", 8))
        self._quick_count.pack(side="left", padx=8)

        # ── "Mark all" — always there, no keyboard shortcut to remember ──────
        # Ctrl+A already did this, but nothing on screen said so
        # (Issu 2026-08-03: "Trash har ingen Empty all / Mark all?").
        b_all = tk.Button(qf, text="☑ All", bg=C_BTN_STD, fg=C_FG_DIM,
                          font=("Segoe UI", 8), relief="flat", cursor="hand2",
                          padx=8, pady=2,
                          command=lambda: self._select_all(True))
        b_all.pack(side="left", padx=2)
        add_tooltip(b_all, "Tick every message shown here (same as Ctrl+A). "
                           "Escape, or Clear on the bar below, unticks them.")

        # ── "✓ Read all" — mark the WHOLE open folder read in one click ──────
        # Smoother than ☑ All then ● Mark read, and it reaches the whole folder
        # on the server, not just the ~40 loaded (Issu 2026-08-03).
        self._read_all_btn = tk.Button(
            qf, text="✓ Read all", bg=C_BTN_STD, fg=C_FG_DIM,
            font=("Segoe UI", 8), relief="flat", cursor="hand2",
            padx=8, pady=2, command=self._mark_current_folder_read)
        self._read_all_btn.pack(side="left", padx=2)
        add_tooltip(self._read_all_btn,
                    "Mark EVERY unread message in this folder as read — the "
                    "whole folder on Gmail, not just what is loaded. Adds "
                    "“read”, never removes it.")

        # ── "Empty Trash" — shown ONLY while you are looking at the Trash ────
        self._empty_trash_btn = tk.Button(
            qf, text="🔥 Empty Trash", bg=C_BTN_DEL, fg=C_BTN_FG,
            font=("Segoe UI", 8, "bold"), relief="flat", cursor="hand2",
            padx=8, pady=2, command=self._empty_trash)
        add_tooltip(self._empty_trash_btn,
                    "Erase EVERYTHING in the Gmail Trash — the whole thing, "
                    "not just what is loaded here. Counts it first, asks "
                    "twice, and cannot be undone.")

        # ── In-window Undo bar (Issu 2026-08-02) ─────────────────────────────
        # Replaces the old floating "Deleted N — Undo" popup that sat on top of
        # every other program and counted down every second. It lives HERE, to
        # the right of the Follow-up quick filter, is hidden until a delete
        # happens, and shows only three steady states: "60 seconds to undo",
        # then "30 sec", then "10 sec" in red. No per-second flicker.
        self._undo_bar = tk.Frame(qf, bg=C_BG1)
        # C_BTN_UNDO is the normal colour of the Undo button — change it here.
        self._undo_btn = tk.Button(
            self._undo_bar, text="↺ Undo delete", bg=C_BTN_UNDO, fg=C_BTN_FG,
            font=("Segoe UI", 8, "bold"), relief="flat", cursor="hand2",
            padx=10, pady=2, command=self._inwindow_undo_click)
        self._undo_btn.pack(side="right", padx=(6, 8))
        # ── DEL 09j — "⚡ DO IT" (Issu 2026-08-22) ───────────────────────────
        # "Kanske bra med en röd DO-knapp, nära UNDO-knapp = skynda på
        #  processen."  The undo window exists so a mistake can be taken back,
        #  but when you already know the delete was right, waiting a minute for
        #  a timer to run out is pure dead time. This is the other half of the
        #  pair: Undo cancels, Do commits, and both are one click away.
        self._do_btn = tk.Button(
            self._undo_bar, text="⚡ Do it", bg=C_BTN_DO, fg=C_BTN_FG,
            font=("Segoe UI", 8, "bold"), relief="flat", cursor="hand2",
            padx=10, pady=2, command=self._inwindow_do_click)
        self._do_btn.pack(side="right", padx=(0, 4))
        add_tooltip(self._do_btn,
                    "Do it NOW — stop waiting for the undo window and send "
                    "the delete to Gmail straight away.")
        self._undo_lbl = tk.Label(self._undo_bar, text="", bg=C_BG1,
                                  fg=C_ACCENT, font=("Segoe UI", 8, "bold"))
        self._undo_lbl.pack(side="right")
        # Packed to the far right of the quick-filter row only while a delete is
        # in limbo; _show_inwindow_undo / _hide_inwindow_undo pack and forget it.
        self._undo_bar_cb = None        # what Undo should call right now

        # ── In-window SEND bar (Issu 2026-08-08) ─────────────────────────────
        # "Du verkar ha flyttat ut SENDING som popup igen, i stället för att ha
        # den inuti programmet."  Quite right: deleting got its in-window undo
        # bar back on 2026-08-02, but SENDING was still throwing an
        # always-on-top floating window over whatever else was on screen, and
        # it counted down every single second.
        #
        # It now lives here, next to the delete bar, and shows the same kind of
        # steady states — no per-second ticking, nothing floating over other
        # programs. Its own frame rather than sharing the delete one, so
        # deleting a message while another is on its way out still shows both.
        self._send_bar = tk.Frame(qf, bg=C_BG1)
        # C_BTN_UNDO is the normal colour of this button — change it here.
        self._send_btn = tk.Button(
            self._send_bar, text="✖ Cancel send", bg=C_BTN_UNDO, fg=C_BTN_FG,
            font=("Segoe UI", 8, "bold"), relief="flat", cursor="hand2",
            padx=10, pady=2, command=self._inwindow_send_cancel_click)
        self._send_btn.pack(side="right", padx=(6, 8))
        # The same "stop waiting" button for the send side (DEL 09j).
        self._send_do_btn = tk.Button(
            self._send_bar, text="⚡ Send now", bg=C_BTN_DO, fg=C_BTN_FG,
            font=("Segoe UI", 8, "bold"), relief="flat", cursor="hand2",
            padx=10, pady=2, command=self._inwindow_send_now_click)
        self._send_do_btn.pack(side="right", padx=(0, 4))
        add_tooltip(self._send_do_btn,
                    "Send it NOW — skip the rest of the undo-send window.")
        self._send_lbl = tk.Label(self._send_bar, text="", bg=C_BG1,
                                  fg=C_ACCENT, font=("Segoe UI", 8, "bold"))
        self._send_lbl.pack(side="right")
        self._send_bar_id  = None      # outbox id this bar is about
        self._send_after_ids = []

        # ── Bulk action bar — only visible when several rows are ticked ──────
        self.bulk_bar = tk.Frame(ml_outer, bg=C_BG4, pady=3)
        self._bulk_lbl = tk.Label(self.bulk_bar, text="", bg=C_BG4, fg=C_FG,
                                  font=("Segoe UI", 9, "bold"))
        self._bulk_lbl.pack(side="left", padx=8)
        for label, colour, cmd, tip in (
                ("🏷 Tag…",        C_BTN_STD,  lambda: self._bulk_tag(), None),
                ("● Mark read",   C_BTN_STD,  lambda: self._bulk_mark_read(), None),
                ("📁 Move to…",    "#3a6a8a",  lambda: self._bulk_move(),
                 "Move the ticked messages to a folder/label on Gmail. Opens "
                 "the same folder picker as a rule — Inbox and its sub-folders, "
                 "expand the ones you want, or type a new name. This replaces "
                 "drag-and-drop, which Gmail's labels do not support."),
                ("🗒 To Notes",    C_BTN_NOTE, lambda: self._bulk_to_notes(), None),
                ("💾 Archive",     C_BTN_STD,  lambda: self._bulk_archive(), None),
                ("🚫 Junk filter…", C_BTN_STD, lambda: self._bulk_make_junk_filter(),
                 "Build ONE mail filter that matches every selected sender "
                 "(Match: any) so their mail is cleared automatically from now "
                 "on — pick what it does (trash / hide / tag)."),
                ("🗑 Delete",      C_BTN_DEL,  lambda: self._bulk_delete(), None)):
            b = tk.Button(self.bulk_bar, text=label, bg=colour, fg=C_BTN_FG,
                          font=("Segoe UI", 8), relief="flat", cursor="hand2",
                          padx=8, pady=2, command=cmd)
            b.pack(side="left", padx=2)
            if tip:
                add_tooltip(b, tip)
        tk.Button(self.bulk_bar, text="Clear", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 8), relief="flat", cursor="hand2",
                  padx=8, pady=2,
                  command=lambda: self._select_all(False)).pack(side="right",
                                                                padx=8)
        # Not packed yet — _update_bulk_bar shows and hides it.

        # ── Frozen header + scrollable rows ──────────────────────────────────
        # The header is a SEPARATE frame above the canvas so it stays visible
        # while the rows scroll. To keep its columns aligned with the rows, the
        # header and the canvas share one left region (the scrollbar sits to the
        # right of BOTH), and the canvas inner frame is stretched to the canvas
        # width — so identical columnconfigure() on both lines the columns up.
        body = tk.Frame(ml_outer, bg=C_BG2)
        body.pack(fill="both", expand=True)

        ml_sb = tk.Scrollbar(body, orient="vertical", bg=C_BG3, troughcolor=C_BG1)
        ml_sb.pack(side="right", fill="y")

        stack = tk.Frame(body, bg=C_BG2)
        stack.pack(side="left", fill="both", expand=True)

        # Frozen header strip (same column geometry as the data rows).
        self.ml_hdr = tk.Frame(stack, bg=C_BG3)
        self.ml_hdr.pack(side="top", fill="x")
        self._hdr_labels = {}      # column index → header Label (for sort arrows)
        self._hdr_base   = {}      # column index → base header text (no arrow)
        for text, col, minsize, weight in _MSG_COLUMNS:
            self.ml_hdr.columnconfigure(col, weight=weight, minsize=minsize)
            lbl = tk.Label(self.ml_hdr, text=text, bg=C_BG3, fg=C_FG_DIM,
                           font=("Segoe UI", 8, "bold"), anchor="w",
                           padx=4, pady=3)
            lbl.grid(row=0, column=col, sticky="ew")
            self._hdr_labels[col] = lbl
            self._hdr_base[col]   = text
            if col != 4:   # every column except the thread-toggle "+" sorts
                lbl.configure(cursor="hand2")
                lbl.bind("<Button-1>", lambda e, c=col: self._sort_by(c))
                lbl.bind("<Enter>", lambda e, w=lbl: w.configure(fg=C_ACCENT))
                lbl.bind("<Leave>", lambda e, w=lbl, c=col: w.configure(
                    fg=C_ACCENT if c == self._sort_col else C_FG_DIM))
        tk.Frame(self.ml_hdr, bg=C_SEP, height=1).grid(
            row=1, column=0, columnspan=len(_MSG_COLUMNS), sticky="ew")
        self._update_header_arrows()

        self.ml_canvas = tk.Canvas(stack, bg=C_BG2, highlightthickness=0)
        ml_sb.configure(command=self.ml_canvas.yview)
        self.ml_canvas.configure(yscrollcommand=ml_sb.set)
        self.ml_canvas.pack(side="top", fill="both", expand=True)

        self._attach_nav(self.ml_canvas)
        self.ml_inner = tk.Frame(self.ml_canvas, bg=C_BG2)
        self.ml_cwin  = self.ml_canvas.create_window((0, 0), window=self.ml_inner, anchor="nw")
        self.ml_inner.bind("<Configure>",
                           lambda e: self.ml_canvas.configure(
                               scrollregion=self.ml_canvas.bbox("all")))
        self.ml_canvas.bind("<Configure>",
                            lambda e: self.ml_canvas.itemconfig(self.ml_cwin, width=e.width))
        _bind_mousewheel(self.ml_inner, self.ml_canvas)

        # Shared column geometry on the data-row frame (matches the header).
        for _text, col, minsize, weight in _MSG_COLUMNS:
            self.ml_inner.columnconfigure(col, weight=weight, minsize=minsize)

        # Data rows start at grid row 0 now (header lives in its own frame).
        self._grid_row = 0

    # ── RIGHT-BOTTOM: Reading pane (thread context + Från/Till/Ämne + body) ───
    def _build_reading_pane(self):
        rp_outer = tk.Frame(self.rpane, bg=C_BG2)
        self.rpane.add(rp_outer, minsize=120)
        self.reading_pane = rp_outer

        # ── Reader-side control: show the whole thread, or just the
        #    message that's actually open. Default OFF — only the
        #    opened message (plus the single message it's a direct
        #    reply to, handled inside _show_message_in_reading_pane) is
        #    shown, so old rounds don't pile up endlessly.
        self._show_full_thread = tk.BooleanVar(
            value=bool(self.cfg.get("rp_show_thread", False)))
        # Two more reader toggles, both remembered, both OFF by default
        # (Issu's request): whether the rules panel and the action buttons
        # show at the TOP of the opened message. Keeping them collapsed keeps
        # the message itself the first thing you see.
        self._rp_show_rules = tk.BooleanVar(
            value=bool(self.cfg.get("rp_show_rules", False)))
        self._rp_show_actions = tk.BooleanVar(
            value=bool(self.cfg.get("rp_show_actions", False)))

        ctl = tk.Frame(rp_outer, bg=C_BG1)
        ctl.pack(fill="x")

        def _reader_toggle(text, var, cfg_key):
            def _cmd():
                self.cfg[cfg_key] = bool(var.get())
                _save_settings(self.cfg)
                if self._selected_msg:
                    self._show_message_in_reading_pane(self._selected_msg)
            tk.Checkbutton(ctl, text=text, variable=var, command=_cmd,
                           bg=C_BG1, fg=C_FG_DIM, selectcolor=C_BG2,
                           activebackground=C_BG1, activeforeground=C_FG,
                           font=("Segoe UI", 8), anchor="w",
                           padx=10, pady=3, relief="flat",
                           highlightthickness=0).pack(side="left")

        # "Show full thread history" keeps its own handler (re-renders only).
        tk.Checkbutton(ctl, text="Show full thread history",
                       variable=self._show_full_thread,
                       command=self._on_show_full_thread_toggled,
                       bg=C_BG1, fg=C_FG_DIM, selectcolor=C_BG2,
                       activebackground=C_BG1, activeforeground=C_FG,
                       font=("Segoe UI", 8), anchor="w",
                       padx=10, pady=3, relief="flat",
                       highlightthickness=0).pack(side="left")
        _reader_toggle("Rules acting on this mail", self._rp_show_rules,
                       "rp_show_rules")
        _reader_toggle("Message actions", self._rp_show_actions,
                       "rp_show_actions")

        # ── Scrollable area: holds context messages + the opened message ───
        self.rp_canvas = tk.Canvas(rp_outer, bg=C_BG2, highlightthickness=0)
        rp_sb = tk.Scrollbar(rp_outer, orient="vertical",
                             command=self.rp_canvas.yview,
                             bg=C_BG3, troughcolor=C_BG1)
        rp_sb.pack(side="right", fill="y")
        self.rp_canvas.configure(yscrollcommand=rp_sb.set)
        self.rp_canvas.pack(fill="both", expand=True)

        self._attach_nav(self.rp_canvas)
        self.rp_inner = tk.Frame(self.rp_canvas, bg=C_BG2)
        self.rp_cwin  = self.rp_canvas.create_window((0, 0), window=self.rp_inner, anchor="nw")
        self.rp_inner.bind("<Configure>",
                           lambda e: self.rp_canvas.configure(
                               scrollregion=self.rp_canvas.bbox("all")))
        self.rp_canvas.bind("<Configure>", self._on_rp_canvas_configure)
        _bind_mousewheel(self.rp_inner, self.rp_canvas)

        self._show_reading_pane_empty()

    def _on_show_full_thread_toggled(self):
        # Remember it, then re-render whatever is currently open.
        self.cfg["rp_show_thread"] = bool(self._show_full_thread.get())
        _save_settings(self.cfg)
        if self._selected_msg:
            self._show_message_in_reading_pane(self._selected_msg)

    def _show_reading_pane_empty(self):
        for w in self.rp_inner.winfo_children():
            w.destroy()
        tk.Label(self.rp_inner, text="No message selected",
                 bg=C_BG2, fg=C_FG_DIM,
                 font=("Segoe UI", 9, "italic"), pady=20).pack()

    def _refresh_messages(self, background=False):
        """DEMO mode → instant mock data. Real mode → fetch off the main
        thread (read-only) so the GUI never freezes on the network.

        `background=True` marks this as an automatic check, which is the only
        case that may raise a notification — pressing Refresh yourself should
        never make a popup appear in your face."""
        self._bg_check = bool(background)
        # ── One automatic refresh at a time (Issu 2026-08-19) ────────────────
        # In the ALL ACCOUNTS view _poll_account counts itself as "viewing" for
        # EVERY account (`self._current_acct in (email, ALL_ACCOUNTS_ID)`), so
        # each of his five accounts finishing its own check kicked off a fresh
        # refresh of all five. With issusbarn on a 1-minute interval and three
        # more on 5, that is a full five-account fetch every few seconds — his
        # log has three of them 8 seconds apart, each abandoned at the 25 s
        # deadline, none ever finishing. They were not five checks; they were
        # one check being restarted before it could answer.
        #
        # A refresh YOU asked for always goes through. The time limit makes it
        # self-healing: if a fetch somehow never reports back, the next check
        # after that stops waiting for it rather than going quiet for good.
        if background and getattr(self, "_fetch_in_flight", False):
            age = time.monotonic() - getattr(self, "_fetch_started", 0.0)
            if age < FETCH_DEADLINE_SEC * 2:
                log.debug("Auto-refresh skipped — one has been on the wire for "
                          "%.0f s already", age)
                return
            log.info("The previous refresh has been running %.0f s and never "
                     "reported back — starting a new one", age)
        # ── Virtual folders — local only, no server involved ─────────────────
        if self._current_folder == "Snoozed":
            self._render_snoozed()
            return
        if self._current_folder == "Notes":
            self._render_notes()
            return
        if self._current_folder == "Follow-ups":
            self._render_followups()
            return
        if self._current_folder == "Deleted":
            self._render_deleted()
            return

        if self._demo_mode:
            self._all_messages = _mock_messages(self._current_folder, self._current_acct)
            self._apply_messages(self._all_messages)
            self._set_status(checked=datetime.now(), extra="demo data")
            self._show_quota(2.4 * 1024**3, 15 * 1024**3)   # so the gauge shows
            return

        folder = self._current_folder
        acct   = self._current_acct
        if acct == ALL_ACCOUNTS_ID:
            targets = [a for a in self._accounts if not a.get("virtual")]
        else:
            targets = [a for a in self._accounts if a.get("email") == acct]

        if not targets:
            self._all_messages = []
            self._apply_messages([])
            return

        # ── An account that is not answering is stood down (Issu 2026-08-17) ──
        # Only for AUTOMATIC passes. A refresh you asked for tries everything
        # and clears the stand-down first, so nothing can be written off behind
        # your back. `carried` keeps a skipped account's messages exactly as
        # they are on screen — standing an account down must never look like
        # its mail vanished.
        stalled, carried = [], []
        if background:
            live = []
            for a in targets:
                left = _stall_left(a["email"])
                if left > 0:
                    stalled.append((a["email"], left))
                else:
                    live.append(a)
            if live and stalled:
                skip = {e for e, _ in stalled}
                carried = [m for m in (self._all_messages or [])
                           if m.get("account_email") in skip]
                targets = live
            elif not live:
                stalled = []          # everything is down: try anyway
        else:
            for a in targets:
                _stall_clear(a["email"])

        # ── INSTANT: show what is already on disk, then refresh over it ───────
        # Reading the cache is local and fast, so a folder you have opened
        # before appears immediately instead of after a network round-trip.
        # The background worker below then updates flags / new mail.
        # Only for a FOREGROUND open (you clicked the folder). A background
        # auto-check must never redraw the list you are reading — that is a
        # flicker for no reason.
        shown_from_cache = False
        if (not background and self.cfg.get("cache_enabled", True)
                and folder not in _VIRTUAL_FOLDERS):
            try:
                cached = []
                for a in targets:
                    cached.extend(_cache_load_folder(a["email"], folder,
                                                     self._fetch_limit))
                # Local drafts are on this disk — there is nothing to wait for,
                # so they belong in the INSTANT render too. Without this, the
                # Drafts folder sat on "loading…" before showing messages that
                # were already sitting on the hard drive (Issu 2026-08-07:
                # "Väldigt stönigt att behöva vänta på Loading HELA TIDEN").
                if folder == "Drafts":
                    try:
                        cached.extend(self._local_draft_rows(targets))
                    except Exception as e:
                        log.debug("local drafts (cache path) failed: %s", e)
                if cached:
                    cached.sort(key=lambda m: m.get("_sortkey", 0.0),
                                reverse=True)
                    # The instant render replaces every row object too, so the
                    # ticks need the same carry-over as _apply_messages gives
                    # them (Issu 2026-09-20). Pressing ↻ on the folder you are
                    # already in must not clear what you had marked.
                    _carry = ([m for m in (self._messages or [])
                               if m.get("id") in self._selected_ids]
                              if self._selected_ids else [])
                    self._all_messages = cached
                    self._messages     = self._apply_local_state(list(cached))
                    self._selected_ids = self._carry_selection(_carry,
                                                               self._messages)
                    self._selected_msg = None
                    self._expanded_rows = set()
                    self._search_active = False
                    self._apply_sort()
                    self._render_msg_list()
                    shown_from_cache = True
            except Exception as e:
                log.debug("instant cache render failed: %s", e)

        # Only for a refresh YOU asked for (Issu 2026-10-12, "så många UPDATING
        # och LOADING"). This used to run for the automatic checks too, and an
        # automatic check that finds nothing new returns early from
        # _apply_messages WITHOUT rewriting the title — so the Inbox sat on
        # "(loading…)" after every quiet check (Main is checked every 2 min).
        if not background:
            self.lbl_folder.configure(
                text=(f"  {self._folder_display_name(folder)}"
                      f"  ({len(self._messages)})  ·  updating…"
                      if shown_from_cache
                      else f"  {self._folder_display_name(folder)}  (loading…)"))
        token = object()
        self._fetch_token = token
        # Whether a fetch is on the wire right now, so an empty list can say
        # "still fetching" instead of claiming the folder is empty. The start
        # time goes with it, so the guard at the top of this function can tell
        # "busy" from "stuck".
        self._fetch_in_flight = True
        self._fetch_started   = time.monotonic()

        def worker():
            collected, errors = [], []
            # ── One thread per ACCOUNT (Issu 2026-08-08) ─────────────────────
            # This used to be a plain sequential loop, so opening Trash or Spam
            # in the All Accounts view meant five full round trips one after
            # another — "jag hade väntat kanske 10 sekunder… det är fortfarande
            # loading nu". Different accounts are different servers-worth of
            # work and different pooled connections, so there is nothing to
            # gain by taking turns: five accounts now cost roughly what one
            # used to. A single account behaves exactly as before.
            #
            # `interactive` puts a folder YOU opened on the fast lane, so it
            # does not queue behind the auto-check and the read-ahead either.
            lock = threading.Lock()
            answered = set()          # accounts that finished inside the round

            def fetch_one(a):
                _t0 = time.monotonic()
                try:
                    pwd  = _decrypt_secret(a.get("secret", ""))
                    msgs = _fetch_folder_smart(
                        a["email"], pwd, folder, limit=self._fetch_limit,
                        use_cache=self.cfg.get("cache_enabled", True),
                        interactive=not background)
                    if time.monotonic() - _t0 > 5:
                        log.info("Slow fetch: %s/%s took %.1f s (%s)",
                                 a["email"], folder, time.monotonic() - _t0,
                                 "automatic" if background else "by hand")
                    with lock:
                        collected.extend(msgs)
                except Exception as e:
                    with lock:
                        errors.append((a["email"], str(e)))
                    log.error("Fetch failed for %s/%s: %s", a["email"], folder, e)
                finally:
                    with lock:
                        answered.add(a["email"])

            # ── ONE account gets the deadline too (Issu 2026-08-19) ─────────
            # This used to call fetch_one() straight, on this thread, for a
            # single account — which meant NO time limit at all: the label sat
            # on "loading…" for however long the socket took (30 s per stalled
            # read, and longer when several piled up). The five-account path
            # had been given a deadline on 2026-08-17 and the one-account path,
            # which is what he uses most of the day, was left behind. Same
            # thread, same join, same limit for both now.
            threads = [threading.Thread(target=fetch_one, args=(a,),
                                        daemon=True) for a in targets]
            for t in threads:
                t.start()
            # ── ONE SHARED DEADLINE, not 120 s per thread ────────────────
            # Issu 2026-08-17, "konstant loading": the list is only drawn
            # once every account has answered, so the slowest one decided
            # how long the window said "updating…". His log had 169 s and
            # 128 s waits for a five-account view — the joins were 120 s
            # EACH, so one account that neither answered nor died on time
            # held everything.
            #
            # Now the whole round has FETCH_DEADLINE_SEC. What has arrived
            # is drawn; a straggler's thread keeps running (it is a daemon
            # and its result is simply not used this round), and the mail
            # already on screen for that account is carried over below, so
            # nothing appears to vanish. The next check picks it up.
            deadline = time.monotonic() + FETCH_DEADLINE_SEC
            for t in threads:
                t.join(timeout=max(0.2, deadline - time.monotonic()))
            # ── Your OWN unsent drafts belong in Drafts (Issu 2026-08-07) ────
            # Half-written messages live on this machine, in Helpfiles/
            # Freemail/Drafts, and were shown NOWHERE — you only ever got them
            # back through the "unsent messages found" question at start-up. So
            # the Drafts folder listed Gmail's drafts, the badge counted
            # something else again, and neither matched what was actually
            # waiting. They now appear here, at the top, marked as local, and
            # double-clicking one opens it for writing.
            if folder == "Drafts":
                try:
                    collected.extend(self._local_draft_rows(targets))
                except Exception as e:
                    log.warning("Could not list local drafts: %s", e)
            # Take a SNAPSHOT under the lock. A straggler thread is still
            # running and may append after this point; what gets drawn must be
            # a list nobody is writing to.
            late = [a["email"] for a in targets if a["email"] not in answered]
            with lock:
                collected = list(collected)
            if late:
                log.info("Drawing the list without %s — still fetching after "
                         "%d s; their mail stays as it was",
                         ", ".join(late), FETCH_DEADLINE_SEC)
                # Same promise as a stood-down account: a slow one must not
                # look as though its mail disappeared.
                collected.extend(m for m in (self._all_messages or [])
                                 if m.get("account_email") in set(late))
            # What a stood-down account already had stays in the list.
            collected.extend(carried)
            collected.sort(key=lambda m: m.get("_sortkey", 0.0), reverse=True)

            # Auto-save attachments from selected senders (off the GUI thread).
            saved = []
            try:
                saved = _autosave_run(collected, self._autosave_store)
            except Exception as e:
                log.error("autosave run failed: %s", e)

            # Keep our own copy of everything, if that is switched on. Also
            # off the GUI thread, and additive only — it can never remove
            # anything from Gmail or from the archive.
            archived = 0
            if self.cfg.get("archive_auto", False):
                try:
                    archived = _archive_run(self.cfg, collected)
                except Exception as e:
                    log.error("archive run failed: %s", e)

            # How full the mailbox is — asked at most every 15 minutes, since
            # it barely moves and every call is another login.
            quota = None
            try:
                acct = self._quota_target_account()
                cached = self._quota_cache.get(acct)
                stale = (cached is None or
                         (datetime.now() - cached[2]).total_seconds() > 900)
                if acct and stale:
                    pwd_q = self._secret_for(acct)
                    if pwd_q:
                        quota = _imap_quota(acct, pwd_q)
                        if quota:
                            self._quota_cache[acct] = (quota[0], quota[1],
                                                       datetime.now())
                elif cached:
                    quota = (cached[0], cached[1])
            except Exception as e:
                log.debug("quota check failed: %s", e)

            def done():
                if self._fetch_token is not token:
                    # ── A newer refresh started while this one was on the wire.
                    #
                    # Issu 2026-08-17, "filter verkar inte köras automatiskt
                    # förrän jag går dit själv" — THIS is why, and his log
                    # proves it: between 07:15 and 08:05 not one filter ran,
                    # while Loss.THN@gmail.com timed out every 30 seconds.
                    #
                    # The rules only ever run inside _apply_messages, which
                    # sits below this line. The auto-check is every 60 s and
                    # one sick account made a fetch take ~60 s (30 s cached +
                    # 30 s full), so EVERY refresh was superseded by the next
                    # one before it finished — and every filter run was thrown
                    # away with it. Nothing was filed until he opened a folder
                    # by hand, which starts a fetch that finishes.
                    #
                    # Drawing a stale list would be wrong, so that part still
                    # goes. But the mail HAS been fetched, and the rules must
                    # run on it: this is the same "check an account you are not
                    # looking at" path _poll_account already uses, so it is not
                    # a new kind of behaviour, only one that now also applies
                    # when the timing is unlucky.
                    try:
                        self._apply_local_state(collected)
                    except Exception as e:
                        log.error("Filter run for a superseded fetch "
                                  "failed: %s", e)
                    # No _notify_new here on purpose: the newer refresh will
                    # announce the same mail, and _seen_keys must not be filled
                    # in behind its back or the toast would be lost entirely.
                    return
                self._fetch_in_flight = False
                self._all_messages = collected
                self._apply_messages(collected)
                # Routine housekeeping is REPORTED, not announced: it goes in
                # the status line rather than a box in front of your reading.
                bits = []
                if saved:
                    bits.append(f"saved {len(saved)} attachment(s)")
                if archived:
                    bits.append(f"archived {archived}")
                # Say it out loud rather than just being quietly faster: a
                # skipped account is something you are entitled to know about.
                for who, left in stalled:
                    bits.append(f"{who} not answering — trying again in "
                                f"{int(left // 60) + 1} min")
                self._set_status(checked=datetime.now(),
                                 extra=("  ·  ".join(bits) if bits else ""))
                if quota:
                    self._show_quota(quota[0], quota[1])
                # Keep the sidebar "(N)" badges and the taskbar in step with
                # what the server now holds (throttled so folder-hopping does
                # not open a connection every click).
                self._maybe_refresh_counts(force=background)
                # ── Read the rest in, quietly, before you ask for it ─────────
                # Issu 2026-08-08: "kan inte programmet jobba med nya saker i
                # bakgrunden, och läsa in lokalt?" — yes. The list you are
                # looking at is headers; the bodies now come down behind it,
                # newest first, so clicking a message is a local read.
                self._start_prefetch(collected, token)
                # ── A server that is being slow is NOT a dialog ──────────────
                # Issu 2026-08-17: "konstant loading… couldn't load from
                # loss.thn". This used to be a MODAL box, raised on every
                # refresh that had any error at all — so an account timing out
                # every minute put a window in front of everything, every
                # minute, and until it was clicked the program was exactly as
                # unusable as it looked.
                #
                # A timeout needs no decision from you: the account is stood
                # down, its mail is still on screen, and the next check tries
                # again. That belongs in the status line. What DOES need you is
                # a rejected password — and that is said once per account per
                # session, not once a minute.
                if errors:
                    for who, why in errors:
                        log.warning("Could not load %s/%s: %s", who, folder, why)
                    stalls = [w for w, why in errors if _is_network_stall(why)]
                    auth   = [(w, why) for w, why in errors
                              if not _is_network_stall(why)]
                    if stalls:
                        self._flash(f"{', '.join(stalls)} did not answer — "
                                    f"their mail is unchanged, trying again "
                                    f"shortly")
                    fresh = [(w, why) for w, why in auth
                             if w not in self._told_about_account]
                    if fresh:
                        for w, _why in fresh:
                            self._told_about_account.add(w)
                        detail = "\n".join(f"• {w}: {why}" for w, why in fresh)
                        messagebox.showwarning(
                            "Could not load mail",
                            "This is not a slow connection — the server "
                            "refused:\n\n" + detail +
                            "\n\nCheck the account's app password "
                            "(Accounts → Add Gmail account… explains where to "
                            "generate one).\n\nSaid once per account; the log "
                            "keeps every occurrence.", parent=self.root)
            try:
                self.root.after(0, done)
            except Exception:
                # Window closed mid-fetch, or Tk refused the callback. The
                # label and the in-flight mark must not be left behind.
                self._fetch_in_flight = False

        def guarded():
            """The worker, wrapped so "loading…" can never become permanent.

            Issu 2026-08-19, "9:51 så står den som loading…": `done()` — the
            ONLY place that cleared `_fetch_in_flight` and rewrote the folder
            label — ran on the Tk thread after the worker returned. Anything
            that stopped the worker reaching `root.after(0, done)` therefore
            left the window saying "loading…" for the rest of the session, and
            the guard at the top of _refresh_messages skipping automatic
            refreshes because one was supposedly still on the wire. His log:
            "The previous refresh has been running 503 s and never reported
            back".

            A fetch that fails is a fine thing. A fetch that never says
            anything is not."""
            try:
                worker()
            except Exception as e:
                log.error("Refresh worker crashed: %s", e, exc_info=True)

                def recover():
                    self._fetch_in_flight = False
                    try:
                        self.lbl_folder.configure(
                            text=f"  {self._folder_display_name(folder)}"
                                 f"  ({len(self._messages)})")
                    except Exception:
                        pass
                    self._flash("The refresh did not finish — trying again on "
                                "the next check")
                try:
                    self.root.after(0, recover)
                except Exception:
                    self._fetch_in_flight = False

        threading.Thread(target=guarded, daemon=True).start()

    # ── Background body prefetch (Issu 2026-08-08) ──────────────────────────
    def _start_prefetch(self, messages, token):
        """Download the bodies of the newest not-yet-cached messages, quietly,
        so that opening one is a local read.

        The list arrives headers-first (that is what made switching folders
        fast), but it also meant the FIRST time you open any given message it
        has to go and fetch it — and if that lands on top of the auto-check it
        is a long wait. Fetching them in advance removes the wait entirely for
        the messages you are actually likely to click: the newest ones.

        `token` is the fetch identity. Change folder and the token changes, the
        prefetch sees it and stops — it will never spend the connection on a
        folder you have left."""
        if self._demo_mode or not self.cfg.get("prefetch_bodies", True):
            return
        want = [m for m in messages if not m.get("_body_loaded", True)][
            :int(self.cfg.get("prefetch_count", 12))]
        if not want:
            return
        # Group by (account, folder) so each group is one connection.
        groups = {}
        for m in want:
            acct, folder, uid = (m.get("account_email"), m.get("_folder"),
                                 m.get("uid"))
            if acct and folder and uid:
                groups.setdefault((acct, folder), []).append(uid)
        if not groups:
            return

        def stop():
            # Folder changed, a newer refresh started, or we are shutting down.
            return (self._fetch_token is not token
                    or getattr(self, "_closing", False))

        def worker():
            for (acct, folder), uids in groups.items():
                if stop():
                    return
                pwd = self._secret_for(acct)
                if not pwd:
                    continue
                try:
                    _prefetch_bodies(acct, pwd, folder, uids, stop=stop)
                except Exception as e:
                    log.debug("prefetch group %s/%s failed: %s",
                              acct, folder, e)

        threading.Thread(target=worker, daemon=True).start()

    def _apply_messages(self, messages):
        """Common tail used by both demo and real fetch once messages exist.

        This is also where every LOCAL rule is applied (mail filters, block
        list, snooze) and where new mail is announced — one place, so demo
        mode, a manual Refresh and a background auto-check all behave the
        same."""
        # In the All Accounts view the same mail really can arrive in two of
        # your accounts (DHL and Tradera write to both of Issu's) — collapse
        # those into one row rather than showing it twice.
        messages = _dedupe_messages(
            messages, across_accounts=(self._current_acct == ALL_ACCOUNTS_ID))
        messages = self._apply_local_state(messages)
        bg = self._bg_check            # capture before _notify_new resets it
        self._notify_new(messages)

        # If a BACKGROUND check changed nothing you can see (same messages,
        # same read/star state), do NOT redraw. Re-rendering the identical list
        # every check is a flicker — and it would also wipe the message you are
        # currently reading. Issu is sensitive to blinking, so silence is the
        # right default here.
        new_sig = frozenset(
            (m.get("id"), bool(m.get("unread")), bool(m.get("starred")))
            for m in messages)
        if bg and new_sig == getattr(self, "_last_render_sig", None):
            self._reconcile_folder_badge()
            return

        # ── Carry the ticks over to the refreshed rows (Issu 2026-09-20) ─────
        # Captured BEFORE self._messages is replaced, because that is the only
        # moment both lists exist: the ids in _selected_ids point at the old
        # objects, the new ones have ids of their own. See _carry_selection.
        _carry = ([m for m in (self._messages or [])
                   if m.get("id") in self._selected_ids]
                  if self._selected_ids else [])
        self._messages = messages
        self._selected_ids = self._carry_selection(_carry, messages)

        # ── Keep the message you are reading OPEN across a background check ───
        # A background auto-check that finds new mail used to clear the reading
        # pane and drop the selection — so text you had highlighted (a tracking
        # number, a link) vanished mid-copy. That is maddening. On a BACKGROUND
        # refresh we now find the still-open message in the fresh list and leave
        # the reading pane exactly as it is (its text selection intact); only
        # when nothing is open, or the open message has truly gone, do we clear
        # the pane. A foreground refresh (you pressed ↻) behaves as before.
        keep = None
        vanished = None
        if bg and self._selected_msg is not None:
            try:
                _open_key = _msg_key(self._selected_msg)
                keep = next((m for m in messages
                             if _msg_key(m) == _open_key), None)
                # Not gone, just RENUMBERED: a message that a rule moved keeps
                # its Message-ID but gets a new UID, so _msg_key no longer
                # matches. Recognise it and carry on with the same message
                # rather than blanking the pane (Issu 2026-08-07).
                if keep is None:
                    _rk = _reply_key(self._selected_msg)
                    if _rk:
                        keep = next((m for m in messages
                                     if _reply_key(m) == _rk), None)
                if keep is None:
                    vanished = self._selected_msg
            except Exception:
                keep = None

        if keep is None:
            self._selected_msg = None
            self._expanded_rows = set()
        self._search_active = False
        self._apply_sort()
        self.lbl_folder.configure(
            text=f"  {self._folder_display_name(self._current_folder)}"
                 f"  ({len(self._messages)})")
        self._render_msg_list()
        if keep is None:
            self._show_reading_pane_empty()
            if vanished is not None:
                # A message going away UNDER YOUR EYES, silently, is the single
                # most infuriating thing this program did (Issu 2026-08-07).
                # It is almost always one of your own rules. Say which one.
                where = self._explain_vanished(vanished)
                self._flash(f"The message you had open left this folder — "
                            f"{where}")
                self._activity_log(
                    "moved", account=vanished.get("account_email", ""),
                    sender=vanished.get("from", ""),
                    subject=vanished.get("subject", ""),
                    detail=f"left {vanished.get('_folder','')} while you had "
                           f"it open — {where}")
            # First list after start-up → reopen the message you had open last.
            self._maybe_restore_last_message()
        else:
            # Re-point the selection at the refreshed object and repaint the row
            # highlight — but do NOT re-render the reading pane, so your text
            # selection survives the check.
            self._selected_msg = keep
            # NOT `= {keep.get("id")}` any more (Issu 2026-09-20). That line
            # threw away however many rows you had ticked and left exactly one —
            # so marking five mails and waiting a minute for the auto-check left
            # you with one, and no sign of why. The carried set already holds
            # them; the open message only joins it when nothing at all survived.
            if not self._selected_ids:
                self._selected_ids = {keep.get("id")}
            self._repaint_selection()
        # The folder you just opened should show a badge that matches what is
        # actually in front of you — corrects a stale server count on the spot.
        self._reconcile_folder_badge()
        self._repaint_badges()
        self._last_render_sig = new_sig

    def _local_draft_rows(self, targets):
        """Your unsent local drafts, shaped like ordinary message rows.

        They are half-written messages sitting in Helpfiles/Freemail/Drafts.
        Until now nothing in the Drafts folder showed them, so the folder could
        say "(2)" while looking empty and six real half-written mails sat on
        disk unseen (Issu 2026-08-07). A row here is marked "✎ local draft" and
        opens straight back into the compose window.

        Drafts already handed to the outbox, or already sent, are skipped — the
        outbox owns those, and offering them here could send the same message
        twice."""
        emails = {a.get("email") for a in targets if a.get("email")}
        rows = []
        for d in _list_drafts():
            if d.get("sent") or d.get("queued"):
                continue
            frm = parseaddr(d.get("from", ""))[1] or d.get("from", "")
            if emails and frm and frm not in emails:
                continue
            saved = _parse_iso(d.get("saved", "")) or datetime.now()
            rows.append({
                "id":            "localdraft-" + str(d.get("id", "")),
                "uid":           None,
                "thread_id":     "localdraft-" + str(d.get("id", "")),
                "account_email": frm or (next(iter(emails), "") if emails else ""),
                "from":          frm,
                "from_name":     "✎ Draft (on this computer)",
                "subject":       d.get("subject", "") or "(no subject)",
                "date":          saved.strftime("%Y-%m-%d %H:%M"),
                "_sortkey":      saved.timestamp(),
                "_dt":           saved.isoformat(timespec="seconds"),
                "body":          d.get("body", ""),
                "_body_loaded":  True,
                "unread":        False,
                "starred":       False,
                "priority":      "normal",
                "spam":          False,
                "attachments":   list(d.get("attachments") or []),
                "_attachment_data": {},
                "_html":         "",
                "_folder":       "Drafts",
                "_to_hdr":       d.get("to", ""),
                "_cc_hdr":       d.get("cc", ""),
                "_reply_to_hdr": "",
                "_references_hdr": "",
                "_list_unsub":   "",
                "_auth_results": "",
                "_message_id":   "",
                "_ics":          "",
                "_labels":       [],
                # What marks it as ours rather than Gmail's, and how to reopen
                # it: _open_local_draft looks this id up on disk.
                "_local_draft":  d.get("id", ""),
            })
        if rows:
            log.info("Drafts: %d unsent local draft(s) listed", len(rows))
        return rows

    def _open_local_draft(self, msg):
        """Reopen one of your own unsent drafts for writing."""
        did = msg.get("_local_draft", "")
        draft = next((d for d in _list_drafts() if d.get("id") == did), None)
        if draft is None:
            self._flash("That draft is no longer on disk")
            return
        ComposeWindow(self.root, self.cfg, app=self,
                      accounts=self._accounts, draft=draft)

    def _delete_local_draft(self, msg):
        """Throw one of your own unsent drafts away, from the Drafts list."""
        did = msg.get("_local_draft", "")
        if not did:
            return
        if not messagebox.askyesno(
                "Throw this draft away",
                f"Delete the draft “{msg.get('subject','')[:60]}”?\n\n"
                "The text is gone for good. Nothing is sent, and nothing on "
                "Gmail is touched.", parent=self.root):
            return
        _delete_draft(did)
        self._activity_log("deleted", account=msg.get("account_email", ""),
                           subject=msg.get("subject", ""),
                           detail="local unsent draft thrown away")
        self._flash("Draft thrown away")
        self._refresh_messages()

    def _explain_vanished(self, msg):
        """Why did the open message leave this folder? A short phrase.

        The filter log written moments ago usually knows exactly: it records
        which rule matched which message and what it did. Falling back to a
        neutral phrase when nothing matches is better than guessing."""
        try:
            key = _msg_key(msg)
            subj = (msg.get("subject") or "").strip()
            for ev in reversed(self._filter_log[-60:]):
                if ev.get("key") == key or (subj and ev.get("subject") == subj):
                    rule    = ev.get("fname", "")
                    actions = ev.get("actions", "")
                    if rule:
                        return f'your rule "{rule}" {actions or "acted on it"}'
                    return actions or "a rule acted on it"
        except Exception:
            pass
        return ("it was moved or deleted somewhere else — the 🧾 Log button "
                "shows what happened")

    def _maybe_restore_last_message(self):
        """On the first message list shown after start-up, reopen whatever was
        open last time (matched by _msg_key). Runs once, then never again."""
        if not getattr(self, "_restore_pending", False):
            return
        self._restore_pending = False
        want = self.cfg.get("last_msg_key", "")
        if not want:
            return
        target = next((m for m in self._messages if _msg_key(m) == want), None)
        if target:
            # Open it without the click side effects, and keep the list scrolled
            # so the row is visible.
            self._focus_message(target)

    # ── Column-header sorting ──────────────────────────────────────────────────
    def _sort_key(self, m):
        """Return a sort key for the current sort column."""
        c = self._sort_col
        if c == 0:   # 📎 attachments
            return (1 if m.get("attachments") else 0,)
        if c == 1:   # ✉ address-mail
            return (1 if _addr_is_marked(self._address_store, m) else 0,)
        if c == 2:   # ★ starred
            return (1 if m.get("starred") else 0,)
        if c == 3:   # Subject
            return (m.get("subject", "").lower(),)
        if c == 5:   # Correspondent
            return (m.get("from_name", "").lower(),)
        if c == 6:   # ! priority
            rank = {"high": 2, "normal": 1, "low": 0}
            return (rank.get(m.get("priority", "normal"), 1),)
        if c == 7:   # ⚠ spam
            return (1 if m.get("spam") else 0,)
        # col 8 (Date) and any fallback → chronological
        return (m.get("_sortkey", 0.0),)

    def _apply_sort(self):
        try:
            self._messages.sort(key=self._sort_key, reverse=self._sort_desc)
        except Exception as e:
            log.warning("Sort failed: %s", e)

    def _sort_by(self, col):
        """Header click: toggle direction if same column, else switch column."""
        if col == self._sort_col:
            self._sort_desc = not self._sort_desc
        else:
            self._sort_col = col
            # Sensible default direction per column: text A→Z ascending,
            # flags/priority/date show "most" first (descending).
            # 0 📎, 1 ✉, 2 ★, 6 !, 7 ⚠, 8 Date  (3 Subject / 5 Corr. ascend).
            self._sort_desc = col in (0, 1, 2, 6, 7, 8)
        self.cfg["sort_col"]  = self._sort_col
        self.cfg["sort_desc"] = self._sort_desc
        self._update_header_arrows()
        self._apply_sort()
        self._selected_msg = None
        self._render_msg_list()

    def _update_header_arrows(self):
        """Show ▲/▼ on the active sort column header, plain text on the rest."""
        arrow = " ▼" if self._sort_desc else " ▲"
        for col, lbl in getattr(self, "_hdr_labels", {}).items():
            base = self._hdr_base.get(col, "")
            if col == self._sort_col:
                lbl.configure(text=base + arrow, fg=C_ACCENT)
            else:
                lbl.configure(text=base, fg=C_FG_DIM)

    def _effective_tid(self, msg):
        """The id the list groups a message under.

        A message in a manual MERGE group uses that group's id (a hand-picked
        set renders as one conversation). Otherwise: when auto-merge is ON, the
        Gmail conversation id; when OFF (the default), the message's own id — one
        row per message, so Tradera "Frakthandlingar" stay separate (Issu)."""
        gid = _merge_group_id_for(self._merge_store, _msg_key(msg))
        if gid is not None:
            return gid
        # A folder marked "don't auto-merge here" answers as though thread_view
        # were off, for this message only (Issu 2026-08-19). Checked BELOW the
        # manual group on purpose: the folder switch turns off the grouping the
        # PROGRAM does by itself, and a group you picked by hand is not that.
        if self._is_no_merge(msg.get("account_email", ""),
                             msg.get("_folder", "")):
            return msg.get("id")
        if self.cfg.get("thread_view", False):
            tid = msg.get("thread_id", msg.get("id"))
            # A conversation the user has explicitly SPLIT APART shows one row
            # per message again, even with auto-merge on (Issu 2026-08-02).
            if str(tid) in set(self.cfg.get("split_threads", []) or []):
                return msg.get("id")
            return tid
        return msg.get("id")

    # ── Manual conversation merge (DEL 04A1) ──────────────────────────────────
    def _merge_candidates(self, msg):
        """Messages that look like they might belong with `msg`: same sender, or
        the same subject (ignoring Re:/Sv:/Fwd:), or the same Gmail conversation.
        The clicked message is always first; the rest are offered to tick."""
        pool = self._all_messages or self._messages
        base_from = (parseaddr(msg.get("from", ""))[1] or "").lower()
        base_subj = _normalize_subject(msg.get("subject", ""))
        base_tid  = msg.get("thread_id")
        out, seen = [msg], {_msg_key(msg)}
        for m in pool:
            k = _msg_key(m)
            if not k or k in seen:
                continue
            frm  = (parseaddr(m.get("from", ""))[1] or "").lower()
            subj = _normalize_subject(m.get("subject", ""))
            same_thread = bool(base_tid and m.get("thread_id") == base_tid)
            if same_thread or (base_from and frm == base_from) \
                    or (base_subj and subj == base_subj):
                out.append(m)
                seen.add(k)
        return out

    def _do_merge(self, keys):
        gid = _merge_add_group(self._merge_store, keys)
        if not gid:
            self._flash("Pick at least two messages")
            return False
        _save_merge_groups(self._merge_store)
        self._expanded_rows = set()
        self._render_msg_list()
        self._flash("Merged into one conversation")
        return True

    def _unmerge(self, msg):
        """Split the whole conversation `msg` is in back into single messages.

        Works for BOTH kinds of grouping (Issu 2026-08-02):
          • a manual MERGE group  → the group is dissolved.
          • an AUTO Gmail thread (thread_view on) → the thread id is remembered
            in cfg["split_threads"], so it stays one-row-per-message from now
            on. Re-group it any time with "Merge with… (pick look-alikes)"."""
        key = _msg_key(msg)
        if _merge_group_id_for(self._merge_store, key) is not None:
            _merge_remove_group_of(self._merge_store, key)
            _save_merge_groups(self._merge_store)
            self._expanded_rows = set()
            self._render_msg_list()
            self._flash("Un-merged — one row per message again")
            return
        # Auto-thread: remember this Gmail conversation as "keep separate".
        if self.cfg.get("thread_view", False):
            tid = str(msg.get("thread_id", msg.get("id")))
            splits = list(self.cfg.get("split_threads", []) or [])
            if tid not in splits:
                splits.append(tid)
                self.cfg["split_threads"] = splits
                _save_settings(self.cfg)
            self._expanded_rows = set()
            self._render_msg_list()
            self._flash("Separated — one row per message again")
            return
        self._flash("This message is not part of a conversation")

    def _merge_selected_from_menu(self):
        """View → Merge selected: merge the current multi-selection directly, or
        open the look-alike picker on the single selected message."""
        sel = self._selected_messages()
        if len(sel) >= 2:
            self._do_merge([_msg_key(m) for m in sel])
        elif self._selected_msg is not None:
            self._merge_dialog(self._selected_msg)
        else:
            messagebox.showinfo(
                "Merge messages",
                "Select the messages to merge first (Ctrl-click several to tick "
                "them), then choose Merge.", parent=self.root)

    def _merge_dialog(self, msg):
        """Pick which look-alike messages to MERGE into one conversation (Issu:
        default is one row per message; this is the opt-in grouping)."""
        cands = self._merge_candidates(msg)
        if len(cands) < 2:
            messagebox.showinfo(
                "Merge messages",
                "No other messages loaded here look like they belong with this "
                "one (same sender, subject or conversation).",
                parent=self.root)
            return
        top = self._dialog_shell("Merge into one conversation", 720, 560)
        tk.Label(top, text="Tick the messages that belong together, then press "
                           "Merge — they show as ONE collapsible conversation. "
                           "Un-merge later from the right-click menu.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 wraplength=680, justify="left", pady=4).pack(fill="x", padx=12)

        holder = tk.Frame(top, bg=C_BG3)
        holder.pack(fill="both", expand=True, padx=12, pady=6)
        canvas = tk.Canvas(holder, bg=C_BG2, highlightthickness=0)
        sb = tk.Scrollbar(holder, orient="vertical", command=canvas.yview)
        inner = tk.Frame(canvas, bg=C_BG2)
        inner.bind("<Configure>",
                   lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
        canvas.create_window((0, 0), window=inner, anchor="nw", width=684)
        canvas.configure(yscrollcommand=sb.set)
        canvas.pack(side="left", fill="both", expand=True)
        sb.pack(side="right", fill="y")
        canvas.bind("<MouseWheel>",
                    lambda e: canvas.yview_scroll(int(-e.delta / 120), "units"))
        inner.bind("<MouseWheel>",
                   lambda e: canvas.yview_scroll(int(-e.delta / 120), "units"))

        base_tid = msg.get("thread_id")
        checks = []
        for m in cands:
            k = _msg_key(m)
            # Pre-check the clicked message + true Gmail-thread members + anything
            # already merged; leave looser (same sender/subject only) matches for
            # the user to opt into.
            pre = ((m is msg)
                   or (base_tid and m.get("thread_id") == base_tid)
                   or (_merge_group_id_for(self._merge_store, k) is not None))
            v = tk.BooleanVar(master=top, value=bool(pre))
            row = tk.Frame(inner, bg=C_BG2)
            row.pack(fill="x", pady=1)
            # Visible check on the dark theme: explicit fg + a light selectcolor
            # so a tick actually shows (Issu 2026-08-02 "kan inte klicka i").
            cb = tk.Checkbutton(row, variable=v, bg=C_BG2, fg=C_FG,
                                selectcolor=C_BG4, activebackground=C_BG2,
                                activeforeground=C_FG, highlightthickness=0,
                                cursor="hand2")
            cb.pack(side="left")
            date = (m.get("_dt", "") or m.get("date", ""))[:16]
            frm  = (m.get("from_name") or m.get("from", ""))[:24]
            subj = m.get("subject", "") or "(no subject)"
            lbl = tk.Label(row, text=f"{date:<16}  {frm:<24}  {subj}",
                           bg=C_BG2, fg=C_FG, font=("Consolas", 9), anchor="w",
                           justify="left", cursor="hand2")
            lbl.pack(side="left", fill="x", expand=True)
            # Click ANYWHERE on the row toggles the tick — the bare checkbox was
            # a tiny target and easy to miss (Issu 2026-08-02).
            def _toggle(_e=None, vv=v):
                vv.set(not vv.get())
            for w in (row, lbl):
                w.bind("<Button-1>", _toggle)
                w.bind("<MouseWheel>",
                       lambda e: canvas.yview_scroll(int(-e.delta / 120),
                                                     "units"))
            checks.append((v, k))

        def _set_all(val):
            for v, _k in checks:
                v.set(val)

        brow = tk.Frame(top, bg=C_BG3)
        brow.pack(fill="x", padx=12, pady=(0, 10))

        def _do(select_all_first=False):
            if select_all_first:
                _set_all(True)
            keys = [k for v, k in checks if v.get()]
            if self._do_merge(keys):
                top.destroy()
        # Select all / none — pick 5 of 7 fast: Select all, then untick two
        # (Issu 2026-08-02). "Merge all" is the one-click select-all-and-merge.
        tk.Button(brow, text="☑ Select all", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=10, pady=4,
                  command=lambda: _set_all(True)).pack(side="left", padx=4)
        tk.Button(brow, text="☐ Select none", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=10, pady=4,
                  command=lambda: _set_all(False)).pack(side="left", padx=4)
        tk.Button(brow, text="Merge selected", bg=C_BTN_NEW, fg=C_BTN_FG,
                  font=("Segoe UI", 9, "bold"), relief="flat", cursor="hand2",
                  padx=12, pady=4,
                  command=lambda: _do()).pack(side="left", padx=(16, 4))
        tk.Button(brow, text="Merge all", bg=C_BTN_NEW, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=12, pady=4,
                  command=lambda: _do(select_all_first=True)).pack(side="left",
                                                                   padx=4)
        tk.Button(brow, text="Cancel", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=12, pady=4, command=top.destroy).pack(side="right", padx=4)

    def _render_msg_list(self):
        # Which messages carry a live follow-up — looked up once per render
        # rather than per row (DEL 04j).
        self._followup_keys = _followup_active_keys(self._followup_store)
        self._apply_float_flags(self._messages)
        # The header is now a separate frozen frame, so the data-row frame
        # holds ONLY rows — clear them all.
        for w in self.ml_inner.winfo_children():
            w.destroy()
        self._row_frames = []

        # Re-apply shared column geometry (in case ml_inner was recreated)
        for _text, col, minsize, weight in _MSG_COLUMNS:
            self.ml_inner.columnconfigure(col, weight=weight, minsize=minsize)

        self._grid_row = 0   # data rows start at the top of the scroll frame

        # ── A tick can never outlive its row (Issu 2026-09-20) ───────────────
        # _selected_ids holds ids, not objects, so an id whose message has left
        # the list would otherwise keep counting towards "N selected" for ever —
        # and, worse, could light up an unrelated row: an id IS a per-folder
        # IMAP UID, and every folder has a message number 42.
        if self._selected_ids:
            _live = {m.get("id") for m in (self._messages or [])}
            if not self._selected_ids <= _live:
                self._selected_ids &= _live

        if not self._messages:
            self._update_bulk_bar()
            # "No messages in this folder." was said even while the folder was
            # still being fetched, which is simply untrue — and it is what made
            # Issu's Frakt folder look empty before its mail appeared
            # (2026-08-08). Tell the two states apart.
            loading = bool(getattr(self, "_fetch_token", None) is not None
                           and getattr(self, "_fetch_in_flight", False))
            tk.Label(self.ml_inner,
                     text=("⏳  Fetching this folder…  (nothing is cached "
                           "locally yet, so it has to come from the server "
                           "first — it will appear here in a moment)"
                           if loading else "No messages in this folder."),
                     bg=C_BG2, fg=(C_ACCENT if loading else C_FG_DIM),
                     font=("Segoe UI", 9, "italic"), pady=20,
                     wraplength=620, justify="left").grid(
                         row=0, column=0, columnspan=len(_MSG_COLUMNS), sticky="w")
            return

        # ── Group into threads ───────────────────────────────────────────────
        #
        # THREADED (the default) shows ONE row per conversation: the newest
        # message in it, with a count, and a + to open the rest indented
        # underneath.
        #
        # This used to give every message its own top-level row AND re-render
        # the siblings when you expanded one — so a three-message thread
        # appeared three times in the list, and five times once expanded. The
        # interleaved "Project Phoenix" thread in the demo data (ids 40/41/42)
        # is there precisely to make that visible.
        #
        # FLAT (View → Threaded view, off) is the honest alternative: one row
        # per message, no twisty, nothing hidden.
        # Anything sitting in the delete-limbo stays out of the list however
        # it got back into _messages — a reload during the undo window used to
        # resurrect it, and an expanded conversation would have shown it even
        # if the lead row did not (DEL 09k). Filtered BEFORE the threads are
        # grouped, so it cannot come back as a thread member either.
        pending = self._pending_delete_keys
        live = ([m for m in self._messages if _msg_key(m) not in pending]
                if pending else list(self._messages))
        # Floating follow-ups ride at the top, whatever the sort order is
        # (stable: the rest keeps its order).
        if any(m.get("_float") for m in live):
            live = ([m for m in live if m.get("_float")]
                    + [m for m in live if not m.get("_float")])

        threads = {}
        for m in live:
            tid = self._effective_tid(m)
            threads.setdefault(tid, []).append(m)

        # Quick filters narrow what is DRAWN without touching _messages, so
        # clearing a toggle brings everything straight back (DEL 09e).
        shown = [m for m in live if self._passes_quick(m)]
        try:
            self._quick_count.configure(
                text=(f"{len(shown)} of {len(live)}"
                      if any(self._quick.values()) else ""))
        except Exception:
            pass

        if not self.cfg.get("thread_view", False):
            for msg in shown:
                self._render_one_row(msg, has_thread=False, indent=False)
        else:
            rendered = set()
            for msg in shown:
                tid = self._effective_tid(msg)
                if tid in rendered:
                    continue          # this conversation already has its row
                rendered.add(tid)
                members = threads.get(tid, [msg])
                # The lead row is the NEWEST message — what the conversation
                # currently says. Note this is not necessarily `msg`: the
                # sorted list may reach an older member of the thread first.
                lead = max(members, key=_thread_order)
                self._render_one_row(lead, has_thread=len(members) > 1,
                                     indent=False,
                                     thread_count=len(members),
                                     thread_id=tid)
                if len(members) > 1 and tid in self._expanded_rows:
                    others = sorted((m for m in members if m is not lead),
                                    key=_thread_order)
                    for m in others:
                        self._render_one_row(m, has_thread=False, indent=True)

        # ── "Load more" row — only in real mode, not while searching, and
        #    only when the folder likely has older messages (we received at
        #    least a full page). Fetches the next page of older mail.
        if (not self._demo_mode and not getattr(self, "_search_active", False)
                and len(self._messages) >= self._fetch_limit):
            more = tk.Label(self.ml_inner,
                            text=f"⬇  Load {FETCH_LIMIT} older messages",
                            bg=C_BG1, fg=C_ACCENT, font=("Segoe UI", 9, "bold"),
                            anchor="center", pady=8, cursor="hand2")
            more.grid(row=self._grid_row, column=0,
                      columnspan=len(_MSG_COLUMNS), sticky="ew")
            more.bind("<Button-1>", lambda e: self._load_more())
            more.bind("<Enter>", lambda e: more.configure(bg=C_BG4))
            more.bind("<Leave>", lambda e: more.configure(bg=C_BG1))
            self._grid_row += 1

        # ── Paint the ticks back on (Issu 2026-09-20) ────────────────────────
        # "jag kan markera ett mail... och så blir den klar och mailet är inte
        # längre markerat." _render_one_row colours a row from its read/unread
        # shade ALONE — it knows nothing about the selection — so every full
        # redraw (an auto-check finishing, a filter run, a quick-filter toggle,
        # a thread being opened) drew the whole list unselected. The tick was
        # still in _selected_ids the entire time; only the colour had gone,
        # which from where you are sitting is the same thing as losing it.
        #
        # Doing it HERE, once, at the end of the one function that draws rows,
        # is what makes it impossible for a future caller to forget — several
        # already did.
        self._repaint_selection()
        self._update_bulk_bar()

    def _row_bg(self, msg):
        """The background colour of one list row: the read/unread shade, unless
        a filter colour or a hand-applied tag overrides it. Kept in one place so
        an in-place read-state repaint matches a full render exactly (DEL 04v)."""
        bg = C_MSG_UNRD if msg.get("unread") else C_MSG_READ
        if msg.get("_filter_color"):
            bg = msg["_filter_color"]
        tag_color = _tag_row_color(self._tag_store, msg)
        if tag_color:
            bg = tag_color
        return bg

    def _subject_text(self, msg, indent, thread_count):
        """The Subject-column text (unread dot, bell, tag marks, thread count).
        Shared by render and by the in-place read repaint."""
        dot = "● " if msg.get("unread") else "   "
        if (not msg.get("_followup")
                and _msg_key(msg) in getattr(self, "_followup_keys", ())):
            dot = "🔔 " + dot.strip() + " " if msg.get("unread") else "🔔  "
        marks = _tag_marks(self._tag_store, msg)
        if marks:
            dot = marks + " " + dot
        # DEL 09p: the padlock goes in FRONT of everything else. Its whole job
        # is to be seen before you tick the row, not after you press Delete.
        if self._is_protected_message(msg):
            dot = "🔒 " + dot
        prefix = "      ↳ " if indent else ""
        count = f"   ({thread_count})" if thread_count > 1 else ""
        # DEL 09m: three Tradera receipts arrived two minutes apart with the
        # same subject to the letter, from the same sender, each with a QR
        # code called QrCode-<number>.png. The subject was worth nothing on
        # such a row, so it gives way to what tells them apart: the town (or
        # the country, when it leaves Sweden) and the title of the game.
        # Display only — search, filters and rules still see the real subject.
        tag = _ship_row_tag(self._ship_facts(msg))
        if tag:
            return f"{prefix}{dot}📦 {tag}{count}"
        return f"{prefix}{dot}{msg['subject']}{count}"

    def _render_one_row(self, msg, has_thread, indent, thread_count=0,
                        thread_id=None):
        """Add one message row directly into ml_inner's shared grid.

        Because header (ml_hdr) and all data rows (ml_inner) use identical
        columnconfigure() calls, columns are naturally aligned without any
        per-row Frame that would reset the grid geometry.
        """
        # A flagged "always unread" sender stays unread while in an Inbox, even
        # if it was clicked earlier this session (Issu's request).
        if msg.get("_always_unread"):
            msg["unread"] = True
        bg        = self._row_bg(msg)
        from_font = ("Segoe UI", 9, "bold") if msg.get("unread") else ("Segoe UI", 9)
        from_fg   = C_FG_UNRD  if msg.get("unread") else C_FG
        gr        = self._grid_row   # current grid row index

        # A collapsed conversation row stands for its whole thread, so both the
        # 📎 and the ✉ show GREY when only a DEEPER message carries the thing —
        # "grått om det finns i tråden men inte i översta" (Issu 2026-09-23).
        # Computed once here and shared by the two icon cells below. Only a
        # collapsed LEAD hides members, so the (O(n)) member scan is skipped for
        # ordinary and expanded-child rows — it never runs per plain message.
        thread_members = (self._collapsed_thread_members(msg)
                          if (has_thread and not indent) else None)

        # ── Col 0 — Attachment icon (grey when only elsewhere in the thread) ──
        if msg.get("attachments"):
            attach_txt, attach_fg = "📎", C_FG_DIM          # colour emoji as before
        elif thread_members and any(m is not msg and m.get("attachments")
                                    for m in thread_members):
            attach_txt, attach_fg = "📎︎", C_FG_DIM     # mono = ghost/grey
        else:
            attach_txt, attach_fg = "", C_FG_DIM
        tk.Label(self.ml_inner, text=attach_txt, bg=bg, fg=attach_fg,
                 font=("Segoe UI", 9), anchor="w", padx=4,
                 cursor="hand2").grid(row=gr, column=0, sticky="ew", pady=4)

        # ── Col 1 — Address-mail envelope (manual mark) ──────────────────────
        # Green when THIS message is marked; grey when only a deeper message in
        # the conversation is; empty otherwise. Click = the address popup (or a
        # normal row-select on an empty cell) — see _address_cell_click.
        # "✉︎" forces the MONOCHROME text glyph, so the green/grey fg is
        # honoured — the bare emoji form would ignore fg and lose the grammar.
        if _addr_is_marked(self._address_store, msg):
            env_txt, env_fg = "✉︎", C_ADDR
        elif thread_members and any(m is not msg
                                    and _addr_is_marked(self._address_store, m)
                                    for m in thread_members):
            env_txt, env_fg = "✉︎", C_FG_DIM
        else:
            env_txt, env_fg = "", C_FG_DIM
        env_lbl = tk.Label(self.ml_inner, text=env_txt, bg=bg, fg=env_fg,
                           font=("Segoe UI", 9), anchor="w", padx=4,
                           cursor="hand2")
        env_lbl.grid(row=gr, column=1, sticky="ew")
        env_lbl.bind("<Button-1>", lambda e, m=msg: self._address_cell_click(e, m))

        # ── Col 2 — Star ─────────────────────────────────────────────────────
        star_fg = "#f5c518" if msg.get("starred") else C_FG_DIM
        tk.Label(self.ml_inner, text="★", bg=bg, fg=star_fg,
                 font=("Segoe UI", 10), cursor="hand2",
                 anchor="w", padx=4).grid(row=gr, column=2, sticky="ew")

        # ── Col 3 — Subject ───────────────────────────────────────────────────
        # The Subject text (unread dot, bell, tag marks, thread count) — built
        # by a shared helper so an in-place read repaint can reproduce it.
        subj_lbl = tk.Label(self.ml_inner,
                 text=self._subject_text(msg, indent, thread_count), bg=bg,
                 fg=from_fg, font=from_font, anchor="w",
                 cursor="hand2")
        subj_lbl.grid(row=gr, column=3, sticky="ew", padx=(2, 4))

        # ── Col 4 — Thread expand/collapse toggle ─────────────────────────────
        # Keyed on the THREAD id, not the message id: the row stands for the
        # whole conversation, and which message leads it can change as new
        # mail arrives.
        tid = thread_id if thread_id is not None else self._effective_tid(msg)
        if has_thread and not indent:
            sign = "−" if tid in self._expanded_rows else "+"
            lbl_toggle = tk.Label(self.ml_inner, text=sign, bg=bg, fg=C_ACCENT,
                                  font=("Segoe UI", 10, "bold"),
                                  cursor="hand2", anchor="w", padx=4)
            lbl_toggle.grid(row=gr, column=4, sticky="ew")
            lbl_toggle.bind("<Button-1>",
                            lambda e, i=tid: self._toggle_thread_row(i))
        else:
            tk.Label(self.ml_inner, text="", bg=bg, anchor="w",
                     cursor="hand2").grid(row=gr, column=4, sticky="ew")

        # ── Col 5 — Correspondent (tinted if the sender has a contact colour) ─
        corr_txt = msg["from_name"]
        # ── The real address, so a dressed-up display name is visible ────────
        # "Kundservice Elgiganten" can be anyone. With this on, the address
        # that actually sent it is shown next to the name. And whenever the
        # NAME itself contains a different e-mail address — the oldest trick
        # there is — the real one is shown regardless of the setting, because
        # that case is not a preference, it is a warning.
        real = (msg.get("from") or "").strip()
        name_has_addr = _re.search(r'[\w.+-]+@[\w.-]+\.\w+', corr_txt or "")
        forged = bool(name_has_addr and real
                      and name_has_addr.group(0).lower() != real.lower())
        # Brand/domain impersonation ("Amazon.se" sent from a scam address) is
        # a warning too, not a preference — flag it in the list regardless of
        # the show-real-address toggle, at the chosen sensitivity.
        brand_forged = bool(_brand_impersonation_warning(
            msg, self.cfg.get("phish_brand_level", "balanced")))
        forged = forged or brand_forged
        if real and (self.cfg.get("show_real_address", False) or forged):
            if real.lower() not in (corr_txt or "").lower():
                corr_txt = f"{corr_txt}  <{real}>" if corr_txt else real
        if forged:
            corr_txt = "⚠ " + corr_txt
        if self._current_acct == ALL_ACCOUNTS_ID and msg.get("account_email"):
            corr_txt += f"  ⟶{msg['account_email'].split('@')[0]}"
        # Colour priority: a per-sender contact colour is the most specific, so
        # it wins; otherwise, in the All Accounts view, tint the whole cell in
        # the OWNING account's colour so you can see at a glance where a message
        # landed (DEL 09c).
        contact_col = self._contact_color(msg)
        acct_col    = self._acct_colors.get(msg.get("account_email", ""))
        # corr_mode records which colours drive this cell, so a read repaint
        # knows what it may touch: "contact" = leave alone (fixed by sender),
        # "acct" = un-bold but keep the account colour, "plain" = follows the
        # read/unread shade like the subject.
        if contact_col:
            corr_txt = "● " + corr_txt        # leading dot makes it pop
            corr_fg  = contact_col
            corr_font = ("Segoe UI", 9, "bold")
            corr_mode = "contact"
        elif self._current_acct == ALL_ACCOUNTS_ID and acct_col:
            corr_fg   = acct_col
            corr_font = from_font
            corr_mode = "acct"
        else:
            corr_fg, corr_font = from_fg, from_font
            corr_mode = "plain"
        # fg (not bg) carries the colour, so it survives row hover/selection
        # which only change the background.
        corr_lbl = tk.Label(self.ml_inner, text=corr_txt, bg=bg, fg=corr_fg,
                 font=corr_font, anchor="w", cursor="hand2")
        corr_lbl.grid(row=gr, column=5, sticky="ew", padx=(2, 4))

        # ── Col 6 — Priority ──────────────────────────────────────────────────
        prio     = msg.get("priority", "normal")
        prio_txt = {"high": "🔴", "low": "🔵"}.get(prio, "")
        tk.Label(self.ml_inner, text=prio_txt, bg=bg, fg=C_FG_DIM,
                 font=("Segoe UI", 8), anchor="w", padx=4,
                 cursor="hand2").grid(row=gr, column=6, sticky="ew")

        # ── Col 7 — Spam marker ───────────────────────────────────────────────
        spam_txt = "⚠" if msg.get("spam") else ""
        tk.Label(self.ml_inner, text=spam_txt, bg=bg, fg="#e0a030",
                 font=("Segoe UI", 9), anchor="w", padx=4,
                 cursor="hand2").grid(row=gr, column=7, sticky="ew")

        # ── Col 8 — Date ──────────────────────────────────────────────────────
        date_lbl = tk.Label(self.ml_inner, text=msg["date"], bg=bg, fg=C_FG_DIM,
                            font=("Segoe UI", 8), anchor="w", cursor="hand2")
        date_lbl.grid(row=gr, column=8, sticky="ew", padx=(0, 8))

        # Collect all label widgets that belong to this row
        # (all cells just placed into grid row gr)
        row_widgets = [w for w in self.ml_inner.grid_slaves(row=gr)]

        # ── Separator line ────────────────────────────────────────────────────
        sep_gr = gr + 1
        tk.Frame(self.ml_inner, bg=C_SEP, height=1).grid(
            row=sep_gr, column=0, columnspan=len(_MSG_COLUMNS), sticky="ew")

        self._grid_row += 2   # advance past data-row + separator

        # ── Click handler ─────────────────────────────────────────────────────
        def _row_click(e, m=msg, rw=row_widgets):
            # Ctrl = add/remove one, Shift = add a run, plain = just this one.
            # event.state bit 0x0004 is Control, 0x0001 is Shift on every
            # platform Tk supports.
            ctrl  = bool(getattr(e, "state", 0) & 0x0004)
            shift = bool(getattr(e, "state", 0) & 0x0001)
            self._select_msg(m, rw, ctrl=ctrl, shift=shift)
        for w in row_widgets:
            col_num = int(w.grid_info().get("column", -1))
            # Skip the "+" toggle (col 4) and the ✉ envelope (col 1) — each owns
            # a Button-1 handler of its own and must not also select the row.
            if col_num not in (1, 4):
                w.bind("<Button-1>", _row_click)

        # ── Right-click menu (mark read/unread, star, spam, snooze, delete…) ──
        def _row_rclick(e, m=msg):
            self._msg_context_menu(e, m)
        for w in row_widgets:
            w.bind("<Button-3>", _row_rclick)

        # ── Hover ─────────────────────────────────────────────────────────────
        # A SELECTED row (part of a multi-selection, not just the last-clicked
        # one) must keep its selection colour on hover-out — otherwise ticked
        # rows looked deselected the moment the mouse left them.
        # A MUTABLE row entry: entry[2] (the base bg) is updated in place when a
        # message flips read↔unread, so hover and selection always use the
        # current colour without a full list rebuild (which is the "flash").
        row_entry = [msg, row_widgets, bg,
                     {"indent": indent, "thread_count": thread_count,
                      "subj": subj_lbl, "corr": corr_lbl,
                      "corr_mode": corr_mode}]

        def _on_enter(e, m=msg, rw=row_widgets):
            if m.get("id") not in self._selected_ids:
                for w in rw:
                    try: w.configure(bg=C_BG4)
                    except Exception: pass
        def _on_leave(e, m=msg, rw=row_widgets, ent=row_entry):
            col = C_MSG_SEL if m.get("id") in self._selected_ids else ent[2]
            for w in rw:
                try: w.configure(bg=col)
                except Exception: pass
        for w in row_widgets:
            w.bind("<Enter>", _on_enter)
            w.bind("<Leave>", _on_leave)

        # Hover the date cell → the exact time, without clicking anything and
        # without changing the selection (Issu 2026-08-29). Bound LAST on
        # purpose: add_tooltip chains with add="+", but the row's own hover and
        # click handlers above are plain replacing binds, so a tooltip attached
        # any earlier would simply have been thrown away.
        # A right-click anywhere on the row gets it as a menu line as well —
        # see _msg_context_menu — for when a bubble that vanishes is not enough
        # to read a full timestamp off.
        add_tooltip(date_lbl, _exact_time(msg), delay=600)

        self._row_frames.append(row_entry)

    def _on_thread_view_changed(self):
        self.cfg["thread_view"] = bool(self._thread_view_var.get())
        self._expanded_rows = set()
        self._render_msg_list()
        self._flash("Threaded view on" if self.cfg["thread_view"]
                    else "Threaded view off")

    def _on_compact_changed(self):
        self.cfg["compact_folders"] = bool(self._compact_var.get())
        _save_settings(self.cfg)
        self._populate_sidebar(self.sidebar_inner)
        self._flash("Compact folders on" if self.cfg["compact_folders"]
                    else "Compact folders off")

    def _on_merge_dup_changed(self):
        self.cfg["merge_duplicate_folders"] = bool(self._merge_dup_var.get())
        _save_settings(self.cfg)
        self._populate_sidebar(self.sidebar_inner)
        self._flash("Duplicate folders merged" if self.cfg["merge_duplicate_folders"]
                    else "Showing all folders")

    def _expand_all(self, expand):
        """Open or close every conversation that has more than one message."""
        if expand:
            counts = {}
            for m in self._messages:
                tid = self._effective_tid(m)
                counts[tid] = counts.get(tid, 0) + 1
            self._expanded_rows = {t for t, n in counts.items() if n > 1}
        else:
            self._expanded_rows = set()
        self._render_msg_list()

    def _toggle_thread_row(self, thread_id):
        """Open or close one conversation. The set holds THREAD ids."""
        if thread_id in self._expanded_rows:
            self._expanded_rows.discard(thread_id)
        else:
            self._expanded_rows.add(thread_id)
        self._render_msg_list()
        # Re-apply selection highlight if the selected message is still visible
        if self._selected_msg is not None:
            for entry in self._row_frames:
                m, rw = entry[0], entry[1]
                if m is self._selected_msg:
                    for w in rw:
                        try: w.configure(bg=C_MSG_SEL)
                        except Exception: pass

    # ==========================================================================
    # DEL 09e — MULTI-SELECT, QUICK FILTERS, BULK ACTIONS, UNDO
    # ==========================================================================

    def _show_message_source(self, msg=None):
        """Ctrl+U — the raw message, headers and all.

        This is the honest answer to "who really sent this": the headers
        cannot be dressed up the way a display name can."""
        msg = msg or self._selected_msg
        if not msg:
            messagebox.showinfo("Message source", "Select a message first.",
                                parent=self.root)
            return
        raw = msg.get("_raw")
        if raw:
            try:
                text = raw.decode("utf-8", "replace")
            except Exception:
                text = str(raw)
        else:
            # No original bytes (demo data, a note, or an older fetch) —
            # show what is known rather than an empty window, and say so.
            text = ("(The original source is not available for this message.\n"
                    " What follows is what F(re)email holds.)\n\n"
                    f"From: {msg.get('from_name','')} <{msg.get('from','')}>\n"
                    f"Reply-To: {msg.get('_reply_to_hdr','')}\n"
                    f"To: {msg.get('_to_hdr','')}\n"
                    f"Subject: {msg.get('subject','')}\n"
                    f"Date: {msg.get('date','')}\n"
                    f"Message-ID: {msg.get('_message_id','')}\n"
                    f"Authentication-Results: {msg.get('_auth_results','')}\n"
                    f"List-Unsubscribe: {msg.get('_list_unsub','')}\n"
                    f"Gmail labels: {', '.join(msg.get('_labels') or [])}\n"
                    f"\n{'-' * 60}\n\n{msg.get('body','')}")

        top = self._dialog_shell("Message source", 820, 620)
        frm = tk.Frame(top, bg=C_BG2)
        frm.pack(fill="both", expand=True, padx=8, pady=6)
        sb = tk.Scrollbar(frm, bg=C_BG3, troughcolor=C_BG1)
        sb.pack(side="right", fill="y")
        t = tk.Text(frm, bg=C_BG2, fg=C_FG, relief="flat",
                    font=("Consolas", 9), wrap="none", yscrollcommand=sb.set,
                    padx=8, pady=6, insertofftime=0, insertontime=9999999)
        no_blink(t)
        sb.configure(command=t.yview)
        sbx = tk.Scrollbar(top, orient="horizontal", command=t.xview,
                           bg=C_BG3, troughcolor=C_BG1)
        sbx.pack(fill="x", padx=8)
        t.configure(xscrollcommand=sbx.set)
        t.pack(fill="both", expand=True)
        t.insert("1.0", text)

        # Highlight the headers that matter when judging a sender.
        t.tag_configure("hdr", foreground=C_ACCENT)
        for name in ("From:", "Reply-To:", "Return-Path:", "Message-ID:",
                     "Authentication-Results:", "Received-SPF:",
                     "DKIM-Signature:", "List-Unsubscribe:"):
            start = "1.0"
            while True:
                pos = t.search(f"\n{name}", start, stopindex="end")
                if not pos:
                    break
                line_end = f"{pos}+1line lineend"
                t.tag_add("hdr", f"{pos}+1c", line_end)
                start = line_end
        t.configure(state="disabled")
        _bind_mousewheel(t, None)

        tk.Button(top, text="Copy to clipboard", bg=C_BTN_STD, fg=C_BTN_FG,
                  relief="flat", padx=14, pady=4,
                  command=lambda: (self.root.clipboard_clear(),
                                   self.root.clipboard_append(text),
                                   self._flash("Copied"))).pack(pady=6)

    def _toggle_real_address(self):
        """Show every sender's real address in the list, next to the name."""
        self.cfg["show_real_address"] = bool(self._real_addr_var.get())
        _save_settings(self.cfg)
        self._render_msg_list()
        self._flash("Real sender address shown" if self.cfg["show_real_address"]
                    else "Sender name only")

    def _on_phish_level_changed(self):
        """Change how hard the fake-sender (brand-impersonation) check tries.

        The per-message scan caches its result on the message, so drop those
        caches and redraw, giving the new sensitivity an immediate effect."""
        self.cfg["phish_brand_level"] = self._phish_level_var.get()
        _save_settings(self.cfg)
        for m in getattr(self, "_all_messages", []) or []:
            m.pop("_phish", None)
        for m in getattr(self, "_messages", []) or []:
            m.pop("_phish", None)
        self._render_msg_list()
        # Re-open the current message so its banner reflects the new setting.
        if self._selected_msg is not None:
            self._show_message_in_reading_pane(self._selected_msg)
        labels = {"off": "off", "domain": "domain-in-name only",
                  "balanced": "balanced", "aggressive": "aggressive"}
        self._flash(f"Fake-sender warnings: {labels.get(self.cfg['phish_brand_level'], '')}")

    def _update_bulk_bar(self):
        """Show the bulk bar only when it has something to act on."""
        n = len(self._selected_ids)
        try:
            if n > 1:
                self._bulk_lbl.configure(text=f"{n} selected")
                if not self.bulk_bar.winfo_ismapped():
                    self.bulk_bar.pack(fill="x", after=self.lbl_folder)
            else:
                if self.bulk_bar.winfo_ismapped():
                    self.bulk_bar.pack_forget()
        except Exception as e:
            log.debug("bulk bar: %s", e)

    # ── Quick filters ─────────────────────────────────────────────────────────
    def _scroll_msg_list_top(self):
        """Jump the message list back to the very top. Used whenever the visible
        set changes from a SHOW/quick-filter toggle, so the now-relevant
        messages at the top aren't left hidden above the old scroll position
        (Issu: clicking Unread kept the old position, forcing a scroll up)."""
        try:
            self.ml_canvas.update_idletasks()      # let the new scrollregion settle
            self.ml_canvas.yview_moveto(0.0)
        except Exception:
            pass

    def _toggle_quick(self, key):
        self._quick[key] = not self._quick[key]
        b = self._quick_btns.get(key)
        if b is not None:
            on = self._quick[key]
            b.configure(bg=C_ACCENT2 if on else C_BTN_STD,
                        fg=C_FG_UNRD if on else C_FG_DIM)
        self._render_msg_list()
        # Switching a SHOW filter changes what's visible → go to the top so the
        # first matches are in view instead of staying scrolled down.
        self._scroll_msg_list_top()

    def _passes_quick(self, msg) -> bool:
        """Does one message survive the pressed quick filters? Several
        pressed at once mean ALL of them must match — that is what makes
        "unread + has files" useful."""
        q = self._quick
        if not any(q.values()):
            return True
        if q["unread"] and not msg.get("unread"):
            return False
        if q["starred"] and not msg.get("starred"):
            return False
        if q["attach"] and not msg.get("attachments"):
            return False
        if q["tagged"] and not _tags_of(self._tag_store, msg):
            return False
        if q["followup"] and _msg_key(msg) not in self._followup_keys:
            return False
        return True

    # ── Bulk actions ──────────────────────────────────────────────────────────
    def _bulk_make_junk_filter(self):
        """Build ONE "any of the following" filter from the selected senders, so
        their mail is cleared automatically from now on (Issu 2026-08-01:
        getting rid of a bunch of junk, doing more than a one-off Delete).

        You choose what the rule does — move to Trash on Gmail, just hide from
        the list, and/or mark read — and it is added to your filters and can be
        run immediately over what is loaded."""
        msgs = self._selected_messages()
        if not msgs:
            return
        # Unique sender addresses among the selection.
        senders = []
        seen = set()
        for m in msgs:
            addr = (parseaddr(m.get("from", ""))[1] or m.get("from", "")).strip()
            if addr and addr.lower() not in seen:
                seen.add(addr.lower())
                senders.append(addr)
        if not senders:
            self._flash("No sender addresses in the selection")
            return

        top = tk.Toplevel(self.root)
        top.title("Junk filter from senders — F(re)email")
        top.configure(bg=C_BG3)
        # Wide enough for the four action buttons on one row (the whole-mailbox
        # one has a long label on purpose — it is the one that does the most).
        _center_over(top, self.root, 660, 440)
        top.transient(self.root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())

        tk.Label(top, text="🚫  Filter these senders", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(pady=(12, 2))
        tk.Label(top, text=f"One rule (Match: ANY) for {len(senders)} sender(s). "
                           f"It will act on every message from them.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8),
                 wraplength=600, justify="center").pack(pady=(0, 6))

        # The list of senders (read-only, scrollable).
        lwrap = tk.Frame(top, bg=C_BG2)
        lwrap.pack(fill="both", expand=True, padx=16, pady=(0, 6))
        sb = tk.Scrollbar(lwrap, bg=C_BG3, troughcolor=C_BG1)
        sb.pack(side="right", fill="y")
        lst = tk.Listbox(lwrap, bg=C_BG2, fg=C_FG, highlightthickness=0,
                         relief="flat", activestyle="none", font=("Segoe UI", 9),
                         yscrollcommand=sb.set, exportselection=False)
        sb.configure(command=lst.yview)
        lst.pack(side="left", fill="both", expand=True)
        for s in senders:
            lst.insert("end", f"  {s}")

        # What the rule does.
        act = tk.Frame(top, bg=C_BG3); act.pack(fill="x", padx=16, pady=(2, 0))
        v_trash = tk.BooleanVar(value=True)
        v_hide  = tk.BooleanVar(value=False)
        v_read  = tk.BooleanVar(value=True)
        tk.Checkbutton(act, text="Move to Gmail Trash  (needs Server changes on)",
                       variable=v_trash, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9), highlightthickness=0,
                       anchor="w").pack(fill="x")
        tk.Checkbutton(act, text="Hide from the message list",
                       variable=v_hide, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9), highlightthickness=0,
                       anchor="w").pack(fill="x")
        tk.Checkbutton(act, text="Mark as read",
                       variable=v_read, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9), highlightthickness=0,
                       anchor="w").pack(fill="x")

        def _create(then="run"):
            """then: "run" (loaded mail) / "sweep" (whole mailbox) / "" (just
            create the rule)."""
            # Every sender goes in the EITHER/OR section: mail from any one of
            # them is junk, and requiring all of them at once would match
            # nothing at all.
            conds = [{"field": "from", "op": "contains", "value": s,
                      "group": "any"} for s in senders]
            rec = dict(_FILTER_DEFAULTS,
                       id=_new_id(),
                       name=f"Junk: {senders[0]}" +
                            (f" +{len(senders)-1}" if len(senders) > 1 else ""),
                       enabled=True, conditions=conds, match_mode="groups",
                       action_trash=bool(v_trash.get()),
                       action_hide=bool(v_hide.get()),
                       action_read=bool(v_read.get()))
            if not (v_trash.get() or v_hide.get() or v_read.get()):
                messagebox.showinfo("Junk filter",
                                    "Tick at least one action.", parent=top)
                return
            self._filter_store.setdefault("filters", []).append(rec)
            _save_filters(self._filter_store)
            top.destroy()
            self._flash("Junk filter created")
            if then == "run":
                self._run_filters_now()
            elif then == "sweep":
                # Straight on to the whole-mailbox clean-out, which is what
                # "get rid of ALL of this sender's mail" actually means.
                self._sweep_dialog()

        br = tk.Frame(top, bg=C_BG3); br.pack(pady=10)
        b_now = tk.Button(br, text="Create & run now", bg=C_BTN_NEW, fg=C_BTN_FG,
                          font=("Segoe UI", 9, "bold"), relief="flat",
                          cursor="hand2", padx=12, pady=4,
                          command=lambda: _create("run"))
        b_now.pack(side="left", padx=4)
        add_tooltip(b_now, "Applies the new rule to the messages currently "
                           "loaded in this folder.")
        b_all = tk.Button(br, text="🧹 Create & clean whole mailbox…",
                          bg="#8a5a2a", fg=C_BTN_FG, font=("Segoe UI", 9),
                          relief="flat", cursor="hand2", padx=12, pady=4,
                          command=lambda: _create("sweep"))
        b_all.pack(side="left", padx=4)
        add_tooltip(b_all, "Creates the rule and then opens the whole-mailbox "
                           "clean-out: every message these senders ever sent, "
                           "not just the loaded ones.")
        tk.Button(br, text="Create only", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=12, pady=4, command=lambda: _create("")).pack(
                      side="left", padx=4)
        tk.Button(br, text="Cancel", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=12, pady=4, command=top.destroy).pack(side="left", padx=4)

    def _bulk_tag(self):
        msgs = self._selected_for_action()
        if not msgs:
            return
        m = tk.Menu(self.root, tearoff=0, bg=C_BG2, fg=C_FG,
                    activebackground=C_BG4, activeforeground=C_FG)
        for tag in self._tag_store.get("tags", []):
            m.add_command(
                label=f"{tag.get('icon','●')}  {tag['name']}",
                command=lambda t=tag, ms=msgs: self._bulk_apply_tag(ms, t))
        try:
            m.tk_popup(self.root.winfo_pointerx(), self.root.winfo_pointery())
        finally:
            m.grab_release()

    def _bulk_apply_tag(self, msgs, tag):
        """Add the tag to every selected message that does not have it —
        deliberately not a toggle, because a mixed selection would otherwise
        do two different things at once."""
        n = 0
        for msg in msgs:
            have = {t["id"] for t in _tags_of(self._tag_store, msg)}
            if tag["id"] not in have:
                _tag_toggle(self._tag_store, msg, tag["id"])
                n += 1
        self._flash(f"{tag['icon']} {tag['name']} added to {n} message(s)")
        self._render_msg_list()
        self._repaint_selection()

    def _bulk_mark_read(self):
        msgs = self._selected_for_action()
        for msg in msgs:
            msg["unread"] = False
        self._flash(f"{len(msgs)} marked as read (in this program)")
        self._render_msg_list()
        self._repaint_selection()

    def _bulk_to_notes(self):
        msgs = self._selected_for_action()
        if not msgs or not messagebox.askyesno(
                "Save to Notes",
                f"Save {len(msgs)} message(s) to your Notes folder?\n\n"
                f"Copies are written to disk; the originals are untouched.",
                parent=self.root):
            return
        n = 0
        for msg in msgs:
            try:
                self._save_message_as_note(msg)
                n += 1
            except Exception as e:
                log.warning("bulk note failed: %s", e)
        self._flash(f"{n} saved to Notes")

    def _bulk_move(self):
        """Move the ticked messages to a folder/label of your choice.

        Gmail's IMAP has no drag-and-drop and its labels are not real folders,
        so tick-then-Move is the way (Issu 2026-08-03). Reuses _move_messages,
        which opens the collapsible-tree picker and does the batched UID MOVE —
        the same path a filter's "move to folder" takes."""
        msgs = self._selected_messages()
        if not msgs:
            return
        self._move_messages(msgs)

    def _bulk_archive(self):
        msgs = self._selected_for_action()
        if not msgs:
            return
        n = _archive_run(self.cfg, msgs)
        messagebox.showinfo(
            "Archive",
            f"{n} new message(s) archived to:\n\n{_archive_dir(self.cfg)}"
            + (f"\n\n{len(msgs) - n} were already there." if n < len(msgs)
               else ""), parent=self.root)

    def _bulk_delete(self):
        """Delete several at once — the thing that made one-at-a-time slow.

        Follows exactly the same rules as deleting one: local hide unless
        server changes are switched on, and then a confirmation naming what
        goes. A collapsed conversation goes whole (Issu 2026-09-01)."""
        msgs = self._selected_for_action()
        if not msgs:
            return
        # In the Deleted archive, "delete" removes the saved LOCAL copies.
        if self._current_folder == "Deleted":
            self._remove_deleted_batch(msgs)
            return
        # Deleting from the TRASH means "for good" (DEL 04s).
        if self._current_folder == "Trash" and not self._demo_mode:
            self._permanent_delete(msgs)
            return
        # ── Protected mail (DEL 09p) ─────────────────────────────────────────
        # The real gate is in _soft_delete, where EVERY delete passes. This is
        # only about not asking a question whose answer cannot matter: with
        # nothing deletable left there is nothing to turn server delete on FOR,
        # and a prompt saying "these 12 messages" when 12 of them are staying
        # put would be a straight lie.
        n_prot = sum(1 for m in msgs if self._is_protected_message(m))
        if n_prot and n_prot == len(msgs) and len(msgs) > 1:
            self._flash(f"🔒 All {n_prot} are protected — nothing deleted. "
                        f"Open one on its own to delete it")
            self._update_bulk_bar()
            return
        have_uid = any(m.get("uid") for m in msgs)
        server = (self.cfg.get("allow_server_changes", False)
                  and not self._demo_mode
                  and have_uid)
        # Server delete OFF but a real account exists → offer to enable it,
        # rather than dead-ending at a local hide (same fix as single delete).
        if not server and not self._demo_mode and have_uid:
            choice = self._prompt_server_delete(max(1, len(msgs) - n_prot))
            if choice is None:
                return
            if choice == "server":
                server = True
            # choice == "hide" → fall through to the local hide below
        if server:
            # No Yes/No popup (Issu 2026-08-01) — the batch goes at once and the
            # Undo button holds the Gmail move for a minute. Self-addressed mail
            # already carries its own explainer in the reading pane, and Undo
            # covers a mis-click, so the old warning dialog is gone.
            self._soft_delete(msgs, permanent=False, server=True)
            self._update_bulk_bar()
            return

        # Local-only hide (demo mail / no server id): same instant-plus-Undo
        # behaviour, nothing on Gmail to change.
        self._soft_delete(msgs, permanent=False, server=False)
        self._update_bulk_bar()

    # ── Undo ──────────────────────────────────────────────────────────────────
    def _push_undo(self, kind, label, payload):
        """Remember something reversible. Only local actions go on this stack
        — anything that touched the server is not undoable from here, and
        pretending otherwise would be a lie."""
        self._undo_stack.append({"kind": kind, "label": label,
                                 "payload": payload, "when": _now_iso()})
        del self._undo_stack[:-20]
        self._flash(f"{label} — Ctrl+Z to undo")

    def _undo_last(self):
        if not self._undo_stack:
            self._flash("Nothing to undo")
            return
        act = self._undo_stack.pop()
        kind = act["kind"]
        if kind == "hide":
            for msg in act["payload"]:
                if msg not in self._all_messages:
                    self._all_messages.append(msg)
                if msg not in self._messages:
                    self._messages.append(msg)
            self._apply_sort()
            self._render_msg_list()
            self._flash("Undone: " + act["label"])
        elif kind == "tag":
            msg, tag_id = act["payload"]
            _tag_toggle(self._tag_store, msg, tag_id)
            self._render_msg_list()
            self._flash("Undone: " + act["label"])
        else:
            self._flash("That cannot be undone")

    def _msg_index(self, msg):
        """Where a message sits in the CURRENT list, for Shift+click runs."""
        for i, m in enumerate(self._messages):
            if m is msg:
                return i
        return None

    # ── Right-click a MESSAGE → its actions (DEL 09e) ──────────────────────────
    def _msg_context_menu(self, event, msg):
        """Right-click a message row. Acts on the whole multi-selection when the
        clicked row is part of one, otherwise on just that message."""
        # The Deleted archive has its own set of actions (restore / continue).
        if msg.get("_folder") == "Deleted":
            self._deleted_context_menu(event, msg)
            return
        ids = self._selected_ids
        if msg.get("id") in ids and len(ids) > 1:
            targets = self._selected_messages()
        else:
            targets = [msg]
        many = len(targets) > 1
        lab  = f"{len(targets)} messages" if many else "message"

        # ── A COLLAPSED ROW IS THE WHOLE CONVERSATION (Issu 2026-09-01) ──────
        # "Allt som är collapsed ska behandlas med samma regel. Vill jag
        #  särskilja så får jag expanda."  So every command that ACTS on mail
        #  gets `acts` (members folded into the closed rows) and says the real
        #  number in `alab`; the read-one-message commands (Open, Reply,
        #  Forward, Snooze, Where is this…) keep `msg`, because replying to a
        #  five-message thread as if it were one mail means nothing.
        #  `targets`/`many`/`lab` stay the LITERAL rows — that is what decides
        #  which single-message items are offered at all.
        acts, _extra = self._expand_collapsed_threads(targets)
        if _extra:
            alab = (f"this conversation ({len(acts)} messages)" if not many
                    else f"these {len(acts)} messages (whole conversations)")
        else:
            alab = lab

        m = tk.Menu(self.root, tearoff=0, bg=C_BG2, fg=C_FG,
                    activebackground=C_BG4, activeforeground=C_FG)

        if not many:
            # The exact time, right where you are when you wonder about it
            # (Issu 2026-08-29). The list deliberately keeps saying
            # "Yesterday" — that is the readable form — so this is the way
            # back to the clock it stands for. Disabled: it is a fact to read,
            # not a command; the line under it copies it.
            _exact = _exact_time(msg)
            m.add_command(label=f"🕐  {_exact}", state="disabled")
            m.add_command(label="📋  Copy the exact time",
                          command=lambda t=_exact: self._copy_to_clipboard(
                              t, "Exact time copied"))
            m.add_separator()
            # Addresses, without having to open the message first — the same
            # sender/recipient copy options the reading-pane header offers
            # (Issu 2026-08-29).
            _frm = parseaddr(msg.get("from", ""))[1] or msg.get("from", "")
            if _frm:
                m.add_command(
                    label=f"📋  Copy sender address  ({_frm})",
                    command=lambda x=_frm: self._copy_to_clipboard(
                        x, "Address copied"))
            self._add_recipient_copy_items(m, msg)
            # ✉ Address-mail mark (manual) — Issu 2026-09-23. The whole-mail
            # variant: no snippet, the envelope just says "there's an address in
            # here". The other variant (save a selection) lives in the reading-
            # pane right-click, where there is text to select.
            _amarked = _addr_is_marked(self._address_store, msg)
            m.add_command(
                label=("✉  Unmark as address mail" if _amarked
                       else "✉  Mark as address mail"),
                command=lambda mm=msg: self._addr_toggle_mark(mm))
            m.add_separator()
            m.add_command(label="Open", command=lambda mm=msg: self._focus_message(mm))
            m.add_command(label="Reply", command=lambda mm=msg: self._ctx_reply(mm))
            m.add_command(label="Forward",
                          command=lambda mm=msg: self._ctx_forward(mm))
            m.add_separator()
            # "Var ligger det här mailet?" — the question Issu asks most often
            # (2026-08-08). Answered properly: every folder AND every account,
            # plus the Gmail labels it carries.
            m.add_command(label="🧭  Where is this message?…",
                          command=lambda mm=msg: self._where_is_dialog(mm))
            m.add_separator()

        m.add_command(label=f"Mark {alab} as read",
                      command=lambda t=acts: self._ctx_mark_read(t, True))
        m.add_command(label=f"Mark {alab} as unread",
                      command=lambda t=acts: self._ctx_mark_read(t, False))
        m.add_separator()

        any_star = any(t.get("starred") for t in targets)
        m.add_command(label=("Remove star" if any_star else "Star"),
                      command=lambda t=acts, s=not any_star: self._ctx_star(t, s))
        any_spam = any(t.get("spam") for t in targets)
        if any_spam:
            m.add_command(label="Not spam (this sender)",
                          command=lambda t=acts: self._ctx_not_spam(t))
        else:
            # Three kinds of spam, the way Issu asked for them.
            spam_menu = tk.Menu(m, tearoff=0, bg=C_BG2, fg=C_FG,
                                activebackground=C_BG4, activeforeground=C_FG)
            spam_menu.add_command(
                label="Internal — block sender, mark read, delete everywhere",
                command=lambda t=acts: self._spam_internal(t))
            spam_menu.add_command(
                label="Report to Gmail  (move to Spam so Gmail learns)",
                command=lambda t=acts: self._spam_external(t))
            spam_menu.add_command(
                label="Internal + unsubscribe",
                command=lambda t=acts: self._spam_unsubscribe(t))
            spam_menu.add_separator()
            spam_menu.add_command(
                label="Just flag as spam here (keep it in the list)",
                command=lambda t=acts: self._ctx_spam(t, True))
            m.add_cascade(label="Mark as spam", menu=spam_menu)
        m.add_separator()

        if not many:
            already = _is_always_unread(self._blocklist_store, msg)
            m.add_command(
                label=("Stop keeping this sender unread" if already
                       else "Always keep this sender unread (Inbox)"),
                command=lambda mm=msg: self._ctx_toggle_always_unread(mm))
            if msg.get("_float"):
                m.add_command(
                    label="✔ Reminder done — put this mail back to normal",
                    command=lambda mm=msg: self._followup_resolve_msg(mm))
            m.add_command(label="Notify me on…",
                          command=lambda mm=msg: self._ctx_snooze(mm))
            m.add_command(label="Create rule from this message…",
                          command=lambda mm=msg: self._sender_rules_dialog(mm))
            m.add_command(label="Create mail filter from this message…",
                          command=lambda mm=msg: self._filters_dialog(prefill_msg=mm))
        m.add_command(label=f"Save {alab} to Notes",
                      command=lambda t=acts: self._ctx_to_notes(t))
        # Manual move to a Gmail folder/label (real accounts). Reuses the same
        # server move as the filter action (DEL 04z).
        if not self._demo_mode and any(t.get("uid") for t in targets):
            # `acts`/`alab`, like every other action above: a collapsed row
            # moves as the whole conversation, and the label says the real
            # number before you click. (Both move paths expand again on their
            # own, harmlessly — the expansion is idempotent — so they are
            # still safe when called from anywhere else.)
            m.add_command(label=f"Move {alab} to folder…",
                          command=lambda t=acts: self._move_messages(t))
            # Move to a folder on ANOTHER account (e.g. the main one) — only
            # worth offering when there IS a second account (Issu 2026-08-01).
            if len([a for a in self._accounts if not a.get("virtual")]) > 1:
                m.add_command(
                    label=f"Move {alab} to another account…",
                    command=lambda t=acts: self._move_to_other_account(t))
        # ── Merge / un-merge conversations (DEL 04A1) ────────────────────────
        # Default is one row per message; this is where you GROUP ones that
        # belong together (a picker with checkboxes, or the current selection),
        # or split a group back apart (Issu: Tradera Frakthandlingar separate,
        # but a real reply chain merged on demand).
        m.add_separator()
        if many:
            m.add_command(
                label=f"🔗 Merge these {len(targets)} into one conversation",
                command=lambda t=targets:
                    self._do_merge([_msg_key(x) for x in t]))
        m.add_command(label="🔗 Merge with…  (pick look-alikes)",
                      command=lambda mm=msg: self._merge_dialog(mm))
        # Offer "Separate" whenever this row actually stands for more than one
        # message — a manual merge group OR an auto Gmail thread (Issu
        # 2026-08-02: a 7-mail expandable had no split button, only Merge).
        is_manual = _merge_group_id_for(self._merge_store, _msg_key(msg)) is not None
        conv_n = self._conversation_member_count(msg)
        if is_manual or conv_n > 1:
            split_lbl = ("✂ Split this conversation apart (un-merge)"
                         if is_manual else
                         f"✂ Separate this conversation ({conv_n}) — one row each")
            m.add_command(label=split_lbl,
                          command=lambda mm=msg: self._unmerge(mm))
        # ── …and the standing answer, on the row where you meet the problem ──
        # "Don't auto-merge in this folder" has lived on the FOLDER's own
        # right-click since 2026-08-19, which is not where anyone looks: you
        # notice the problem here, on a collapsed row of look-alikes. Same
        # setting, same folder, offered where the question comes up
        # (Issu 2026-08-23).
        nm_fld  = msg.get("_folder", "")
        nm_acct = msg.get("account_email", "")
        if nm_fld and nm_acct and nm_fld not in _VIRTUAL_FOLDERS \
                and not self._demo_mode:
            nm_short = nm_fld.replace("\\", "/").rstrip("/").split("/")[-1] \
                or nm_fld
            if self._is_no_merge(nm_acct, nm_fld):
                m.add_command(
                    label=f'🔗 Auto-merge conversations in “{nm_short}” again',
                    command=lambda a=nm_acct, f=nm_fld, s=nm_short:
                        self._toggle_no_merge(a, f, s))
            else:
                m.add_command(
                    label=f'🔗 Never merge anything in “{nm_short}” — '
                          f'one row per message',
                    command=lambda a=nm_acct, f=nm_fld, s=nm_short:
                        self._toggle_no_merge(a, f, s))
        # In the Trash: put it BACK (move to the Inbox). Gmail's Trash has no
        # record of the original folder, so restore lands in the Inbox.
        if (self._current_folder == "Trash" and not self._demo_mode
                and any(t.get("uid") for t in targets)):
            m.add_separator()
            m.add_command(label=f"Restore {alab} from Trash  (back to Inbox)",
                          command=lambda t=acts: self._untrash_messages(t))
        # ── 🔒 Protect / 🔓 Unprotect (DEL 09p) ──────────────────────────────
        # Right next to Delete, because that is the only thing protection has
        # an opinion about. A mixed selection offers BOTH, so neither half of
        # it is silently decided for you.
        m.add_separator()
        n_prot = sum(1 for t in acts if self._is_protected_message(t))
        if n_prot < len(acts):
            m.add_command(
                label=(f"🔒  Protect {alab} from bulk delete"
                       if not n_prot else
                       f"🔒  Protect the other {len(acts) - n_prot}"),
                command=lambda t=acts: self._protect_messages(t))
        if n_prot:
            m.add_command(
                label=(f"🔓  Unprotect {alab}" if n_prot == len(acts)
                       else f"🔓  Unprotect the {n_prot} protected one(s)"),
                command=lambda t=acts: self._unprotect_messages(t))
        m.add_separator()
        m.add_command(label=f"Delete {alab}…",
                      command=lambda t=acts: self._ctx_delete(t))

        try:
            m.tk_popup(event.x_root, event.y_root)
        finally:
            m.grab_release()

    def _known_folder_names(self):
        """Folder / label names to offer when moving mail: your recently-used
        destinations FIRST (Issu 2026-08-02 "ofta-vägar"), then the standard
        ones, then every custom label discovered across the real accounts."""
        names, seen = [], set()
        # Frequent / recent destinations first.
        for nm in (self.cfg.get("recent_move_folders", []) or []):
            if nm and nm not in seen:
                seen.add(nm); names.append(nm)
        for f in _FOLDERS:
            if f not in _VIRTUAL_FOLDERS and f not in seen:
                seen.add(f); names.append(f)
        for lst in (self._user_folders or {}).values():
            for entry in lst:
                nm = entry.get("full") or entry.get("display") or ""
                if nm and nm not in seen:
                    seen.add(nm); names.append(nm)
        return names

    def _record_move_folder(self, name):
        """Remember a move destination so it rises to the top of the picker
        next time (most-recent first, capped at 10) — and feed the favourite
        slots (DEL 09g) and the use COUNT the dropdown sorts on (DEL 09i)."""
        name = (name or "").strip()
        if not name:
            return
        recent = [n for n in (self.cfg.get("recent_move_folders", []) or [])
                  if n != name]
        recent.insert(0, name)
        self.cfg["recent_move_folders"] = recent[:10]
        counts = self.cfg.get("move_folder_counts")
        if not isinstance(counts, dict):
            counts = {}
        try:
            counts[name] = int(counts.get(name, 0) or 0) + 1
        except Exception:
            counts[name] = 1
        self.cfg["move_folder_counts"] = counts
        self._fav_record(name, save=False)
        _save_settings(self.cfg)

    # ── DEL 09i — "ALL OF THEM, MOST USED AT THE TOP" (Issu 2026-08-22) ───────
    #
    # "Move to folder… alternativen rymmer bara 3, sedan tar popup-bredden
    #  slut. Bättre om en dropdown-lista med alla sparade; sorterade efter
    #  'mest använd = överst'."
    #
    # The five favourite chips are laid out side by side, and a Gmail label
    # path is long ("INBOX/Temporär/0---Frakt & Kvitto"), so the fourth and
    # fifth ran off the edge of a 580-px dialog and were simply not there. Two
    # separate things were wrong and both are fixed:
    #
    #   • the chips now WRAP (three to a row) instead of falling off the end,
    #     so all five slots are always visible;
    #   • and there is a real dropdown listing EVERY folder, ordered by how
    #     many times mail has actually gone there. The counts are what makes
    #     it useful: recency alone kept demoting the folder he uses constantly
    #     the moment he filed one thing somewhere else.
    def _move_count(self, name) -> int:
        counts = self.cfg.get("move_folder_counts") or {}
        try:
            return int(counts.get(name, 0) or 0)
        except Exception:
            return 0

    def _folders_by_use(self, names=None):
        """Every folder worth offering, most-used first.

        Order: highest use count, then most recently used, then alphabetically
        — so a brand-new mailbox is still sorted sensibly on the day the counts
        are all zero. Returns [(name, count), …]."""
        if names is None:
            names = self._known_folder_names()
        recent = [n for n in (self.cfg.get("recent_move_folders", []) or []) if n]
        rank = {n: i for i, n in enumerate(recent)}
        out, seen = [], set()
        for nm in list(names) + recent:          # a recent folder the server
            if nm and nm not in seen:            # no longer lists is still
                seen.add(nm)                     # somewhere mail went
                out.append(nm)
        out.sort(key=lambda n: (-self._move_count(n),
                                rank.get(n, 10_000),
                                n.lower()))
        return [(n, self._move_count(n)) for n in out]

    def _folder_dropdown_row(self, parent, get_names, set_name, choose):
        """The "▾ All folders — most used first" row.

        A tk OptionMenu cannot show two hundred labels usefully and ttk's
        Combobox will not take this theme, so the dropdown is built here: a
        borderless Toplevel under the button holding a filtered, scrollable
        list. One click fills the Folder box, a double-click moves."""
        row = tk.Frame(parent, bg=C_BG3)
        row.pack(fill="x", padx=12, pady=(4, 0))
        tk.Label(row, text="▾ All folders:", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 9, "bold")).pack(side="left")

        shown = tk.StringVar(value="  (click to choose — most used at the top)")
        btn = tk.Label(row, textvariable=shown, bg=C_BG2, fg=C_FG,
                       font=("Segoe UI", 9), anchor="w", cursor="hand2",
                       padx=8, pady=3)
        btn.pack(side="left", fill="x", expand=True, padx=(6, 0))
        add_tooltip(btn, "Every folder you can move mail to, ordered by how "
                         "many times you have actually moved mail there. "
                         "Type to narrow the list; double-click to move.")

        state = {"pop": None}

        def _close(*_a):
            pop = state.get("pop")
            state["pop"] = None
            try:
                if pop is not None and pop.winfo_exists():
                    pop.destroy()
            except Exception:
                pass

        def _open(*_a):
            if state.get("pop") is not None:
                _close()
                return
            pop = tk.Toplevel(parent)
            pop.overrideredirect(True)
            pop.configure(bg=C_ACCENT2)
            state["pop"] = pop
            x = btn.winfo_rootx()
            y = btn.winfo_rooty() + btn.winfo_height()
            w = max(320, btn.winfo_width())
            pop.geometry(f"{w}x300+{x}+{y}")
            try:
                pop.transient(parent.winfo_toplevel())
            except Exception:
                pass

            inner = tk.Frame(pop, bg=C_BG2)
            inner.pack(fill="both", expand=True, padx=1, pady=1)
            e_f = tk.Entry(inner, bg=C_BG3, fg=C_FG, relief="flat",
                           insertbackground=C_ACCENT, font=("Segoe UI", 9),
                           insertofftime=0, insertontime=9999999)
            no_blink(e_f)
            e_f.pack(fill="x", padx=4, pady=4, ipady=2)

            lf = tk.Frame(inner, bg=C_BG2)
            lf.pack(fill="both", expand=True, padx=4, pady=(0, 4))
            # Scrollbar BEFORE the expanding listbox, or Tk renders it 1 px
            # wide (the packer trap — see the same note in File_manager).
            sb = tk.Scrollbar(lf, bg=C_BG3, troughcolor=C_BG1)
            sb.pack(side="right", fill="y")
            lb = tk.Listbox(lf, bg=C_BG2, fg=C_FG, relief="flat",
                            highlightthickness=0, activestyle="none",
                            selectbackground=C_MSG_SEL,
                            selectforeground=C_FG_UNRD,
                            font=("Segoe UI", 9), exportselection=False,
                            yscrollcommand=sb.set)
            lb.pack(side="left", fill="both", expand=True)
            sb.configure(command=lb.yview)
            _bind_mousewheel(lb, lb)

            rows = []                       # parallel to the listbox contents

            def _fill(*_a):
                needle = e_f.get().strip().lower()
                rows.clear()
                lb.delete(0, "end")
                for nm, cnt in self._folders_by_use(get_names()):
                    if needle and needle not in nm.lower():
                        continue
                    rows.append(nm)
                    tail = f"   ({cnt}×)" if cnt else ""
                    lb.insert("end", f"{nm}{tail}")
                if rows:
                    lb.selection_set(0)

            def _take(commit):
                sel = lb.curselection()
                if not sel:
                    return
                nm = rows[sel[0]]
                shown.set("  " + nm)
                _close()
                (choose if commit else set_name)(nm)

            e_f.bind("<KeyRelease>", _fill)
            e_f.bind("<Down>", lambda ev: (lb.focus_set(), "break"))
            e_f.bind("<Return>", lambda ev: (_take(False), "break"))
            e_f.bind("<Escape>", lambda ev: (_close(), "break"))
            lb.bind("<Return>", lambda ev: _take(False))
            lb.bind("<Double-Button-1>", lambda ev: _take(True))
            lb.bind("<Button-1>", lambda ev: lb.after(1, lambda: _take(False)))
            lb.bind("<Escape>", lambda ev: _close())
            pop.bind("<FocusOut>", lambda ev: None)   # clicking the list is a
                                                      # focus change; never
                                                      # close on it
            _fill()
            e_f.focus_set()

        btn.bind("<Button-1>", _open)
        btn.bind("<Enter>", lambda ev: btn.configure(bg=C_BG4))
        btn.bind("<Leave>", lambda ev: btn.configure(bg=C_BG2))
        try:
            parent.winfo_toplevel().bind("<Destroy>", lambda ev: _close(),
                                         add="+")
        except Exception:
            pass
        return shown

    # ── FIVE favourite destinations (Issu 2026-08-03) ─────────────────────────
    #
    # "Jag har sagt… 5 platser för detta… 4 första blir permanenta (måste
    #  väljas bort) och femte ersätts hela tiden."
    #
    # Slots 1–4 are PERMANENT: the first four different folders you move mail
    # to claim them and stay there until you press the ✕ on the chip. Slot 5 is
    # the rolling one and is overwritten by every destination after that. So
    # the four folders you use constantly settle down and stop moving about,
    # while the fifth is whatever you touched last — which is the pair of
    # behaviours a most-recently-used list can never give you at the same time.
    FAV_SLOTS   = 5
    FAV_PINNED  = 4          # slots 1..4; slot 5 (index 4) is the rolling one

    def _fav_list(self):
        """The favourite slots as a clean list of {"name", "pinned"} dicts,
        never longer than FAV_SLOTS. Repairs anything odd found on disk."""
        out = []
        for i, entry in enumerate(self.cfg.get("fav_move_folders", []) or []):
            if isinstance(entry, str):
                entry = {"name": entry, "pinned": i < self.FAV_PINNED}
            if not isinstance(entry, dict):
                continue
            name = (entry.get("name") or "").strip()
            if not name or any(f["name"] == name for f in out):
                continue
            out.append({"name": name,
                        "pinned": bool(entry.get("pinned",
                                                 len(out) < self.FAV_PINNED))})
            if len(out) >= self.FAV_SLOTS:
                break
        return out

    def _fav_save(self, favs, save=True):
        self.cfg["fav_move_folders"] = [dict(f) for f in favs[:self.FAV_SLOTS]]
        if save:
            _save_settings(self.cfg)

    def _fav_record(self, name, save=True):
        """A destination was actually used: claim a permanent slot if one is
        still free, otherwise take the rolling fifth."""
        name = (name or "").strip()
        if not name:
            return
        favs = self._fav_list()
        if any(f["name"] == name for f in favs):
            return                              # already a favourite
        pinned = [f for f in favs if f["pinned"]][:self.FAV_PINNED]
        if len(pinned) < self.FAV_PINNED:
            pinned.append({"name": name, "pinned": True})
            rolling = [f for f in favs if not f["pinned"]]
        else:
            rolling = [{"name": name, "pinned": False}]
        self._fav_save(pinned + rolling[:self.FAV_SLOTS - len(pinned)], save)

    def _fav_pin(self, name, save=True):
        """Pin a folder by hand into the first free permanent slot; if all four
        are taken, the oldest permanent one steps aside."""
        name = (name or "").strip()
        if not name:
            return
        favs   = [f for f in self._fav_list() if f["name"] != name]
        pinned = [f for f in favs if f["pinned"]]
        rolling = [f for f in favs if not f["pinned"]]
        pinned.append({"name": name, "pinned": True})
        pinned = pinned[-self.FAV_PINNED:]      # oldest falls off
        self._fav_save(pinned + rolling[:self.FAV_SLOTS - len(pinned)], save)

    def _fav_remove(self, name, save=True):
        self._fav_save([f for f in self._fav_list()
                        if f["name"] != (name or "").strip()], save)

    # ── The folder picker itself ──────────────────────────────────────────────
    def _folder_tree_nodes(self, names):
        """Turn a flat list of folder paths into a nested tree.

        Node: {"seg", "path", "leaf": bool, "children": [node, …]}. `leaf` says
        the path is a real folder you can move mail to; a purely intermediate
        level (a Gmail label that only exists as a parent) is still shown, but
        choosing it would create a new label — which is exactly what the Entry
        below the tree is for, so it stays selectable."""
        root = {"seg": "", "path": "", "leaf": False, "kids": {}}
        for name in names:
            parts = [p for p in (name or "").split("/") if p != ""]
            if not parts:
                continue
            node, path = root, ""
            for p in parts:
                path = f"{path}/{p}" if path else p
                node = node["kids"].setdefault(
                    p, {"seg": p, "path": path, "leaf": False, "kids": {}})
            node["leaf"] = True

        def _flatten(n):
            n["children"] = [_flatten(k) for _, k in
                             sorted(n["kids"].items(),
                                    key=lambda kv: kv[0].lower())]
            n.pop("kids", None)
            return n
        return _flatten(root)["children"]

    def _fav_chip_row(self, parent, set_name, choose):
        """The ★ Favourites strip. Returns a redraw() to call after a change.

        Shared by both folder pickers so the five slots mean the same thing
        wherever you move mail from."""
        host = tk.Frame(parent, bg=C_BG3)
        host.pack(fill="x", padx=12, pady=(2, 4))

        # THREE CHIPS TO A ROW, THEN WRAP (Issu 2026-08-22). Packed side by
        # side they ran off the edge of the dialog at the fourth one — a
        # Gmail label path is long, the dialog is 580 px, and pack() does not
        # wrap: slots 4 and 5 were not "hard to see", they were off-screen.
        FAV_PER_ROW = 3

        def redraw():
            for w in host.winfo_children():
                w.destroy()
            favs = self._fav_list()
            head = tk.Frame(host, bg=C_BG3)
            head.pack(fill="x")
            tk.Label(head, text="★ Favourites:", bg=C_BG3, fg=C_FG,
                     font=("Segoe UI", 9, "bold")).pack(side="left")
            if not favs:
                tk.Label(head,
                         text="  (the first four folders you move mail to "
                              "become permanent here; the fifth is always the "
                              "one you used last)",
                         bg=C_BG3, fg=C_FG_DIM, wraplength=420, justify="left",
                         font=("Segoe UI", 8, "italic")).pack(side="left")
                return
            line = [None]

            def _new_line():
                line[0] = tk.Frame(host, bg=C_BG3)
                line[0].pack(fill="x", pady=1)
                return line[0]

            for i, f in enumerate(favs):
                if i % FAV_PER_ROW == 0:
                    _new_line()
                chip = tk.Frame(line[0], bg=C_BG2)
                chip.pack(side="left", padx=3)
                mark  = "📌" if f["pinned"] else "⏱"
                short = f["name"]
                if len(short) > 22:
                    short = "…" + short[-21:]
                b = tk.Label(chip, text=f" {mark} {short} ", bg=C_BG2,
                             fg=C_ACCENT if f["pinned"] else C_FG_DIM,
                             font=("Segoe UI", 8), cursor="hand2")
                b.pack(side="left")
                b.bind("<Button-1>", lambda ev, n=f["name"]: set_name(n))
                b.bind("<Double-Button-1>", lambda ev, n=f["name"]: choose(n))
                b.bind("<Enter>", lambda ev, w=b: w.configure(bg=C_BG4))
                b.bind("<Leave>", lambda ev, w=b: w.configure(bg=C_BG2))
                add_tooltip(b, f["name"] +
                            ("   ·  permanent slot — press ✕ to free it"
                             if f["pinned"] else
                             "   ·  the rolling 5th slot, replaced by whatever "
                             "you use next"))
                x = tk.Label(chip, text="✕ ", bg=C_BG2, fg="#c05a5a",
                             font=("Segoe UI", 8), cursor="hand2")
                x.pack(side="left")
                x.bind("<Button-1>",
                       lambda ev, n=f["name"]: (self._fav_remove(n), redraw()))
        redraw()
        return redraw

    def _folder_tree_body(self, parent, get_names, set_name, choose,
                          after_pin=None):
        """A COLLAPSIBLE folder tree with a Find box and Collapse/Expand all.

        Replaces the flat list that made a mailbox with fifty labels unusable
        ("det finns fortfarande ingen kollaps i katalogerna", Issu 2026-08-03).
        What is folded is remembered in the settings, so the picker opens the
        way you left it. Returns (redraw, save_state)."""
        collapsed = set(self.cfg.get("picker_collapsed", []) or [])
        state = {"nodes": []}

        frow = tk.Frame(parent, bg=C_BG3)
        frow.pack(fill="x", padx=12)
        tk.Label(frow, text="Find:", bg=C_BG3, fg=C_FG_DIM, width=6,
                 anchor="e", font=("Segoe UI", 9)).pack(side="left")
        e_find = tk.Entry(frow, bg=C_BG2, fg=C_FG, relief="flat",
                          insertbackground=C_ACCENT, font=("Segoe UI", 10),
                          insertofftime=0, insertontime=9999999)
        no_blink(e_find)
        e_find.pack(side="left", fill="x", expand=True, ipady=2, padx=(4, 0))

        twrap = tk.Frame(parent, bg=C_BG2)
        twrap.pack(fill="both", expand=True, padx=12, pady=6)
        tsb = tk.Scrollbar(twrap, bg=C_BG3, troughcolor=C_BG1)
        tsb.pack(side="right", fill="y")
        tcanvas = tk.Canvas(twrap, bg=C_BG2, highlightthickness=0,
                            yscrollcommand=tsb.set)
        tsb.configure(command=tcanvas.yview)
        tcanvas.pack(side="left", fill="both", expand=True)
        tinner = tk.Frame(tcanvas, bg=C_BG2)
        twin = tcanvas.create_window((0, 0), window=tinner, anchor="nw")
        tinner.bind("<Configure>",
                    lambda ev: tcanvas.configure(
                        scrollregion=tcanvas.bbox("all")))
        tcanvas.bind("<Configure>",
                     lambda ev: tcanvas.itemconfig(twin, width=ev.width))
        _bind_mousewheel(tinner, tcanvas)

        def _pin(path):
            self._fav_pin(path)
            if after_pin:
                after_pin()

        def _row(node, depth):
            path   = node["path"]
            kids   = node["children"]
            folded = path in collapsed
            row = tk.Frame(tinner, bg=C_BG2)
            row.pack(fill="x")
            tk.Frame(row, bg=C_BG2,
                     width=6 + depth * 14).pack(side="left", fill="y")
            if kids:
                tw = tk.Label(row, text=("▸" if folded else "▾"), bg=C_BG2,
                              fg=C_ACCENT, font=("Segoe UI", 8), width=2,
                              cursor="hand2")
                tw.pack(side="left")
                tw.bind("<Button-1>", lambda ev, p=path: _toggle(p))
            else:
                tk.Label(row, text=" ", bg=C_BG2, width=2).pack(side="left")
            n_kids = len(kids)
            count  = f"   ({n_kids})" if (kids and folded) else ""
            lbl = tk.Label(row, text=f"{'📂' if kids else '📁'}  "
                                     f"{node['seg']}{count}",
                           bg=C_BG2, fg=C_FG if node["leaf"] else C_FG_DIM,
                           font=("Segoe UI", 9), anchor="w", cursor="hand2")
            lbl.pack(side="left", fill="x", expand=True)
            lbl.bind("<Button-1>", lambda ev, p=path: set_name(p))
            lbl.bind("<Double-Button-1>", lambda ev, p=path: choose(p))
            lbl.bind("<Enter>", lambda ev, w=lbl: w.configure(bg=C_BG4))
            lbl.bind("<Leave>", lambda ev, w=lbl: w.configure(bg=C_BG2))
            add_tooltip(lbl, path)
            star = tk.Label(row, text="★", bg=C_BG2, fg="#6a6f8a",
                            font=("Segoe UI", 9), cursor="hand2")
            star.pack(side="right", padx=(0, 8))
            star.bind("<Button-1>", lambda ev, p=path: _pin(p))
            add_tooltip(star, "Keep this folder in a permanent favourite slot")
            if kids and not folded:
                for k in kids:
                    _row(k, depth + 1)

        def redraw(*_a):
            for w in tinner.winfo_children():
                w.destroy()
            names = list(get_names())
            state["nodes"] = self._folder_tree_nodes(names)
            needle = e_find.get().strip().lower()
            if needle:
                # A search shows a FLAT list of every hit: folding is also a way
                # of finding things, and the two must not fight each other.
                hits = [n for n in names if needle in n.lower()]
                if not hits:
                    tk.Label(tinner, text="   no folder matches that",
                             bg=C_BG2, fg=C_FG_DIM,
                             font=("Segoe UI", 9, "italic"),
                             anchor="w").pack(fill="x", pady=6)
                for nm in hits[:400]:
                    lbl = tk.Label(tinner, text=f"   📁  {nm}", bg=C_BG2,
                                   fg=C_FG, font=("Segoe UI", 9), anchor="w",
                                   cursor="hand2")
                    lbl.pack(fill="x")
                    lbl.bind("<Button-1>", lambda ev, n=nm: set_name(n))
                    lbl.bind("<Double-Button-1>", lambda ev, n=nm: choose(n))
                    lbl.bind("<Enter>", lambda ev, w=lbl: w.configure(bg=C_BG4))
                    lbl.bind("<Leave>", lambda ev, w=lbl: w.configure(bg=C_BG2))
                return
            for n in state["nodes"]:
                _row(n, 0)

        def _toggle(path):
            collapsed.discard(path) if path in collapsed else collapsed.add(path)
            redraw()

        def _all(fold):
            def walk(ns):
                for n in ns:
                    if n["children"]:
                        if fold:
                            collapsed.add(n["path"])
                        else:
                            collapsed.discard(n["path"])
                        walk(n["children"])
            walk(state["nodes"])
            redraw()

        e_find.bind("<KeyRelease>", redraw)

        crow = tk.Frame(parent, bg=C_BG3)
        crow.pack(fill="x", padx=12)
        for text, cmd in (("▸ Collapse all", lambda: _all(True)),
                          ("▾ Expand all", lambda: _all(False))):
            tk.Button(crow, text=text, bg=C_BG2, fg=C_FG_DIM,
                      font=("Segoe UI", 8), relief="flat", cursor="hand2",
                      padx=8, pady=1,
                      command=cmd).pack(side="left", padx=(0, 4))

        def save_state():
            self.cfg["picker_collapsed"] = sorted(collapsed)
            _save_settings(self.cfg)

        redraw()                # draw it once, now — not only on a keystroke
        return redraw, save_state

    def _pick_target_folder(self, title, note=""):
        """Pick a folder/label to move mail to.

        Three ways in, in the order you actually use them:
          ★ five favourite slots   — one click, always at the top
          📂 a collapsible tree     — sub-folders fold away and STAY folded
          ⌨ the name typed by hand — a folder that does not exist is created

        `note` is an optional line shown before you choose — used to say that
        a collapsed conversation is going as a whole, since a title bar
        truncates and this must not be a surprise.

        Returns the chosen name, or None if cancelled."""
        top = self._dialog_shell(title, 620, 730)
        result = {"name": None}

        if note:
            nb = tk.Frame(top, bg="#243a4a", padx=10, pady=6)
            nb.pack(fill="x", padx=12, pady=(6, 0))
            tk.Label(nb, text=note, bg="#243a4a", fg="#bfe0f5",
                     font=("Segoe UI", 8), anchor="w", justify="left",
                     wraplength=560).pack(fill="x")

        tk.Label(top, text="Pick a folder/label, or type a new name (it will "
                           "be created). Sub-folders fold away with ▸ and stay "
                           "that way next time.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 wraplength=540, justify="left", pady=4).pack(fill="x", padx=12)

        erow = tk.Frame(top, bg=C_BG3)          # packed further down
        e = tk.Entry(erow, bg=C_BG2, fg=C_FG, relief="flat",
                     insertbackground=C_ACCENT, font=("Segoe UI", 10),
                     insertofftime=0, insertontime=9999999)
        no_blink(e)

        def _set_name(nm):
            e.delete(0, "end")
            e.insert(0, nm)

        def _ok(nm=None):
            nm = (nm if nm is not None else e.get()).strip()
            if nm:
                result["name"] = nm
                save_state()
                top.destroy()

        redraw_favs = self._fav_chip_row(top, _set_name, _ok)
        self._folder_dropdown_row(top, self._known_folder_names, _set_name, _ok)
        _redraw, save_state = self._folder_tree_body(
            top, self._known_folder_names, _set_name, _ok,
            after_pin=lambda: redraw_favs())

        erow.pack(fill="x", padx=12, pady=(6, 0))
        tk.Label(erow, text="Folder:", bg=C_BG3, fg=C_FG_DIM, width=6,
                 anchor="e", font=("Segoe UI", 9)).pack(side="left")
        e.pack(side="left", fill="x", expand=True, ipady=3, padx=(4, 4))
        b_pin = tk.Button(erow, text="★ Pin", bg=C_BTN_STD, fg=C_BTN_FG,
                          font=("Segoe UI", 8), relief="flat", cursor="hand2",
                          padx=8, pady=1,
                          command=lambda: (self._fav_pin(e.get().strip()),
                                           redraw_favs()))
        b_pin.pack(side="left")
        add_tooltip(b_pin, "Keep this folder in a permanent favourite slot "
                           "(the first four; the fifth is always the one you "
                           "used last)")
        e.bind("<Return>", lambda ev: _ok())

        br = tk.Frame(top, bg=C_BG3)
        br.pack(fill="x", padx=12, pady=(6, 10))
        for text, colour, cmd in (("Move here", C_BTN_NEW, _ok),
                                  ("Cancel", C_BTN_STD, top.destroy)):
            tk.Button(br, text=text, bg=colour, fg=C_BTN_FG,
                      font=("Segoe UI", 9), relief="flat", cursor="hand2",
                      padx=12, pady=4, command=cmd).pack(side="left", padx=4)

        e.focus_set()
        top.wait_window()
        return result["name"]

    def _move_messages(self, targets):
        """Move messages to a Gmail folder/label the user picks (DEL 04z).
        A real server change, so Server changes must be on (offered inline).

        A COLLAPSED conversation row moves WHOLE (Issu 2026-09-01) — see
        _expand_collapsed_threads. Expand the row first to move one message
        out of a thread."""
        targets, extra = self._expand_collapsed_threads(targets)
        msgs = [t for t in targets if t.get("uid")]
        if not msgs:
            return
        note = ("" if not extra else
                f"↳  This is a whole conversation: {len(msgs)} messages, "
                f"{extra} of them hidden inside the collapsed row. They all "
                f"go together.\n"
                f"    Cancel and open the row with + first if you meant to "
                f"move a single message out of the thread.")
        target = self._pick_target_folder(
            f"Move {len(msgs)} message(s) to…", note=note)
        if not target:
            return
        self._move_selected_to(msgs, target)
        if extra:
            self._flash(f"Whole conversation moved — {len(msgs)} messages, "
                        f"not just the row")

    def _move_selected_to(self, msgs, target, enable_prompt=True):
        """Move a known set of messages to a NAMED Gmail folder/label. Shared by
        the manual Move… picker and "Report to Gmail spam" (DEL 04A2). A real
        server change, so Server changes must be on — offered inline. Instant in
        the view; the IMAP move runs on a worker and a failure reloads."""
        msgs = [m for m in msgs if m.get("uid")]
        if not msgs:
            return
        # ── DEL 09l — EVERY MOVE IS WRITTEN DOWN, INCLUDING THE ONES THAT DID
        #    NOT HAPPEN (Issu 2026-08-22) ───────────────────────────────────
        # "Log… har den med (försök till) MOVE? (så att jag kan se om något
        #  inte MOVE och i så fall varför)"  It did not: only moves a RULE made
        #  were logged, so a move made by hand — and above all one that quietly
        #  failed on one message out of forty while the other thirty-nine went
        #  through — left no trace at all. The log now carries the attempt,
        #  then one line per message that did NOT make it, with the server's
        #  own words for why.
        src = ", ".join(sorted({(m.get("_folder") or "?") for m in msgs}))[:70]
        self._activity_log(
            "move-try", account=msgs[0].get("account_email", ""),
            subject=(msgs[0].get("subject", "") if len(msgs) == 1 else ""),
            detail=f"asked to move {len(msgs)} message(s): {src} → {target}")
        if not self.cfg.get("allow_server_changes", False):
            if not (enable_prompt and messagebox.askyesno(
                    "Move on Gmail",
                    "Moving mail changes it on Gmail, which is currently off.\n\n"
                    f"Turn on Server changes and move {len(msgs)} message(s) to "
                    f"“{target}”?", parent=self.root, default="no")):
                self._activity_log(
                    "move-failed", account=msgs[0].get("account_email", ""),
                    detail=f"nothing moved to {target} — Server changes is off "
                           f"and you chose not to turn it on")
                return
            self.cfg["allow_server_changes"] = True
            _save_settings(self.cfg)
            log.info("allow_server_changes enabled from Move/Report")
        # Remember this destination so it tops the picker next time (#3).
        self._record_move_folder(target)
        # Instant local removal from the current view.
        for mm in msgs:
            if mm in self._messages:
                self._messages.remove(mm)
            if mm in self._all_messages:
                self._all_messages.remove(mm)
        self._selected_ids = set()
        self._selected_msg = None
        self._render_msg_list()
        self._show_reading_pane_empty()
        self._flash(f"Moving {len(msgs)} → {target}…")

        payload = list(msgs)

        def worker():
            problems = []
            # Per-message outcomes, written to the activity log on the MAIN
            # thread in done(): the store is shared, and saving it once per
            # message would mean forty JSON writes for one bulk move (DEL 09l).
            results = []            # [(ok, msg, reason), …]
            for mm in payload:
                acct   = mm.get("account_email", "")
                pwd    = self._secret_for(acct)
                folder = mm.get("_folder", "Inbox")
                uid    = mm.get("uid")
                if not pwd:
                    why = f"No stored password for {acct}."
                    problems.append(why)
                    results.append((False, mm, why))
                    continue
                try:
                    prob = _imap_move_message(acct, pwd, folder, uid, target)
                    if prob:
                        problems.append(prob)
                        results.append((False, mm, str(prob)))
                        log.warning("move refused uid=%s %s → %s: %s",
                                    uid, folder, target, prob)
                    else:
                        results.append((True, mm, ""))
                        log.info("moved uid=%s %s → %s", uid, folder, target)
                except Exception as e:
                    problems.append(str(e))
                    results.append((False, mm, str(e)))
                    log.error("move failed: %s", e)

            def done():
                good = [r for r in results if r[0]]
                bad  = [r for r in results if not r[0]]
                if good:
                    first = good[0][1]
                    self._activity_log(
                        "moved", account=first.get("account_email", ""),
                        sender=(first.get("from", "") if len(good) == 1 else ""),
                        subject=(first.get("subject", "") if len(good) == 1
                                 else ""),
                        detail=f"moved {len(good)} message(s) to {target}"
                               f"   (by hand, not by a rule)")
                # One line PER failure — "why did THAT one stay behind" is the
                # question this log exists to answer.
                for _ok, mm, why in bad:
                    self._activity_log(
                        "move-failed", account=mm.get("account_email", ""),
                        sender=mm.get("from", ""),
                        subject=mm.get("subject", ""),
                        detail=f"could NOT move to {target} — {why}"[:400])
                if problems:
                    messagebox.showwarning(
                        "Move on Gmail",
                        "Some messages could not be moved:\n\n"
                        + "\n".join(f"• {p}" for p in problems[:6])
                        + "\n\nReloading to show what is really on Gmail.",
                        parent=self.root)
                    self._refresh_messages()
                else:
                    # Unfold the sidebar down to where the mail went, so it is
                    # somewhere you can SEE (Issu 2026-08-03).
                    opened = False
                    for mm in payload:
                        opened |= self._reveal_folder(
                            mm.get("account_email", ""), target, redraw=False)
                    if opened:
                        self._populate_sidebar(self.sidebar_inner)
                    self._maybe_refresh_counts(force=True)
            try:
                self.root.after(0, done)
            except Exception:
                pass
        threading.Thread(target=worker, daemon=True).start()

    # ── Cross-account move (DEL 04A3) — Issu: "flytta till annat konto" ────────
    def _account_folders(self, email):
        """Folder/label names available on ONE account: the standard non-virtual
        ones plus that account's own discovered labels."""
        names = [f for f in _FOLDERS if f not in _VIRTUAL_FOLDERS]
        seen = set(names)
        for entry in (self._user_folders or {}).get(email, []):
            nm = entry.get("full") or entry.get("display") or ""
            if nm and nm not in seen:
                seen.add(nm)
                names.append(nm)
        return names

    def _pick_account_and_folder(self, title, default_account=None):
        """Pick a TARGET ACCOUNT and a folder on it. Returns (email, folder) or
        (None, None). Used to move mail to another account (e.g. the main one)."""
        reals = [a for a in self._accounts if not a.get("virtual")]
        if len(reals) < 2:
            messagebox.showinfo(
                title, "You only have one account, so there is no other account "
                "to move to. Add a second Gmail account first (Accounts → Add).",
                parent=self.root)
            return None, None
        top = self._dialog_shell(title, 620, 750)
        result = {"acct": None, "folder": None}
        tk.Label(top, text="Move to which account, and which folder on it?\n"
                           "The message is COPIED there (original sender kept — "
                           "no forwarding) and then removed from where it is now.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 wraplength=540, justify="left", pady=4).pack(fill="x", padx=12)
        arow = tk.Frame(top, bg=C_BG3); arow.pack(fill="x", padx=12, pady=(4, 0))
        tk.Label(arow, text="Account:", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left")
        emails = [a["email"] for a in reals]
        av = tk.StringVar(value=(default_account if default_account in emails
                                 else emails[0]))
        om = tk.OptionMenu(arow, av, *emails)
        om.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                     activeforeground=C_FG, highlightthickness=0, relief="flat",
                     font=("Segoe UI", 9), anchor="w")
        om["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                             activeforeground=C_FG)
        om.pack(side="left", fill="x", expand=True, padx=(4, 0))

        erow = tk.Frame(top, bg=C_BG3)          # packed further down
        e = tk.Entry(erow, bg=C_BG2, fg=C_FG, relief="flat",
                     insertbackground=C_ACCENT, font=("Segoe UI", 10),
                     insertofftime=0, insertontime=9999999)
        no_blink(e)

        def _set_name(nm):
            e.delete(0, "end")
            e.insert(0, nm)

        def _ok(nm=None):
            nm = (nm if nm is not None else e.get()).strip()
            if nm:
                result["acct"] = av.get()
                result["folder"] = nm
                save_state()
                top.destroy()

        # Same five favourite slots and the same folding tree as the ordinary
        # picker — the filter editor's "Browse…" lands HERE whenever there is
        # more than one account, which is why it looked like the collapse and
        # the favourites had never been built (Issu 2026-08-03).
        redraw_favs = self._fav_chip_row(top, _set_name, _ok)
        self._folder_dropdown_row(
            top, lambda: self._account_folders(av.get()), _set_name, _ok)
        redraw_tree, save_state = self._folder_tree_body(
            top, lambda: self._account_folders(av.get()), _set_name, _ok,
            after_pin=lambda: redraw_favs())
        av.trace_add("write", lambda *_a: redraw_tree())

        erow.pack(fill="x", padx=12, pady=(6, 0))
        tk.Label(erow, text="Folder:", bg=C_BG3, fg=C_FG_DIM, width=6,
                 anchor="e", font=("Segoe UI", 9)).pack(side="left")
        e.pack(side="left", fill="x", expand=True, ipady=3, padx=(4, 4))
        e.insert(0, "Inbox")
        b_pin = tk.Button(erow, text="★ Pin", bg=C_BTN_STD, fg=C_BTN_FG,
                          font=("Segoe UI", 8), relief="flat", cursor="hand2",
                          padx=8, pady=1,
                          command=lambda: (self._fav_pin(e.get().strip()),
                                           redraw_favs()))
        b_pin.pack(side="left")
        e.bind("<Return>", lambda ev: _ok())

        br = tk.Frame(top, bg=C_BG3); br.pack(fill="x", padx=12, pady=(6, 10))
        for text, colour, cmd in (("Move here", C_BTN_NEW, _ok),
                                  ("Cancel", C_BTN_STD, top.destroy)):
            tk.Button(br, text=text, bg=colour, fg=C_BTN_FG, font=("Segoe UI", 9),
                      relief="flat", cursor="hand2", padx=12, pady=4,
                      command=cmd).pack(side="left", padx=4)
        e.focus_set()
        top.wait_window()
        return result["acct"], result["folder"]

    def _move_to_other_account(self, targets):
        """Right-click → move mail to a folder on ANOTHER account (the main one).
        Picks account + folder, then does the APPEND-then-trash cross move.

        A collapsed conversation goes whole here too — the cross-account move
        is upload-then-trash, and splitting a thread across two accounts is
        the last thing anyone wants."""
        targets, _extra = self._expand_collapsed_threads(targets)
        msgs = [t for t in targets if t.get("uid")]
        if not msgs:
            return
        src = msgs[0].get("account_email", "")
        default = next((a["email"] for a in self._accounts
                        if not a.get("virtual") and a["email"] != src), None)
        acct, folder = self._pick_account_and_folder(
            "Move to another account", default)
        if acct and folder:
            self._activity_log(
                "move-try", account=src,
                subject=(msgs[0].get("subject", "") if len(msgs) == 1 else ""),
                detail=f"asked to move {len(msgs)} message(s) to {folder} on "
                       f"{acct}   (cross-account)")
            self._cross_account_move(msgs, acct, folder)

    def _cross_account_move(self, msgs, target_account, target_folder):
        """Move mail to a folder on a DIFFERENT account. There is no cross-account
        IMAP MOVE, so the raw message is UPLOADED (APPEND) to the target account's
        folder — the ORIGINAL sender is preserved, no forwarding, no spoofing —
        and then trashed from the source account. A real server change on BOTH
        accounts, so Server changes must be on (offered inline)."""
        msgs = [m for m in msgs if m.get("uid")]
        if not msgs:
            return
        tpwd = self._secret_for(target_account)
        if not tpwd:
            messagebox.showwarning(
                "Move to another account",
                f"No stored password for {target_account} — add it under "
                f"Accounts first.", parent=self.root)
            return
        if not self.cfg.get("allow_server_changes", False):
            if not messagebox.askyesno(
                    "Move to another account",
                    f"Copy {len(msgs)} message(s) to “{target_folder}” on "
                    f"{target_account} (original sender kept) and remove them "
                    f"from the source account?\n\nThat changes Gmail, which is "
                    f"currently OFF. Turn Server changes ON and do it?",
                    parent=self.root, default="no"):
                return
            self.cfg["allow_server_changes"] = True
            _save_settings(self.cfg)
            log.info("allow_server_changes enabled from cross-account move")
        # Instant removal from the current view.
        for mm in msgs:
            if mm in self._messages:
                self._messages.remove(mm)
            if mm in self._all_messages:
                self._all_messages.remove(mm)
        self._selected_ids = set()
        self._selected_msg = None
        self._render_msg_list()
        self._show_reading_pane_empty()
        self._flash(f"Moving {len(msgs)} → {target_account} / {target_folder}…")

        payload = list(msgs)

        def worker():
            problems, moved = [], 0
            failed = []            # [(msg, reason)] — logged in done(), DEL 09l
            for mm in payload:
                raw = mm.get("_raw")
                if isinstance(raw, str):
                    raw = raw.encode("utf-8", "replace")
                subj = (mm.get("subject", "") or "")[:40]
                if not raw:
                    why = ("no stored content — open the message once, then "
                           "try again")
                    problems.append(f"No stored content for “{subj}” — open it "
                                    f"once, then try again.")
                    failed.append((mm, why))
                    continue
                # 1. Upload to the target account.
                prob = _imap_append_message(target_account, tpwd, target_folder,
                                            raw)
                if prob:
                    problems.append(f"{subj}: {prob}")
                    failed.append((mm, str(prob)))
                    continue
                # 2. Only AFTER a good upload, remove the original.
                src  = mm.get("account_email", "")
                spwd = self._secret_for(src)
                if spwd and mm.get("uid"):
                    tprob = _imap_trash_message(src, spwd,
                                                mm.get("_folder", "Inbox"),
                                                mm.get("uid"))
                    if tprob:
                        problems.append(f"{subj}: copied, but the original could "
                                        f"not be removed ({tprob}).")
                        failed.append((mm, f"copied to {target_account}, but "
                                           f"the original could not be removed "
                                           f"({tprob})"))
                moved += 1
                log.info("cross-account move: %s → %s/%s", src, target_account,
                         target_folder)

            def done():
                if moved:
                    self._activity_log(
                        "moved", account=target_account,
                        subject=(payload[0].get("subject", "")
                                 if moved == 1 else ""),
                        detail=f"moved {moved} message(s) to {target_folder} on "
                               f"{target_account}   (cross-account, by hand)")
                for mm, why in failed:
                    self._activity_log(
                        "move-failed", account=mm.get("account_email", ""),
                        sender=mm.get("from", ""),
                        subject=mm.get("subject", ""),
                        detail=f"could NOT move to {target_folder} on "
                               f"{target_account} — {why}"[:400])
                if problems:
                    messagebox.showwarning(
                        "Move to another account",
                        f"{moved} moved. Some had problems:\n\n"
                        + "\n".join(f"• {p}" for p in problems[:6])
                        + "\n\nReloading to show what is really there.",
                        parent=self.root)
                    self._refresh_messages()
                else:
                    self._maybe_refresh_counts(force=True)
            try:
                self.root.after(0, done)
            except Exception:
                pass
        threading.Thread(target=worker, daemon=True).start()

    def _untrash_messages(self, targets):
        """Move messages out of the Gmail Trash back into the Inbox (DEL 04t).
        A real server change, so it needs 'server changes' on — offered inline
        if it is off. Instant in the view; the IMAP move runs in the background,
        and a failure reloads the folder so the view always matches Gmail."""
        msgs = [t for t in targets if t.get("uid")]
        if not msgs:
            return
        if not self.cfg.get("allow_server_changes", False):
            ans = messagebox.askyesno(
                "Restore from Trash",
                "Moving mail out of the Trash changes it on Gmail, which is "
                "currently switched off.\n\nTurn on server changes and move "
                f"{len(msgs)} message(s) back to the Inbox?",
                parent=self.root, default="no")
            if not ans:
                return
            self.cfg["allow_server_changes"] = True
            _save_settings(self.cfg)
            log.info("allow_server_changes enabled from Restore-from-Trash")
        elif not messagebox.askyesno(
                "Restore from Trash",
                f"Move {len(msgs)} message(s) out of the Trash and back into "
                f"the Inbox?", parent=self.root, default="yes"):
            return
        # Instant local removal from the Trash view.
        for m in msgs:
            if m in self._messages:
                self._messages.remove(m)
            if m in self._all_messages:
                self._all_messages.remove(m)
        self._selected_ids = set()
        self._selected_msg = None
        self._render_msg_list()
        self._show_reading_pane_empty()
        self._flash(f"Restoring {len(msgs)}…  (updating Gmail in the background)")

        payload = list(msgs)

        def worker():
            problems = []
            for m in payload:
                acct   = m.get("account_email", "")
                pwd    = self._secret_for(acct)
                folder = m.get("_folder", "Trash")
                uid    = m.get("uid")
                if not pwd:
                    problems.append(f"No stored password for {acct}.")
                    continue
                try:
                    prob = _imap_move_message(acct, pwd, folder, uid, "Inbox")
                    if prob:
                        problems.append(prob)
                except Exception as e:
                    problems.append(str(e))
                    log.error("un-trash failed: %s", e)

            def done():
                if problems:
                    messagebox.showwarning(
                        "Restore from Trash",
                        "Some messages could not be restored:\n\n"
                        + "\n".join(f"• {p}" for p in problems[:6])
                        + "\n\nReloading to show what is really on Gmail.",
                        parent=self.root)
                    self._refresh_messages()
                else:
                    self._maybe_refresh_counts(force=True)
            try:
                self.root.after(0, done)
            except Exception:
                pass
        threading.Thread(target=worker, daemon=True).start()

    def _deleted_context_menu(self, event, msg):
        """Right-click menu for a message in the Deleted archive."""
        m = tk.Menu(self.root, tearoff=0, bg=C_BG2, fg=C_FG,
                    activebackground=C_BG4, activeforeground=C_FG)
        m.add_command(label="Open", command=lambda mm=msg: self._focus_message(mm))
        m.add_command(label="Restore to Gmail",
                      command=lambda mm=msg: self._restore_deleted(mm))
        m.add_command(label="Continue (write to sender)",
                      command=lambda mm=msg: self._continue_deleted(mm))
        m.add_separator()
        m.add_command(label="Remove this local copy…",
                      command=lambda mm=msg: self._remove_deleted(mm))
        m.add_command(label="Empty the Deleted archive…",
                      command=self._empty_deleted)
        m.add_command(label="Keep deleted copies for…  (days)",
                      command=self._set_deleted_keep_days)
        try:
            m.tk_popup(event.x_root, event.y_root)
        finally:
            m.grab_release()

    def _focus_message(self, msg):
        """Make one message the single selection and show it in the reading
        pane, without the click-side effects (used by the right-click menu)."""
        self._selected_ids = {msg.get("id")}
        self._selected_msg = msg
        self._render_msg_list()
        self._repaint_selection()
        self._update_bulk_bar()
        self._show_message_in_reading_pane(msg)

    # ── Recipient lists: fold, and per-sender "never show" ──────────────────
    def _my_addresses(self) -> set:
        """Every address that is one of YOUR accounts, lower-cased."""
        return {(a.get("email") or "").strip().lower()
                for a in getattr(self, "_accounts", []) if a.get("email")}

    def _recipients_menu(self, event, sender, addrs=None, caption=""):
        """Right-click a To:/Cc: line. The per-sender switch is here rather
        than in a settings page because this is the moment you want it: you
        are looking at the wall of addresses that annoyed you.

        Copying a RECIPIENT lives here too (Issu 2026-08-29: "jag kan bara
        copy senders adress… jag kanske vill kopiera en av mottagarna"). Your
        own address is offered as well and marked "(you)" — sometimes the
        address you need is the alias of yours the mail was actually sent to,
        which is not necessarily the account you are reading it in."""
        lst = [(s or "").lower()
               for s in (self.cfg.get("hide_recipients_from") or [])]
        m = tk.Menu(self.root, tearoff=0, bg=C_BG2, fg=C_FG,
                    activebackground=C_BG4, activeforeground=C_FG)

        addrs = list(addrs or [])
        if addrs:
            mine = self._my_addresses()
            cap = (caption or "").rstrip(":") or "recipient"
            # A short list goes straight on the menu — one click, no hunting.
            # A long one goes in a submenu, because a fifty-name circular would
            # otherwise push every other command off the bottom of the screen.
            if len(addrs) <= 12:
                target = m
            else:
                target = tk.Menu(m, tearoff=0, bg=C_BG2, fg=C_FG,
                                 activebackground=C_BG4, activeforeground=C_FG)
                m.add_cascade(label=f"📋  Copy one of the {len(addrs)} "
                                    f"{cap} addresses", menu=target)
            for a in addrs:
                you = "   (you)" if a.strip().lower() in mine else ""
                target.add_command(
                    label=f"📋  Copy  {a}{you}",
                    command=lambda x=a: self._copy_to_clipboard(
                        x, "Address copied"))
            if len(addrs) > 1:
                m.add_command(
                    label=f"📋  Copy all {len(addrs)} {cap} addresses",
                    command=lambda x=list(addrs): self._copy_to_clipboard(
                        ", ".join(x), f"{len(x)} addresses copied"))
            m.add_separator()

        if sender and sender in lst:
            m.add_command(label=f'Show recipients from {sender} again',
                          command=lambda: self._toggle_hide_recipients(sender))
        elif sender:
            m.add_command(label=f'Never show recipients from {sender}',
                          command=lambda: self._toggle_hide_recipients(sender))
        m.add_separator()
        cur = int(self.cfg.get("recipients_max", 5) or 0)
        for n in (0, 3, 5, 10, 25):
            label = ("Always show every recipient" if n == 0
                     else f"Fold the list when there are more than {n}")
            m.add_command(label=("• " if n == cur else "   ") + label,
                          command=lambda k=n: self._set_recipients_max(k))
        try:
            m.tk_popup(event.x_root, event.y_root)
        finally:
            m.grab_release()

    def _toggle_hide_recipients(self, sender):
        lst = [(s or "").lower()
               for s in (self.cfg.get("hide_recipients_from") or [])]
        sender = (sender or "").lower()
        if not sender:
            return
        if sender in lst:
            lst.remove(sender)
            self._flash(f"Recipients from {sender} are shown again")
        else:
            lst.append(sender)
            self._flash(f"Recipients from {sender} will stay hidden")
        self.cfg["hide_recipients_from"] = sorted(set(lst))
        _save_settings(self.cfg)
        if self._selected_msg is not None:
            self._show_message_in_reading_pane(self._selected_msg)

    def _set_recipients_max(self, n):
        self.cfg["recipients_max"] = int(n)
        _save_settings(self.cfg)
        self._flash("Every recipient is shown" if not n
                    else f"Recipient lists fold above {n}")
        if self._selected_msg is not None:
            self._show_message_in_reading_pane(self._selected_msg)

    # ── "Where is this message?" (Issu 2026-08-08) ──────────────────────────
    def _where_is_dialog(self, msg):
        """Find every copy of one message, in every folder of every account.

        Gmail does not put a message IN a folder — it hangs labels on it — so
        "where is it" usually has more than one honest answer, and a message
        that has also been copied to another account has answers in two
        mailboxes at once. Both are shown, with the labels, and each row opens
        that copy.

        Nothing here changes anything: it is a read-only look."""
        mid = (msg.get("_message_id") or "").strip()
        top = self._dialog_shell("Where is this message?", 760, 560)
        tk.Label(top, text="🧭  Where is this message?", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold"), pady=(8)).pack()
        tk.Label(top, text=f"“{msg.get('subject','(no subject)')[:70]}”\n"
                           f"from {msg.get('from_name') or msg.get('from','')}",
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 9),
                 justify="center").pack(pady=(0, 4))

        body = tk.Frame(top, bg=C_BG3)
        body.pack(fill="both", expand=True, padx=14, pady=6)
        sb = tk.Scrollbar(body, bg=C_BG3, troughcolor=C_BG1)
        sb.pack(side="right", fill="y")
        txt = tk.Text(body, bg=C_BG2, fg=C_FG, relief="flat", wrap="word",
                      font=("Segoe UI", 9), padx=10, pady=8,
                      yscrollcommand=sb.set,
                      insertofftime=0, insertontime=9999999)
        no_blink(txt)
        sb.configure(command=txt.yview)
        txt.pack(fill="both", expand=True)
        _bind_mousewheel(txt, txt)
        txt.tag_configure("acct", foreground=C_ACCENT,
                          font=("Segoe UI", 10, "bold"))
        txt.tag_configure("dim", foreground=C_FG_DIM)
        txt.tag_configure("hit", foreground="#a8e6a8")

        if not mid:
            txt.insert("end", "  This message has no Message-ID, so it cannot "
                              "be traced. (Locally written notes have none.)")
            txt.configure(state="disabled")
            return

        txt.insert("end", "  Looking…\n", "dim")
        txt.configure(state="disabled")

        results = {}
        accounts = [a for a in self._accounts if not a.get("virtual")]

        def render():
            txt.configure(state="normal")
            txt.delete("1.0", "end")
            total = sum(len(v) for v in results.values())
            if not results:
                txt.insert("end", "  Looking…\n", "dim")
            for email in sorted(results):
                places = results[email]
                txt.insert("end", f"\n  {email}\n", "acct")
                if not places:
                    txt.insert("end", "      not in this account\n", "dim")
                    continue
                for p in places:
                    txt.insert("end", f"      ✓  {p['folder']}",
                               "hit")
                    txt.insert("end", f"   (uid {p['uid']})\n", "dim")
                    if p.get("labels"):
                        txt.insert("end",
                                   f"          labels: "
                                   f"{', '.join(p['labels'])}\n", "dim")
            if results and total == 0:
                txt.insert("end",
                           "\n  Not found anywhere. It may have been deleted "
                           "for good, or it lives in an account that is not "
                           "set up here.\n", "dim")
            elif total:
                txt.insert("end",
                           f"\n  {total} copy/copies found. On Gmail one "
                           f"message wears several labels, so appearing in "
                           f"more than one place is normal — it is still one "
                           f"message.\n", "dim")
            txt.configure(state="disabled")

        def worker(a):
            email = a["email"]
            pwd = self._secret_for(email)
            places = []
            if pwd:
                try:
                    places = _locate_message(email, pwd, mid)
                except Exception as e:
                    log.warning("locate failed for %s: %s", email, e)

            def done():
                results[email] = places
                try:
                    if txt.winfo_exists():
                        render()
                except Exception:
                    pass
            try:
                self.root.after(0, done)
            except Exception:
                pass

        for a in accounts:
            threading.Thread(target=worker, args=(a,), daemon=True).start()

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(fill="x", padx=14, pady=(0, 12))
        tk.Button(btns, text="Close", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=14, pady=4, command=top.destroy).pack(side="left")
        tk.Label(btns, text="  Read-only — this only looks.",
                 bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8, "italic")).pack(side="left", padx=8)

    def _ctx_reply(self, msg):
        self._focus_message(msg)
        self._reply()

    def _ctx_forward(self, msg):
        self._focus_message(msg)
        self._forward()

    def _ctx_mark_read(self, targets, read):
        for t in targets:
            was = bool(t.get("unread"))
            t["unread"] = (not read)
            # Remember a by-hand "unread" so its next open uses the longer
            # reread dwell — and so it is never pushed to Gmail as unread.
            t["_manually_unread"] = (not read)
            if read and was and not t.get("_always_unread"):
                self._badge_adjust(t, -1)
            elif (not read) and not was:
                self._badge_adjust(t, +1)
        if read:
            self._mark_read_on_server_async(targets)   # \Seen only, never unset
        # Recolour just the affected rows in place — no full rebuild, no flash.
        # Fall back to a full render only if a row wasn't found (e.g. filtered).
        if not all(self._repaint_row_read(t) for t in targets):
            self._render_msg_list()
        self._repaint_selection()
        self._repaint_badges()
        self._flash(f"{len(targets)} marked as "
                    f"{'read' if read else 'unread'}"
                    f"{'' if read else ' (local only)'}")

    def _ctx_star(self, targets, on):
        for t in targets:
            t["starred"] = bool(on)
        self._render_msg_list()
        self._repaint_selection()

    def _ctx_spam(self, targets, on):
        if not on:
            self._ctx_not_spam(targets)
            return
        for t in targets:
            self._blocklist_add("spam", t, reason="right-click")
            t["spam"] = True
        self._render_msg_list()
        self._repaint_selection()
        self._flash("Marked as spam")

    def _ctx_not_spam(self, targets):
        """"Not spam (this sender)" (Issu 2026-08-10). Two things happen:

        1) The sender is removed from the local "spam" list (blocklist.json),
           so _is_local_spam() stops re-flagging their mail on every future
           render/refresh — the whole point being that you do NOT have to
           repeat this for every message the same person sends. This part
           already worked before this fix.

        2) NEW: any of the targets that are really sitting in Gmail's Spam
           folder are now actually moved back to the Inbox on the server —
           previously this only cleared the local flag and left the mail
           sitting in Spam, which is not what "not spam" should mean. See
           _restore_from_spam() for the move itself.

        A message that was only ever flagged spam locally (still sitting in
        the Inbox, e.g. via "Just flag as spam here") has nothing to move —
        only real Spam-folder mail is restored."""
        targets = list(targets)
        if not targets:
            return
        for t in targets:
            self._blocklist_remove_matching("spam", t)
            t["spam"] = False

        to_restore = [t for t in targets
                      if t.get("_folder") == "Spam" and t.get("uid")]
        self._render_msg_list()
        self._repaint_selection()
        if to_restore:
            self._flash(f"No longer spam — moving {len(to_restore)} back "
                        f"to the Inbox…")
            self._restore_from_spam(to_restore)
        else:
            self._flash("No longer spam")

    def _restore_from_spam(self, targets):
        """Move message(s) out of Gmail's Spam folder back into the Inbox, and
        keep them NOT READ there (Issu 2026-08-10: "Mark as not spam" should
        put the mail back in the Inbox as not-read).

        The "not read" part is deliberately a LOCAL flag only — exactly like
        every other "mark unread" in this program (see _ctx_mark_read): this
        program only ever ADDS \\Seen on the server, never removes it, so
        that a local "unread" can't make Gmail/your phone re-ping for a
        message you may already have opened here. If the message truly never
        had \\Seen set on Gmail (the normal case for spam nobody opened), the
        Inbox copy will show as unread there too, automatically."""
        msgs = [t for t in targets if t.get("uid")]
        if not msgs:
            return
        if not self.cfg.get("allow_server_changes", False):
            if not messagebox.askyesno(
                    "Not spam",
                    "Moving mail out of Spam changes it on Gmail, which is "
                    "currently switched off.\n\nTurn on server changes and "
                    f"move {len(msgs)} message(s) back to the Inbox?",
                    parent=self.root, default="yes"):
                return
            self.cfg["allow_server_changes"] = True
            _save_settings(self.cfg)
            log.info("allow_server_changes enabled from Not-spam")

        # Instant local removal from the current (Spam) view; mark unread
        # locally right away so the Inbox shows it as not-read immediately,
        # without waiting for the background move to finish.
        for m in msgs:
            m["unread"] = True
            if m in self._messages:
                self._messages.remove(m)
            if m in self._all_messages:
                self._all_messages.remove(m)
        self._selected_ids = set()
        self._selected_msg = None
        self._render_msg_list()
        self._show_reading_pane_empty()

        payload = list(msgs)

        def worker():
            problems = []
            for m in payload:
                acct   = m.get("account_email", "")
                pwd    = self._secret_for(acct)
                folder = m.get("_folder", "Spam")
                uid    = m.get("uid")
                if not pwd:
                    problems.append(f"No stored password for {acct}.")
                    continue
                try:
                    prob = _imap_move_message(acct, pwd, folder, uid, "Inbox")
                    if prob:
                        problems.append(prob)
                    else:
                        log.info("not-spam: moved uid=%s Spam → Inbox", uid)
                except Exception as e:
                    problems.append(str(e))
                    log.error("not-spam restore failed: %s", e)

            def done():
                if problems:
                    messagebox.showwarning(
                        "Not spam",
                        "Some messages could not be moved back to the "
                        "Inbox:\n\n"
                        + "\n".join(f"• {p}" for p in problems[:6])
                        + "\n\nReloading to show what is really on Gmail.",
                        parent=self.root)
                    self._refresh_messages()
                else:
                    self._maybe_refresh_counts(force=True)
            try:
                self.root.after(0, done)
            except Exception:
                pass
        threading.Thread(target=worker, daemon=True).start()

    # ── Spam variants (DEL 04A2) — Issu's internal / external / unsubscribe ────
    def _spam_gmail_folder(self, msg):
        """The LOGICAL "Spam" name — _imap_move_message maps it to the account's
        real Spam/Junk mailbox via IMAP SPECIAL-USE, so it works even when Gmail
        localizes it (e.g. Swedish "[Gmail]/Skräppost")."""
        return "Spam"

    def _spam_internal(self, targets):
        """"Spam intern" (Issu): I say it's junk. Block the sender so future mail
        is caught, mark it read, and delete it from everywhere — to the Gmail
        Trash, so a hidden local copy is still kept and it can be undone. NOT
        reported to Gmail's own spam filter (that is "external")."""
        targets = list(targets)
        if not targets:
            return
        for t in targets:
            self._blocklist_add("spam", t, reason="spam-internal")
            t["spam"] = True
            if not t.get("_always_unread"):
                t["unread"] = False
        # Delete from everywhere = the normal delete path (Gmail Trash + hidden
        # Deleted copy + instant removal here, with Undo).
        self._selected_ids = {t.get("id") for t in targets}
        self._bulk_delete()

    def _spam_external(self, targets):
        """"Spam externt" (Issu): report to Gmail. Move the mail into Gmail's own
        Spam folder so Gmail's filter LEARNS from it, like clicking Report spam
        in Gmail. A real server change — offered inline if it is off."""
        msgs = [t for t in targets if t.get("uid")]
        if not msgs:
            if self._demo_mode:
                messagebox.showinfo(
                    "Report spam",
                    "This is demo mail. Add your Gmail account to report real "
                    "spam to Gmail.", parent=self.root)
            return
        for t in msgs:
            self._blocklist_add("spam", t, reason="spam-report")
            t["spam"] = True
        self._move_selected_to(msgs, self._spam_gmail_folder(msgs[0]))

    def _spam_unsubscribe(self, targets):
        """"Spam unsubscribe" (Issu): internal spam PLUS unsubscribe. Opens the
        unsubscribe helper for the sender (which asks before sending/opening
        anything), then does the internal-spam clean-up."""
        targets = list(targets)
        if not targets:
            return
        lead = targets[0]
        unsub = _find_unsubscribe(lead)
        if unsub.get("mailto") or unsub.get("http"):
            # The dialog asks before sending an e-mail / opening a page.
            self._unsubscribe_dialog(lead)
        else:
            messagebox.showinfo(
                "Unsubscribe",
                "This message has no unsubscribe link (no List-Unsubscribe "
                "header). Doing the internal-spam clean-up only.",
                parent=self.root)
        self._spam_internal(targets)

    def _ctx_toggle_always_unread(self, msg):
        if _is_always_unread(self._blocklist_store, msg):
            self._blocklist_remove_matching("always_unread", msg)
            msg["_always_unread"] = False
            self._flash("Sender no longer kept unread")
        else:
            self._blocklist_add("always_unread", msg, reason="right-click")
            if msg.get("_folder") == "Inbox":
                msg["unread"] = True
                msg["_always_unread"] = True
            self._flash("Sender kept unread while in Inbox")
        self._render_msg_list()
        self._repaint_selection()

    def _ctx_snooze(self, msg):
        self._selected_msg = msg
        self._snooze_selected()

    def _ctx_to_notes(self, targets):
        n = 0
        for t in targets:
            try:
                self._save_message_as_note(t)
                n += 1
            except Exception as e:
                log.warning("context save-to-notes failed: %s", e)
        self._flash(f"{n} saved to Notes")

    def _ctx_delete(self, targets):
        self._selected_ids = {t.get("id") for t in targets}
        self._bulk_delete()

    # ── Local sender lists (spam / always-unread) ──────────────────────────────
    def _blocklist_add(self, key, msg, reason=""):
        email = (msg.get("from") or "").strip().lower()
        if not email:
            return
        lst = self._blocklist_store.setdefault(key, [])
        if not any((e.get("match") or "").strip().lower() == email for e in lst):
            lst.append({"match": email, "added": _now_iso(), "reason": reason})
            _save_blocklist(self._blocklist_store)

    def _blocklist_remove_matching(self, key, msg):
        hay = (msg.get("from", "") + " " + msg.get("from_name", "")).lower()
        lst = self._blocklist_store.get(key, [])
        kept = [e for e in lst
                if not ((e.get("match") or "").strip()
                        and (e.get("match") or "").strip().lower() in hay)]
        self._blocklist_store[key] = kept
        _save_blocklist(self._blocklist_store)

    def _select_msg(self, msg, row_widgets, ctrl=False, shift=False):
        """Select one message, or extend a multi-selection (DEL 09e).

        Plain click behaves exactly as before — one message, opened in the
        reading pane. Ctrl and Shift build a set instead, and the bulk action
        bar appears as soon as more than one row is ticked."""
        ix = self._msg_index(msg)
        # Clicking a message hands the arrow keys to the RIGHT pane (DEL 09f).
        self._nav_zone = "messages"
        self._paint_nav_zone()

        if ctrl:
            mid = msg.get("id")
            if mid in self._selected_ids:
                self._selected_ids.discard(mid)
            else:
                self._selected_ids.add(mid)
            self._last_click_ix = ix
        elif shift and self._last_click_ix is not None and ix is not None:
            lo, hi = sorted((self._last_click_ix, ix))
            for m in self._messages[lo:hi + 1]:
                self._selected_ids.add(m.get("id"))
        else:
            self._selected_ids = {msg.get("id")}
            self._last_click_ix = ix

        self._selected_msg = msg
        if not (ctrl or shift):
            # Opening one marks it read — but only after you have kept it open
            # for your chosen dwell (default 1 s), so scrolling past does not
            # read it. A message you flagged unread by hand needs the longer
            # reread dwell. See _schedule_read / _dwell_mark_read.
            self._schedule_read(msg)
        # Just recolour rows for the new selection — a full _render_msg_list()
        # here rebuilt the whole list on every click, which is a flash for
        # nothing (Issu is sensitive to it). _repaint_selection already sets
        # each row to its selected/base colour.
        self._repaint_selection()
        self._update_bulk_bar()
        # With several ticked, the reading pane would just be noise — keep
        # showing whichever one was clicked last.
        self._show_message_in_reading_pane(msg)
        # "Always open HTML" (Issu 2026-08-01): only on a real single click, so
        # background refreshes and multi-select never pop a window.
        if (not (ctrl or shift)
                and self.cfg.get("always_html_view", False)
                and (msg.get("_html") or "").strip()):
            self._show_html_popup(msg, auto=True)

    # ── Keyboard navigation of the message list (Issu 2026-08-02) ──────────────
    def _nav_message(self, delta, extend=False):
        """Move the selection up (delta=-1) or down (+1) the VISIBLE rows.
        With extend=True (Shift held) the newly-reached row is ADDED to the
        selection, so Shift+Up/Down grows a multi-selection — the thing that
        "kunde inte hålla inne SHIFT och gå upp/ned". Returns "break" so the
        arrow key does not also scroll the window twice."""
        rows = getattr(self, "_row_frames", None) or []
        if not rows:
            return "break"
        self._nav_zone = "messages"
        self._paint_nav_zone()
        # Where are we now? Match the currently-open message to its row.
        self._resync_selected_msg()
        cur = None
        if self._selected_msg is not None:
            for i, e in enumerate(rows):
                if e[0] is self._selected_msg:
                    cur = i
                    break
        if cur is None:
            cur = 0 if delta > 0 else len(rows) - 1
        else:
            cur = max(0, min(len(rows) - 1, cur + delta))
        target = rows[cur][0]
        if extend:
            # Shift+arrow is a RANGE from the anchor, rebuilt every press — so
            # turning round and coming back shrinks the selection again instead
            # of leaving a trail of ticked rows behind (Issu 2026-08-03).
            anchor = self._last_click_ix
            if anchor is None:
                anchor = self._msg_index(self._selected_msg)
                self._last_click_ix = anchor
            ix = self._msg_index(target)
            if anchor is not None and ix is not None:
                lo, hi = sorted((anchor, ix))
                self._selected_ids = {m.get("id")
                                      for m in self._messages[lo:hi + 1]}
            else:
                self._selected_ids = {target.get("id")}
            self._selected_msg = target
            self._repaint_selection()
            self._update_bulk_bar()
            self._show_message_in_reading_pane(target)
        else:
            self._select_msg(target, None)
        # Keep one row of headroom in the direction of travel, so the next
        # message you would reach is always on screen before you take it.
        self._scroll_msg_into_view(target, lookahead=delta)
        return "break"

    def _scroll_msg_into_view(self, msg, lookahead=0):
        """Scroll the message list so `msg`'s row is visible after a keyboard
        move — and, with `lookahead`, so the NEXT row in the direction you are
        travelling is visible too.

        That second part is the point (Issu 2026-08-03): selecting with
        Shift+arrow against the edge of the list means the row you are about to
        take is off screen, so you tick something you never saw and have to
        untick it again. One row of headroom in the direction of travel means
        you can always see what you are about to reach.

        Silent if anything is not laid out yet."""
        try:
            rows = getattr(self, "_row_frames", None) or []
            idx = next((i for i, e in enumerate(rows) if e[0] is msg), None)
            if idx is None:
                return
            wanted = [idx]
            if lookahead:
                peek = idx + (1 if lookahead > 0 else -1)
                if 0 <= peek < len(rows):
                    wanted.append(peek)

            def _span(i):
                e = rows[i]
                if not e[1]:
                    return None
                w = e[1][0]
                t = w.winfo_y()
                return t, t + max(1, w.winfo_height())

            self.ml_canvas.update_idletasks()
            spans = [s for s in (_span(i) for i in wanted) if s]
            if not spans:
                return
            top = min(s[0] for s in spans)
            bot = max(s[1] for s in spans)
            total  = max(1, self.ml_inner.winfo_height())
            canv_h = max(1, self.ml_canvas.winfo_height())
            y0 = self.ml_canvas.canvasy(0)
            # If both rows cannot fit at once (a very short list pane), the
            # SELECTED row wins — never scroll the thing you just picked away.
            if bot - top > canv_h:
                sel = _span(idx)
                top, bot = sel if sel else (top, bot)
            if top < y0:
                self.ml_canvas.yview_moveto(max(0.0, top / total))
            elif bot > y0 + canv_h:
                self.ml_canvas.yview_moveto(max(0.0, (bot - canv_h) / total))
        except Exception:
            pass

    # ── Mark-read dwell (DEL 09e) ──────────────────────────────────────────────
    def _cancel_read_timer(self):
        if self._read_timer_id is not None:
            try:
                self.root.after_cancel(self._read_timer_id)
            except Exception:
                pass
        self._read_timer_id  = None
        self._read_timer_msg = None

    def _schedule_read(self, msg):
        """Arm the "this becomes read after a dwell" timer for one message.
        A message flagged unread by hand uses the longer reread dwell."""
        self._cancel_read_timer()
        if not self.cfg.get("mark_read_enabled", True):
            self._apply_read(msg)
            return
        secs = (int(self.cfg.get("reread_seconds", 5) or 0)
                if msg.get("_manually_unread")
                else int(self.cfg.get("mark_read_seconds", 1) or 0))
        if secs <= 0:
            self._apply_read(msg)
            return
        self._read_timer_msg = msg
        self._read_timer_id  = self.root.after(
            secs * 1000, lambda m=msg: self._dwell_fire(m))

    def _dwell_fire(self, msg):
        self._read_timer_id  = None
        self._read_timer_msg = None
        # Only if you are STILL on this message — moving away cancels the read.
        if msg is self._selected_msg:
            self._apply_read(msg)

    def _apply_read(self, msg):
        """Mark a message read: locally (unless its sender is kept unread) and,
        one-directionally, on Gmail."""
        was_unread = bool(msg.get("unread") or msg.get("_manually_unread"))
        if not msg.get("_always_unread"):
            msg["unread"] = False
        msg["_manually_unread"] = False
        self._mark_read_on_server_async([msg])
        if was_unread:
            if not msg.get("_always_unread"):
                self._badge_adjust(msg, -1)   # instant "(1)" → "(0)"
            # Update JUST this row's colours/font in place — no full list
            # rebuild, so there is no flash when a mail turns read (DEL 04v).
            # Issu is sensitive to blinking; the whole-list re-render was the
            # visible flicker here.
            if not self._repaint_row_read(msg):
                self._render_msg_list()       # fallback if the row wasn't found
            self._repaint_badges()

    def _repaint_row_read(self, msg) -> bool:
        """Recolour one already-drawn row to match its current read/unread
        state, in place. Returns True if the row was found and updated."""
        entry = next((e for e in self._row_frames if e[0] is msg), None)
        if entry is None:
            return False
        row_widgets, meta = entry[1], entry[3]
        new_bg = self._row_bg(msg)
        entry[2] = new_bg                     # keep hover/selection in sync
        selected = msg.get("id") in self._selected_ids
        shown_bg = C_MSG_SEL if selected else new_bg
        for w in row_widgets:
            try:
                w.configure(bg=shown_bg)
            except Exception:
                pass
        from_font = (("Segoe UI", 9, "bold") if msg.get("unread")
                     else ("Segoe UI", 9))
        from_fg   = C_FG_UNRD if msg.get("unread") else C_FG
        subj = meta.get("subj")
        if subj is not None:
            try:
                subj.configure(
                    text=self._subject_text(msg, meta.get("indent", False),
                                            meta.get("thread_count", 0)),
                    fg=from_fg, font=from_font, bg=shown_bg)
            except Exception:
                pass
        corr = meta.get("corr")
        mode = meta.get("corr_mode", "plain")
        if corr is not None and mode != "contact":
            try:
                if mode == "acct":
                    corr.configure(font=from_font, bg=shown_bg)   # keep acct fg
                else:
                    corr.configure(font=from_font, fg=from_fg, bg=shown_bg)
            except Exception:
                pass
        return True

    def _mark_read_on_server_async(self, msgs):
        """Add \\Seen on Gmail for these messages (never removes it). No-op
        unless Server changes AND mark-read-on-server are both on."""
        if (self._demo_mode
                or not self.cfg.get("mark_read_on_server", True)
                or not self.cfg.get("allow_server_changes", False)):
            return
        groups = {}
        for m in msgs:
            uid  = m.get("uid")
            acct = m.get("account_email", "")
            fold = m.get("_folder", "Inbox")
            if uid and acct:
                groups.setdefault((acct, fold), []).append(uid)
        if not groups:
            return

        def worker():
            for (acct, fold), uids in groups.items():
                try:
                    pwd = self._secret_for(acct)
                    if pwd:
                        _imap_mark_seen(acct, pwd, fold, uids)
                except Exception as e:
                    log.warning("mark-seen on server failed for %s: %s", acct, e)
        threading.Thread(target=worker, daemon=True).start()

    def _carry_selection(self, old_selected, new_messages):
        """Re-point ticked rows at the refreshed message objects.

        A fetch hands back BRAND-NEW dicts, so every id in _selected_ids
        belongs to an object that is about to be thrown away. Matching them up
        again takes two passes, in this order:

          1. _msg_key — Message-ID plus account: the same mail, same place.
          2. _reply_key — the bare Message-ID. A message a rule MOVED keeps its
             Message-ID but gets a NEW UID, and the id IS the UID, so without
             this step a tick would quietly disappear the moment one of your
             own rules filed the mail (the same renumbering _apply_messages
             already handles for the message you have OPEN).

        Anything that finds no match has genuinely left the list — deleted,
        moved away, filtered out — and its tick goes with it."""
        if not old_selected:
            return set()
        by_key, by_reply = {}, {}
        for m in new_messages:
            try:
                by_key.setdefault(_msg_key(m), m)
                rk = _reply_key(m)
                if rk:
                    by_reply.setdefault(rk, m)
            except Exception:
                continue
        out = set()
        for old in old_selected:
            hit = None
            try:
                hit = by_key.get(_msg_key(old))
                if hit is None:
                    rk = _reply_key(old)
                    if rk:
                        hit = by_reply.get(rk)
            except Exception:
                hit = None
            if hit is not None:
                out.add(hit.get("id"))
        return out

    def _repaint_selection(self):
        """Colour every row according to the current selection."""
        for entry in self._row_frames:
            m, rw, orig_bg = entry[0], entry[1], entry[2]
            if m.get("id") in self._selected_ids:
                colour = C_MSG_SEL
            else:
                colour = orig_bg
            for w in rw:
                try:
                    w.configure(bg=colour)
                except Exception:
                    pass

    def _selected_messages(self):
        """The message dicts currently ticked, in list order.

        The LITERAL ticked rows — what selection painting, the "N selected"
        count and the merge picker need. Anything that ACTS on mail should
        use _selected_for_action() instead."""
        return [m for m in self._messages if m.get("id") in self._selected_ids]

    def _selected_for_action(self):
        """The ticked rows with every COLLAPSED conversation opened out.

        Issu 2026-09-01: "allt som är collapsed ska behandlas med samma regel.
        Vill jag särskilja så får jag expanda." A closed row shows the newest
        message and a count — it IS the conversation — so tag / read / notes /
        archive / spam / move / delete all take the whole thing. Open the row
        with + and each message gets its own row again, and then an action on
        one of those touches only that one.

        Two deliberate exceptions keep using the literal rows:
        _bulk_make_junk_filter (it builds a rule out of SENDER addresses, and
        a conversation contains the other party AND you — junking your own
        address would be a real foot-gun) and the merge commands (merging is
        about rows; a collapsed conversation is already merged)."""
        msgs, _extra = self._expand_collapsed_threads(self._selected_messages())
        return msgs

    def _select_all(self, on=True):
        self._selected_ids = ({m.get("id") for m in self._messages} if on
                              else set())
        self._render_msg_list()
        self._repaint_selection()
        self._update_bulk_bar()

    def _on_rp_canvas_configure(self, event):
        self.rp_canvas.itemconfig(self.rp_cwin, width=event.width)
        # The pane's real width can settle AFTER the first render — window
        # resize, sidebar toggle, splitter drag, or just initial layout — and
        # each per-message Text's height was fitted to the wrapped-line count
        # at whatever width existed at THAT moment. Left stale, a later
        # narrower width re-wraps the text to MORE lines than the box still
        # shows, silently clipping the bottom of the message (Issu
        # 2026-08-05: "det visas inte hela meddelandet... förr än jag kör
        # reply" — Reply's own Text isn't height-fitted this way, so it
        # always showed everything). Debounced so a window drag doesn't
        # re-measure on every pixel.
        if getattr(self, "_rp_refit_after", None):
            try:
                self.rp_canvas.after_cancel(self._rp_refit_after)
            except Exception:
                pass
        self._rp_refit_after = self.rp_canvas.after(120, self._refit_rp_text_heights)

    def _refit_rp_text_heights(self):
        self._rp_refit_after = None
        for t in getattr(self, "_rp_texts", []):
            try:
                if not t.winfo_exists():
                    continue
                n = self._text_displaylines(t)
                if n:
                    t.configure(height=n)
            except Exception:
                pass
        try:
            self.rp_canvas.configure(scrollregion=self.rp_canvas.bbox("all"))
        except Exception:
            pass

    def _ensure_full_body(self, msg):
        """If `msg` is a header-only stub (its folder was listed but this
        particular message was never opened before), fetch its real body in
        the background and splice the result into place once it lands — the
        moment you open ANY message it looks and behaves exactly like it
        always did. Only the folder LIST got faster; nothing about reading
        a message changed except that the very first open of a given
        message does one extra small fetch (Issu 2026-08-06)."""
        if msg.get("_body_loaded", True) or self._demo_mode:
            return
        uid, account, folder = msg.get("uid"), msg.get("account_email"), msg.get("_folder")
        if not uid or not account or not folder:
            return
        # Already trying — a re-render must not start a second fetch of the
        # same message on top of the first.
        if msg.get("_body_fetching"):
            return
        pwd = self._secret_for(account)
        if not pwd:
            msg["_body_error"] = ("No stored password for this account, so the "
                                  "message cannot be downloaded.")
            return
        msg["_body_fetching"] = True
        msg.pop("_body_error", None)
        mid = msg.get("_message_id", "")

        def worker():
            err = ""
            moved_to = ""
            try:
                built = _fetch_single_full_body(account, pwd, folder, uid)
            except Exception as e:
                log.warning("Lazy full-body fetch failed for %s/%s uid %s: %s",
                           account, folder, uid, e)
                built, err = None, str(e)

            # ── It was not there. Where did it go? (Issu 2026-08-07) ─────────
            # A filter moving the message is the normal reason, not an
            # exception — so FOLLOW it instead of leaving the pane on
            # "Loading" forever, which is what used to happen.
            if built is None and mid:
                try:
                    new_folder, new_uid = _find_message_anywhere(
                        account, pwd, mid)
                    if new_folder and new_uid:
                        built = _fetch_single_full_body(
                            account, pwd, new_folder, new_uid)
                        if built is not None:
                            moved_to = new_folder
                            err = ""
                except Exception as e:
                    log.warning("Could not follow moved message %s: %s", mid, e)
                    err = err or str(e)

            def done():
                msg["_body_fetching"] = False
                if built is None:
                    # Say so, in the pane, with a button — never an endless
                    # "Loading…" with no way forward.
                    msg["_body_error"] = (
                        err or "This message is no longer where it was listed "
                               "— it was probably moved or deleted somewhere "
                               "else (another client, or one of your own "
                               "filters).")
                    sel = self._selected_msg
                    if (sel is not None and sel.get("uid") == uid
                            and sel.get("account_email") == account
                            and sel.get("_folder") == folder):
                        self._show_message_in_reading_pane(msg)
                    return
                # ── Update the dict IN PLACE, never replace it ───────────────
                # This used to do `lst[i] = built`, which throws the original
                # dict away and puts a different object in the list. Anything
                # already holding the old one — a Reply or Smart Reply window
                # opened a second earlier — was left holding a header-only stub
                # with body == "" for ever, and quietly sent a reply with NO
                # original text in it.
                #
                # That is Issu's 2026-08-08 report ("när jag svarar till en
                # person och lägger till annan också, så kommer första
                # personens originalmeddelande inte med"): it has nothing to do
                # with the second recipient, it is a race with the on-demand
                # body fetch. Updating the same dict means every window that
                # already has it gets the real body the moment it lands.
                target = None
                for lst in (self._all_messages, self._messages):
                    for i, m in enumerate(lst):
                        if (m.get("uid") == uid and m.get("account_email") == account
                                and m.get("_folder") == folder):
                            m.update(built)
                            target = m
                sel = self._selected_msg
                if (sel is not None and sel.get("uid") == uid
                        and sel.get("account_email") == account
                        and sel.get("_folder") == folder):
                    sel.update(built)
                    target = sel
                if target is None:
                    # Not in any list any more (folder changed under us) — at
                    # least fill in the dict we were asked about.
                    msg.update(built)
                    target = msg
                if (sel is not None and sel is target):
                    self._show_message_in_reading_pane(target)
                    if moved_to:
                        # Not a silent rescue: knowing the message MOVED, and
                        # where to, is the whole answer to "why does it keep
                        # disappearing on me".
                        self._flash(f"That message had been moved — opened it "
                                    f"from {moved_to}")
                        self._activity_log(
                            "moved", account=account,
                            subject=msg.get("subject", ""),
                            detail=f"followed to {moved_to} when opening it "
                                   f"(it was listed under {folder})")
            try:
                self.root.after(0, done)
            except Exception:
                pass   # window closed mid-fetch

        threading.Thread(target=worker, daemon=True).start()

    def _retry_body_fetch(self, msg):
        """"Try again" on the "could not open this message" panel — clears the
        error and starts the download over, following the message if a filter
        has moved it in the meantime (Issu 2026-08-07)."""
        msg.pop("_body_error", None)
        msg["_body_fetching"] = False
        self._show_message_in_reading_pane(msg)

    def _toggle_fix_encoding(self):
        """Turn the åäö repair on or off. Shared by the Tools menu and the
        tick-box next to "Always (open HTML automatically)" — ONE variable
        drives both, so they can never disagree."""
        on = bool(self._fix_enc_var.get())
        self.cfg["fix_broken_encoding"] = on
        _save_settings(self.cfg)
        log.info("Repair broken åäö: %s", "ON" if on else "off")
        # Switching it OFF must actually undo the repair on screen, not leave
        # the fixed text sitting there until the next fetch — a tick-box that
        # only works one way is worse than none.
        msg = self._selected_msg
        if msg is not None:
            if not on and msg.get("_body_raw_enc"):
                msg["body"] = msg.pop("_body_raw_enc")
            msg.pop("_enc_fixed", None)
            self._show_message_in_reading_pane(msg)

    def _repair_msg_encoding(self, msg, force=False) -> bool:
        """Fix "=C3=A5" → "å" in ONE message's body, once. Returns whether it
        changed anything.

        The original text is kept in `_body_raw_enc`, so the repair is never
        destructive and "Show source" still shows what actually arrived."""
        if msg is None or (msg.get("_enc_fixed") and not force):
            return False
        body = msg.get("body") or ""
        fixed, did = _repair_encoding(body, msg.get("_charset") or "utf-8")
        msg["_enc_fixed"] = True          # asked and answered — don't re-test
        if not did:
            return False
        msg["_body_raw_enc"] = body
        msg["body"] = fixed
        log.info("Repaired quoted-printable in %r (%d → %d chars)",
                 (msg.get("subject") or "")[:60], len(body), len(fixed))
        return True

    def _fix_encoding_now(self):
        """Tools → "Repair åäö in THIS message now" — works whether or not the
        automatic switch is on, so a one-off mess needs no settings trip."""
        msg = self._selected_msg
        if msg is None:
            messagebox.showinfo("Repair åäö", "Open a message first.",
                                parent=self.root)
            return
        if self._repair_msg_encoding(msg, force=True):
            self._show_message_in_reading_pane(msg)
            self._flash("Repaired the åäö in this message")
        else:
            messagebox.showinfo(
                "Repair åäö",
                "This message does not look like the “=C3=A5” problem, so "
                "nothing was changed.\n\nThat problem shows as =C3=A5 for å, "
                "=C3=A4 for ä and =C3=B6 for ö, with lines broken in the "
                "middle of a word.", parent=self.root)

    def _show_message_in_reading_pane(self, msg):
        self._ensure_full_body(msg)
        for w in self.rp_inner.winfo_children():
            w.destroy()
        # Read-only body Text widgets whose height must be corrected to the
        # exact wrapped-line count once the pane has its real width (DEL 04t).
        self._rp_texts = []
        self._rp_main_frame = None      # set when the opened message renders

        # Remember which message is open, so start-up can reopen it. Only write
        # when it actually changes, so re-renders (toggles) don't hammer disk.
        try:
            k = _msg_key(msg)
            if k and k != self.cfg.get("last_msg_key", ""):
                self.cfg["last_msg_key"] = k
                _save_settings(self.cfg)
        except Exception:
            pass

        thread_id = self._effective_tid(msg)
        # Find every message currently in the list that belongs to the
        # same thread (live lookup — if a message is deleted elsewhere it
        # simply won't appear here any more, no separate state to keep in sync).
        # Uses the EFFECTIVE id, so a manual merge shows its members and an
        # un-merged message shows only itself (no quoted context).
        thread_msgs = [m for m in self._messages
                       if self._effective_tid(m) == thread_id]
        # Chronological — see _thread_order for why not by id.
        thread_msgs.sort(key=_thread_order)
        # Undo undecoded quoted-printable in what is about to be SHOWN, and
        # only in that. Every message here is one you opened or one in its
        # thread, the body is already in hand, and _looks_quoted_printable
        # answers "no" for normal mail before anything is rebuilt.
        if self.cfg.get("fix_broken_encoding", False):
            for m in thread_msgs or [msg]:
                self._repair_msg_encoding(m)

        try:
            main_index = thread_msgs.index(msg)
        except ValueError:
            thread_msgs = [msg]
            main_index = 0

        if self._show_full_thread.get():
            # Full history: every earlier and later message in the thread.
            before = thread_msgs[:main_index]
            after  = thread_msgs[main_index + 1:]
        else:
            # Latest round only: just the single message directly before
            # this one (what's actually being replied to), nothing older.
            # Keeps the reading pane from accumulating an ever-growing
            # quote chain — matches what Smart Reply sends by default.
            before = thread_msgs[main_index - 1:main_index] if main_index > 0 else []
            after  = []

        for m in before:
            self._render_message_block(self.rp_inner, m, is_main=False)
        self._render_message_block(self.rp_inner, msg, is_main=True)
        for m in after:
            self._render_message_block(self.rp_inner, m, is_main=False)

        # The new content has its own height. Recompute the scroll region and
        # jump back to the top, so opening a message never leaves you scrolled
        # into the blank space below a previous, longer one (the "it goes blank
        # and I'm no longer in the message" bug).
        try:
            self.rp_inner.update_idletasks()
            # Now that every body Text has its real on-screen width, set each
            # one's height to the true wrapped-line count so it shows in full
            # (a read-only Text does not auto-size, and it must never scroll on
            # its own — the whole reading pane scrolls as one). Shared with
            # _on_rp_canvas_configure, which redoes this on every later resize
            # too — a stale height clipped the bottom of the message otherwise.
            self._refit_rp_text_heights()
            self.rp_inner.update_idletasks()
            self.rp_canvas.configure(scrollregion=self.rp_canvas.bbox("all"))
            # Land on the message you OPENED. If older messages (or their
            # attachments) render above it, scroll them off the top so the mail
            # you clicked is what you see first — the previous message is still
            # there if you scroll up (Issu 2026-08-01). No context above → top.
            main_frame = getattr(self, "_rp_main_frame", None)
            if before and main_frame is not None and main_frame.winfo_exists():
                total = max(1, self.rp_inner.winfo_height())
                self.rp_canvas.yview_moveto(
                    max(0.0, min(1.0, main_frame.winfo_y() / total)))
            else:
                self.rp_canvas.yview_moveto(0.0)
        except Exception:
            pass

    # ── Hidden message parts + the per-message rules panel (DEL 04t) ──────────
    @staticmethod
    def _text_displaylines(t):
        """The number of *display* (wrapped) lines a Text currently shows, at
        its real width. Called via the low-level Tk command so it works on
        every Python version (the Text.count() wrapper is recent).

        THE +1 IS NOT A FUDGE. "count -displaylines A B" counts the boundaries
        CROSSED between the two indices, so a three-line widget measured from
        "1.0" to "end - 1c" answers 2 — one short, every time. Where the body
        ends with a blank line the missing line was blank and nobody noticed;
        where it does not, the last line of the message was simply cut off, and
        a mail whose last line is its only link (BoardGameGeek's geekmail
        footer, for one) lost the link. Measured, not guessed: Tk 8.6 answers
        1 for "line1\\nline2" and 3 for "a\\nb\\nc\\n" (Issu 2026-08-17).

        A body that already ends in a newline keeps the old count: that last
        display line is empty, and showing it would only add a blank row."""
        try:
            t.update_idletasks()
            n = int(t.tk.call(t._w, "count", "-displaylines", "1.0", "end - 1c"))
            if not t.get("1.0", "end - 1c").endswith("\n"):
                n += 1
            return max(1, n)
        except Exception:
            return None

    def _hidden_for(self, msg) -> list:
        """The substrings currently folded away in this message."""
        return list(self._hiddenparts_store.get("hidden", {}).get(
            _msg_key(msg), []))

    def _hide_part(self, msg, text):
        """Fold away a piece of the opened message (local + reversible)."""
        text = (text or "").strip("\n")
        if not text.strip():
            return
        d = self._hiddenparts_store.setdefault("hidden", {})
        lst = d.setdefault(_msg_key(msg), [])
        if text not in lst:
            lst.append(text)
        _save_hidden_parts(self._hiddenparts_store)
        self._show_message_in_reading_pane(msg)

    def _unhide_part(self, msg, text):
        d = self._hiddenparts_store.setdefault("hidden", {})
        key = _msg_key(msg)
        lst = d.get(key, [])
        if text in lst:
            lst.remove(text)
        if not lst:
            d.pop(key, None)
        _save_hidden_parts(self._hiddenparts_store)
        self._show_message_in_reading_pane(msg)

    def _reveal_trimmed(self, msg, *texts):
        """Show block(s) a standing trim rule folded, for THIS message only.

        The rule is deliberately left alone. Looking at a footer once is not a
        decision to stop hiding it everywhere for ever — that is what the rule
        editor is for, and it is one right-click away on the same marker."""
        key = _msg_key(msg)
        for t in texts:
            self._trim_revealed.add((key, t))
        self._show_message_in_reading_pane(msg)

    def _toggle_context_body(self, ctx_key, msg):
        """Open (or shorten again) one of the QUOTED messages shown above the
        one you clicked. Per session and per message — a thread you opened up
        yesterday should not still be sprawling today."""
        seen = getattr(self, "_ctx_expanded", None)
        if seen is None:
            seen = self._ctx_expanded = set()
        if ctx_key in seen:
            seen.discard(ctx_key)
        else:
            seen.add(ctx_key)
        self._show_message_in_reading_pane(self._selected_msg or msg)

    def _add_trim_rule_from_text(self, msg, text):
        """Turn a piece of the open message into a standing "always hide this"
        rule — the fastest path there is from "this junk again" to never seeing
        it again (Issu 2026-08-16: "med möjlighet för mig att lägga till nya
        saker").

        Scoped to THIS sender by default, and shown for approval before it is
        saved, because a rule made from a selection is easy to make too wide.
        Blank lines are dropped: they match everywhere and would fold the whole
        message."""
        lines = [ln.strip() for ln in (text or "").splitlines() if ln.strip()]
        if not lines:
            self._flash("Select some text first")
            return
        sender = (msg.get("from", "") or "").strip()
        dom = sender.split("@")[-1] if "@" in sender else sender
        rec = dict(_TRIM_DEFAULTS)
        rec.update({
            "id": _new_id(),
            "name": f"Hide from {dom or 'this sender'}"[:60],
            "from_contains": dom,
            "kind": "line",
            "patterns": lines[:20],
            "builtin": False,
        })
        preview = "\n".join(f"   • {p[:70]}" for p in rec["patterns"][:8])
        more = f"\n   … and {len(rec['patterns']) - 8} more" if len(rec["patterns"]) > 8 else ""
        if not messagebox.askyesno(
                "Always hide text like this?",
                f"Hide every line containing one of these, in mail from "
                f"“{dom}”:\n\n{preview}{more}\n\n"
                f"This only changes what is SHOWN — the message itself, and "
                f"any reply you write, keep the full text.\n\n"
                f"You can edit or switch it off later in "
                f"Tools → “Hide boilerplate in messages…”.",
                parent=self.root, default="yes"):
            return
        self._trim_store.setdefault("rules", []).append(rec)
        _save_trim_rules(self._trim_store)
        self._flash(f"Hiding {len(rec['patterns'])} line pattern(s) from {dom}")
        self._show_message_in_reading_pane(msg)

    # ── "Never show THIS line again" (Issu 2026-08-17) ────────────────────────
    #
    # "att jag ska kunna permanent-skippa eller från avsändare-X-specifikt".
    # Both, from the line itself: right-click it, pick how wide the rule should
    # reach, done. Everything the boilerplate editor can do, this dialog does
    # for the one case that comes up over and over — one line, gone for good.

    @staticmethod
    def _clicked_line(widget, event) -> str:
        """The text of the body line the mouse is over.

        Fold markers are stripped out first: "⟨2 lines hidden — … ⟩" is the
        program's own furniture, and a rule built from it would be a rule that
        matches nothing in any real message."""
        try:
            idx = widget.index(f"@{event.x},{event.y}")
            txt = widget.get(f"{idx} linestart", f"{idx} lineend")
        except Exception:
            return ""
        txt = _re.sub(r"⟨[^⟩]*⟩", "", txt).strip()
        return txt if len(txt) >= 3 else ""

    @staticmethod
    def _line_to_pattern(line: str, wildcards: bool) -> str:
        """Turn one line of a message into a regular expression for a rule.

        Anchored to the WHOLE line, because "never show this line" means this
        line and not every longer line that happens to contain it. With
        `wildcards` on, every run of digits becomes \\d+ — without that, a rule
        made from "On Today 09:16, Peter Olsson wrote:" would match exactly one
        message ever, which is not what "never again" means."""
        pat = _re.escape(line.strip())
        if wildcards:
            pat = _re.sub(r"\d+", r"\\d+", pat)
        return rf"^\s*{pat}\s*$"

    @staticmethod
    def _looks_machine_sent(addr: str) -> bool:
        """Does this address belong to a MACHINE that makes up a new one every
        time? BoardGameGeek writes from reply+1101f4fh6pu@mail.boardgamegeek.com
        — pinning a rule to that exact address would make it fire once and never
        again, so for senders like this the domain is the sensible default."""
        local = (addr or "").split("@")[0].lower()
        if any(w in local for w in ("noreply", "no-reply", "donotreply",
                                    "do-not-reply", "bounce", "mailer")):
            return True
        return bool(_re.search(r"\+\S", local) or _re.search(r"\d{4,}", local))

    def _hide_line_forever(self, msg, line: str, prefer_orphan: bool = False):
        """Build a standing hide rule out of ONE line of the open message."""
        line = (line or "").strip()
        if not line:
            self._flash("Right-click the line you want gone")
            return
        addr = (parseaddr(msg.get("from", ""))[1] or
                msg.get("from", "") or "").strip()
        dom  = addr.split("@")[-1] if "@" in addr else addr
        is_attrib = bool(_ATTRIB_RE.search(line))

        top = tk.Toplevel(self.root)
        top.title("Never show this line again")
        top.configure(bg=C_BG3)
        _center_over(top, self.root, 640, 560)
        top.transient(self.root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())

        tk.Label(top, text="Never show this line again",
                 bg=C_BG1, fg=C_ACCENT, font=("Segoe UI", 12, "bold"),
                 pady=8).pack(fill="x")
        tk.Label(top, text="Display only. The message keeps the line, a reply "
                           "still quotes it, and nothing on Gmail changes. "
                           "Every folded line leaves a marker you can click to "
                           "read it after all.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 wraplength=600, justify="left").pack(fill="x", padx=16,
                                                      pady=(6, 8))

        tk.Label(top, text="The line:", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 9, "bold"), anchor="w").pack(fill="x",
                                                                padx=16)
        tk.Label(top, text=line, bg=C_BG2, fg=C_FG, font=("Consolas", 9),
                 anchor="w", justify="left", wraplength=596, padx=8,
                 pady=6).pack(fill="x", padx=16, pady=(2, 10))

        # ── How far should it reach? ────────────────────────────────────────
        v_scope = tk.StringVar(
            value=("domain" if (not addr or self._looks_machine_sent(addr))
                   else "addr"))
        v_wild  = tk.BooleanVar(value=bool(_re.search(r"\d", line)))
        v_orph  = tk.BooleanVar(value=bool(prefer_orphan or is_attrib))

        tk.Label(top, text="Hide it in mail from:", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 9, "bold"), anchor="w").pack(fill="x",
                                                                padx=16)
        for lbl, val in ((f"only  {addr or '(this sender)'}", "addr"),
                         (f"everyone at  {dom or '(this domain)'}", "domain"),
                         ("every sender, always", "all")):
            tk.Radiobutton(top, text=lbl, value=val, variable=v_scope,
                           bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                           activebackground=C_BG3, activeforeground=C_FG,
                           font=("Segoe UI", 9), highlightthickness=0,
                           anchor="w").pack(fill="x", padx=30)

        tk.Checkbutton(top, text="treat the numbers in it as “any number” "
                                 "(dates, times, order numbers)",
                       variable=v_wild, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9), highlightthickness=0,
                       anchor="w").pack(fill="x", padx=26, pady=(8, 0))
        if is_attrib or prefer_orphan:
            tk.Checkbutton(
                top,
                text="only when there is NOTHING under it (recommended here)",
                variable=v_orph, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                activebackground=C_BG3, activeforeground=C_FG,
                font=("Segoe UI", 9), highlightthickness=0,
                anchor="w").pack(fill="x", padx=26)
            tk.Label(top, text="“… wrote:” over a quote that actually arrived "
                               "is worth reading; over an empty one it is "
                               "noise. Ticked, the rule hides EVERY such line "
                               "whose quote is missing — and leaves the rest "
                               "alone. Unticked, it hides this exact wording.",
                     bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8),
                     anchor="w", justify="left",
                     wraplength=580).pack(fill="x", padx=44, pady=(0, 4))

        # ── What it would do to the message on screen ───────────────────────
        tk.Label(top, text="In this message it would hide:", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 9, "bold"), anchor="w").pack(fill="x",
                                                                padx=16,
                                                                pady=(8, 2))
        pv = tk.Label(top, text="", bg=C_BG2, fg=C_FG_DIM,
                      font=("Consolas", 8), anchor="nw", justify="left",
                      wraplength=596, padx=8, pady=6, height=4)
        pv.pack(fill="x", padx=16)

        def _rule() -> dict:
            rec = dict(_TRIM_DEFAULTS)
            scope = v_scope.get()
            rec.update({
                "id": _new_id(),
                "from_contains": (addr if scope == "addr" else
                                  dom if scope == "domain" else ""),
                "builtin": False,
                "enabled": True,
                "regex": True,
            })
            if v_orph.get() and (is_attrib or prefer_orphan):
                rec["kind"] = "orphan"
                rec["patterns"] = [r"wrote\s*:\s*$", r"skrev\s*:\s*$"]
                rec["name"] = "“… wrote:” with nothing under it"
            else:
                rec["kind"] = "line"
                rec["patterns"] = [self._line_to_pattern(line, v_wild.get())]
                rec["name"] = f"Hide: {line[:34]}"
            if rec["from_contains"]:
                rec["name"] = f"{rec['name']}  ({rec['from_contains']})"[:70]
            return rec

        def _preview(*_a):
            body = msg.get("body", "") or ""
            parts, _lbl, _sil = _trim_hidden_parts(
                body, [_rule()], msg,
                keep_links=self.cfg.get("trim_keep_links", True))
            if not parts:
                pv.configure(
                    text="  nothing — this rule matches no line here.\n"
                         "  (Check “any number” if the line carries a date or "
                         "an order number.)")
                return
            shown = "\n".join(f"  {p.splitlines()[0][:80]}" for p in parts[:3])
            more  = f"\n  … and {len(parts) - 3} more" if len(parts) > 3 else ""
            pv.configure(text=f"{shown}{more}")

        for v in (v_scope, v_wild, v_orph):
            v.trace_add("write", _preview)
        _preview()

        def _save(event=None):
            rec = _rule()
            self._trim_store.setdefault("rules", []).append(rec)
            _save_trim_rules(self._trim_store)
            log.info("Hide-line rule added: %s | %s", rec["name"],
                     rec["patterns"])
            top.destroy()
            self._flash("That line is hidden from now on")
            self._show_message_in_reading_pane(self._selected_msg or msg)

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(fill="x", padx=16, pady=12)
        tk.Button(btns, text="🚫  Hide it from now on", bg=C_BTN_NEW,
                  fg=C_BTN_FG, font=("Segoe UI", 9, "bold"), relief="flat",
                  cursor="hand2", padx=14, pady=4,
                  command=_save).pack(side="left")
        tk.Button(btns, text="Cancel", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=14, pady=4, command=top.destroy).pack(side="left",
                                                             padx=6)
        tk.Label(btns, text="ENTER hides it · ESC closes", bg=C_BG3,
                 fg=C_FG_DIM, font=("Segoe UI", 8, "italic")).pack(side="left",
                                                                   padx=8)
        top.bind("<Return>", _save)

    def _enable_orphan_rule(self, msg):
        """The one-click version for "… wrote:" with nothing under it: the same
        dialog, with the "only when nothing follows" box already ticked."""
        line = ""
        for ln in (msg.get("body", "") or "").splitlines():
            if _ATTRIB_RE.search(ln):
                line = ln.strip()
                break
        self._hide_line_forever(msg, line or "wrote:", prefer_orphan=True)

    def _unhide_all_parts(self, msg):
        self._hiddenparts_store.setdefault("hidden", {}).pop(_msg_key(msg), None)
        _save_hidden_parts(self._hiddenparts_store)
        self._show_message_in_reading_pane(msg)

    def _hide_selection(self, text_widget, msg):
        """Fold away whatever is selected in the reading-pane body."""
        try:
            sel = text_widget.get("sel.first", "sel.last")
        except Exception:
            sel = ""
        if not sel.strip():
            self._flash("Select some text first, then Hide")
            return
        self._hide_part(msg, sel)

    def _sender_rule_lines(self, msg) -> list:
        """Plain-language description of every standing rule that fires because
        of WHO sent this message (applies to all their mail)."""
        sender = (parseaddr(msg.get("from", ""))[1]
                  or msg.get("from", "")).strip().lower()
        lines = []
        if not sender:
            return lines
        for r in self._autosave_store.get("rules", []):
            mf = (r.get("match_from") or "").lower()
            if mf and mf in sender:
                where = r.get("subfolder") or "common"
                lines.append(f"📎  Save their attachments  (into: {where})")
        for x in self._filter_store.get("filters", []):
            if not x.get("enabled", True):
                continue
            mf = (x.get("match_from") or "").lower()
            if not (mf and mf in sender):
                continue
            acts = []
            if x.get("action_tag"):
                nm = next((t["name"] for t in self._tag_store.get("tags", [])
                           if t["id"] == x["action_tag"]), "tag")
                acts.append(f"tag “{nm}”")
            if x.get("action_read"):
                acts.append("mark read")
            if x.get("action_star"):
                acts.append("star")
            if x.get("action_hide"):
                acts.append("hide from the list")
            if x.get("action_color"):
                acts.append("colour it")
            if x.get("action_notify") == "never":
                acts.append("never notify")
            elif x.get("action_notify") == "always":
                acts.append("always notify")
            lines.append("⚙  " + (", ".join(acts) if acts
                                   else (x.get("name") or "filter")))
        for key, label in (("spam", "🚫  marked as spam"),
                           ("always_unread", "●  kept unread while in the Inbox"),
                           ("trusted", "✔  trusted — phishing checks eased"),
                           ("blocked", "⛔  blocked — hidden everywhere")):
            for e in self._blocklist_store.get(key, []):
                m = (e.get("match") or "").strip().lower()
                if m and m in sender:
                    lines.append(label)
                    break
        return lines

    def _message_rule_lines(self, msg) -> list:
        """How THIS one message is being handled right now (not the sender)."""
        lines = []
        for t in _tags_of(self._tag_store, msg):
            lines.append(f"{t.get('icon','●')}  tag “{t.get('name','')}”")
        for nm in (msg.get("_filter_names") or []):
            lines.append(f"⚙  filter “{nm}” applied")
        if msg.get("starred"):
            lines.append("★  starred")
        if msg.get("spam"):
            lines.append("🚫  spam")
        try:
            if _msg_key(msg) in getattr(self, "_followup_keys", set()):
                lines.append("🔔  a follow-up reminder is set")
            if msg.get("_float"):
                lines.append("🔼  lifted to the top until you press Done")
        except Exception:
            pass
        try:
            if _msg_key(msg) in _snooze_lookup(self._snooze_store):
                lines.append("⏰  snoozed")
        except Exception:
            pass
        hidden = self._hidden_for(msg)
        if hidden:
            lines.append(f"✂  {len(hidden)} hidden part(s) in the text below")
        return lines

    def _render_rules_panel(self, parent, msg):
        """Panel at the TOP of an opened message showing which rules act on it —
        split into 'for this message' and 'for this sender' (Issu's request).
        Shown/hidden by the reader "Rules acting on this mail" toggle."""
        panel = tk.Frame(parent, bg=C_BG3)
        panel.pack(fill="x", pady=(0, 4))

        tk.Label(panel, text="Rules acting on this mail", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 9, "bold"), anchor="w").pack(
                     fill="x", padx=10, pady=(4, 0))

        msg_lines    = self._message_rule_lines(msg)
        sender_lines = self._sender_rule_lines(msg)
        sender = (parseaddr(msg.get("from", ""))[1]
                  or msg.get("from", "")).strip()

        body = tk.Frame(panel, bg=C_BG3)
        body.pack(fill="x", padx=10, pady=(2, 4))

        def _column(title, lines, empty_text, buttons):
            col = tk.Frame(body, bg=C_BG2, padx=10, pady=8)
            col.pack(fill="x", pady=(4, 0))
            tk.Label(col, text=title, bg=C_BG2, fg=C_ACCENT,
                     font=("Segoe UI", 8, "bold"), anchor="w").pack(fill="x")
            if lines:
                for ln in lines:
                    tk.Label(col, text=ln, bg=C_BG2, fg=C_FG,
                             font=("Segoe UI", 9), anchor="w", justify="left",
                             wraplength=520).pack(fill="x", pady=(2, 0))
            else:
                tk.Label(col, text=empty_text, bg=C_BG2, fg=C_FG_DIM,
                         font=("Segoe UI", 8, "italic"), anchor="w").pack(
                             fill="x", pady=(2, 0))
            brow = tk.Frame(col, bg=C_BG2)
            brow.pack(fill="x", pady=(6, 0))
            for text, colour, cmd in buttons:
                tk.Button(brow, text=text, bg=colour, fg=C_BTN_FG,
                          font=("Segoe UI", 8), relief="flat", cursor="hand2",
                          padx=8, pady=2, command=cmd).pack(side="left",
                                                            padx=(0, 6))

        # For THIS message — its own tags / follow-up / snooze / hidden parts.
        msg_buttons = [("🏷 Tag…", C_BTN_STD, lambda m=msg: self._tags_popup(m)),
                       ("🔔 Remind me…", C_FOLLOWUP,
                        lambda m=msg: self._followup_dialog(m)),
                       ("⏰ Notify me", C_BTN_STD,
                        lambda m=msg: self._snooze_from_pane(m))]
        if msg.get("_float"):
            msg_buttons.insert(0, ("✔ Done — reminder finished", C_BTN_NEW,
                                   lambda m=msg: self._followup_resolve_msg(m)))
        if self._hidden_for(msg):
            msg_buttons.append(("↺ Show hidden text", C_BTN_NEW,
                                lambda m=msg: self._unhide_all_parts(m)))
        _column("For THIS message", msg_lines,
                "Nothing special is applied to this one message yet.",
                msg_buttons)

        # For THIS sender — standing rules that hit every mail they send.
        # "Show all from this sender" only LISTS them — it changes nothing, so
        # it is safe to click (Issu wasn't sure the 📇 icon meant "trash").
        sender_buttons = [("📋 Edit sender rules…", C_BTN_STD,
                           lambda m=msg: self._sender_rules_dialog(m)),
                          ("📇 Show all from this sender (just lists them)",
                           C_BTN_STD, lambda m=msg: self._all_from_sender(m))]
        _column(f"For THIS sender  ({sender})" if sender else "For THIS sender",
                sender_lines,
                "No standing rules for this sender yet.",
                sender_buttons)

        tk.Label(panel,
                 text="“Edit sender rules…” is where you make mail from this "
                      "sender always save its attachments into a folder you "
                      "choose (e.g. 0---Frakt & Kvitto, with a month sub-folder).",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 anchor="w", justify="left", wraplength=560).pack(
                     fill="x", padx=10, pady=(6, 0))
        tk.Frame(panel, bg=C_SEP, height=1).pack(fill="x", padx=10,
                                                 pady=(6, 0))

    def _insert_text_with_links(self, t, text, msg):
        """Insert a run of body text into the reading-pane Text, turning any
        http/https URL into a clickable link (opens through _open_url, so it
        still uses the right browser profile) — Issu couldn't click the link in
        a plain message and had to copy-paste (DEL 04w)."""
        pos = 0
        for m in _URL_RE.finditer(text):
            if m.start() > pos:
                t.insert("end", text[pos:m.start()])
            url = m.group(0)
            start = t.index("end - 1c")
            t.insert("end", url)
            self._link_seq = getattr(self, "_link_seq", 0) + 1
            tagname = f"link_{self._link_seq}"
            t.tag_add(tagname, start, t.index("end - 1c"))
            t.tag_configure(tagname, foreground=C_ACCENT, underline=True)
            t.tag_bind(tagname, "<Enter>",
                       lambda e, w=t: w.configure(cursor="hand2"))
            t.tag_bind(tagname, "<Leave>",
                       lambda e, w=t: w.configure(cursor="arrow"))
            t.tag_bind(tagname, "<Button-1>",
                       lambda e, u=url, mm=msg: self._open_url(u, mm))
            # Right-click a link → Open OR Copy link address (Issu: with DHL mail
            # he wanted both, not just open). "break" so the body menu below
            # does not also pop up.
            t.tag_bind(tagname, "<Button-3>",
                       lambda e, u=url, mm=msg: (self._link_context_menu(e, u, mm),
                                                 "break")[1])
            pos = m.end()
        if pos < len(text):
            t.insert("end", text[pos:])

    def _render_body_with_hiding(self, parent, msg, fg, font_body):
        """The opened message's body, rendered in a read-only Text so you can
        select a piece and fold it away (DEL 04t). Hidden pieces show as a small
        inline marker you click to bring them back. Non-main (quoted) messages
        keep the plain Label — you only fold the message you are working on."""
        hidden = self._hidden_for(msg)
        # ── Standing boilerplate rules (DEL 04t2) ───────────────────────────
        # Folded the same way a hand-picked selection is, so the renderer below
        # needs no new case: the only difference is that the marker names the
        # RULE, and clicking it reveals the block for this message without
        # touching the rule. A block you have already clicked open stays open
        # while the message is on screen.
        auto, auto_labels, auto_silent = _trim_hidden_parts(
            msg.get("body", ""), self._trim_store.get("rules", []), msg,
            keep_links=self.cfg.get("trim_keep_links", True))
        mkey = _msg_key(msg)
        auto = [a for a in auto if (mkey, a) not in self._trim_revealed]
        segments = _segment_body(msg.get("body", ""), hidden + auto)

        wrap = tk.Frame(parent, bg=C_BG2)
        wrap.pack(fill="x")

        t = tk.Text(wrap, wrap="word", bg=C_BG2, fg=fg,
                    font=font_body, relief="flat", highlightthickness=0, bd=0,
                    padx=14, pady=10, cursor="arrow",
                    selectbackground=C_ACCENT, selectforeground="#ffffff",
                    insertofftime=0, insertontime=9999999, height=1,
                    # exportselection off → a background auto-check (which builds
                    # other widgets) can no longer steal this text's highlight
                    # out from under you mid-copy (Issu #16, 2026-08-01).
                    exportselection=False)
        no_blink(t)
        # This Text only DISPLAYS — clicking in it to select a piece must not
        # kill every keyboard shortcut and both arrow keys (DEL 09f).
        self._attach_nav(t)
        t.tag_configure("hiddenmark", foreground=C_ACCENT,
                        font=("Segoe UI", 8, "italic"))

        collapse = self.cfg.get("collapse_blank_lines", True)
        for kind, val in segments:
            if kind == "text":
                # Display-only tidy-up: a wall of blank lines left behind by an
                # HTML table becomes one. msg["body"] keeps every one of them.
                self._insert_text_with_links(
                    t, _collapse_blank_runs(val) if collapse else val, msg)
            else:
                # A compact, clickable stand-in for the folded piece. A rule's
                # marker says WHICH rule, and how many lines it took — "6 lines
                # hidden" is the difference between trusting this and wondering
                # what you are not being shown.
                # Markup cleaned by a "strip" rule leaves nothing behind — a
                # marker per [/q] tag was worse than the tags (see
                # _trim_hidden_parts). "↺ Show boilerplate" still restores it.
                if val in auto_silent:
                    continue
                rule_name = auto_labels.get(val) if val in auto else None
                if rule_name:
                    n = val.count("\n") + 1
                    caption = (f"  ⟨{n} line{'s' if n > 1 else ''} hidden — "
                               f"{rule_name} · click to show⟩  ")
                else:
                    caption = "  ⟨hidden — click to show⟩  "
                start = t.index("end - 1c")
                t.insert("end", caption, "hiddenmark")
                tagname = f"unhide_{len(t.tag_names())}"
                t.tag_add(tagname, start, t.index("end - 1c"))
                t.tag_configure(tagname, foreground=C_ACCENT, underline=True)
                t.tag_bind(tagname, "<Enter>",
                           lambda e, w=t: w.configure(cursor="hand2"))
                t.tag_bind(tagname, "<Leave>",
                           lambda e, w=t: w.configure(cursor="arrow"))
                if rule_name:
                    t.tag_bind(tagname, "<Button-1>",
                               lambda e, m=msg, v=val: self._reveal_trimmed(m, v))
                    # Right-click the marker → the rule that hid it, so a rule
                    # that folds too much is one click from being fixed.
                    t.tag_bind(tagname, "<Button-3>",
                               lambda e, v=val: (self._trim_rules_dialog(
                                   focus_name=auto_labels.get(v, "")), "break")[1])
                else:
                    t.tag_bind(tagname, "<Button-1>",
                               lambda e, m=msg, v=val: self._unhide_part(m, v))

        # Read-only, but the mouse must still be able to SELECT (that is how you
        # pick what to hide). Block editing keystrokes, keep copy working.
        def _readonly(e):
            if (e.state & 0x4) and e.keysym.lower() in ("c", "a"):
                return          # Ctrl+C / Ctrl+A pass through
            if e.keysym in ("Left", "Right", "Up", "Down", "Home", "End",
                            "Prior", "Next"):
                return
            return "break"
        t.bind("<Key>", _readonly)
        # Right-click anywhere in the body → Copy / Select all, so you never have
        # to remember Ctrl+C (Issu couldn't copy from the reading pane).
        t.bind("<Button-3>", lambda e, w=t, m=msg: self._body_context_menu(e, w, m))
        t.pack(fill="x")
        self._rp_texts.append(t)

        # Controls: hide what is selected, and (if anything is folded) show all.
        ctl = tk.Frame(parent, bg=C_BG2, padx=14)
        ctl.pack(fill="x", pady=(0, 2))
        tk.Button(ctl, text="✂ Hide selection", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 8), relief="flat", cursor="hand2",
                  padx=8, pady=2,
                  command=lambda w=t, m=msg: self._hide_selection(w, m)
                  ).pack(side="left")
        if hidden:
            tk.Button(ctl, text=f"↺ Show all hidden ({len(hidden)})",
                      bg=C_BTN_NEW, fg=C_BTN_FG, font=("Segoe UI", 8),
                      relief="flat", cursor="hand2", padx=8, pady=2,
                      command=lambda m=msg: self._unhide_all_parts(m)
                      ).pack(side="left", padx=(6, 0))
        # Boilerplate folded by a standing rule gets its own control, separate
        # from the hand-picked one above: they are undone in different ways and
        # one button doing both would be a button that sometimes edits a rule.
        if auto:
            tk.Button(ctl, text=f"↺ Show boilerplate ({len(auto)})",
                      bg=C_BTN_STD, fg=C_BTN_FG, font=("Segoe UI", 8),
                      relief="flat", cursor="hand2", padx=8, pady=2,
                      command=lambda m=msg, a=list(auto):
                          self._reveal_trimmed(m, *a)
                      ).pack(side="left", padx=(6, 0))
        tk.Label(ctl, text="select text, then Hide — local only, never sent",
                 bg=C_BG2, fg=C_FG_DIM,
                 font=("Segoe UI", 7, "italic")).pack(side="left", padx=8)

    def _render_message_block(self, parent, msg, is_main):
        """Render one message's header + body (+ attachments).

        is_main=True  → full-size, normal colours (the opened message).
        is_main=False → indented, dimmed grey (other messages in the
                        same thread, shown only as context).
        """
        indent = 0 if is_main else 28
        fg_subject = C_FG if is_main else C_FG_DIM
        fg_meta    = C_FG_DIM if is_main else "#5a5e78"
        bg_hdr     = C_BG3 if is_main else C_BG2
        font_subj  = ("Segoe UI", 11, "bold") if is_main else ("Segoe UI", 9, "bold")
        font_body  = ("Segoe UI", 10) if is_main else ("Segoe UI", 9)

        outer = tk.Frame(parent, bg=C_BG2)
        outer.pack(fill="x", padx=(indent, 0), pady=(0, 6) if is_main else (0, 2))
        # Remember the OPENED message's frame so the reading pane can scroll
        # straight to it, instead of landing on the quoted/previous message above
        # it (Issu: "jag måste alltid scrolla" past the old message + its
        # attachments to reach the one I clicked).
        if is_main:
            self._rp_main_frame = outer

        # ── Top-of-message strips (DEL 04t) — actions + rules, both optional ──
        # Both sit ABOVE the header now (Issu wanted the action buttons at the
        # top, not the bottom) and are toggled from the reader toolbar, OFF by
        # default so the message is what you see first.
        if is_main and self._rp_show_actions.get():
            self._render_message_actions(outer, msg)
        # "View formatted (HTML)" / "Always" belong UP HERE, directly under the
        # message actions (Issu 2026-08-16). They used to render below the
        # body: on a long HTML newsletter — exactly the mail you want the
        # formatted view for — the switch was several screens down, so you had
        # to scroll through the very text you were trying not to read in order
        # to reach the button that would have shown it properly.
        if is_main:
            self._render_html_row(outer, msg)
            self._render_unsub_row(outer, msg)
        if is_main and self._rp_show_rules.get():
            self._render_rules_panel(outer, msg)

        # ── Header ───────────────────────────────────────────────────────
        hdr = tk.Frame(outer, bg=bg_hdr, padx=12, pady=8 if is_main else 5)
        hdr.pack(fill="x")

        # Right-click anywhere in the header → copy subject / sender / all
        # (these are Labels, so you cannot drag-select them — Issu 2026-08-02).
        def _hdr_rclick(e, m=msg):
            self._header_context_menu(e, m)
        hdr.bind("<Button-3>", _hdr_rclick)

        lbl_subject = tk.Label(hdr, text=msg.get("subject", ""), bg=bg_hdr,
                               fg=fg_subject, font=font_subj, anchor="w",
                               wraplength=560 - indent, justify="left")
        lbl_subject.pack(fill="x")

        # DEL 09p — said where the message is actually being READ, not only as
        # a padlock in the list. A protected message looks like any other until
        # you try to delete it, and that is too late to be told.
        if is_main and self._is_protected_message(msg):
            tk.Label(hdr,
                     text="🔒  Protected — a delete that takes several "
                          "messages at once skips this one. Right-click the "
                          "row → 🔓 Unprotect to release it.",
                     bg=bg_hdr, fg="#7ddba8", font=("Segoe UI", 8),
                     anchor="w", wraplength=560 - indent,
                     justify="left").pack(fill="x", pady=(3, 0))

        lbl_from = tk.Label(
            hdr, text=f"From:  {msg.get('from_name','')}  <{msg.get('from','')}>",
            bg=bg_hdr, fg=fg_meta, font=("Segoe UI", 9 if is_main else 8),
            anchor="w")
        lbl_from.pack(fill="x", pady=(4 if is_main else 2, 0))

        to_acct = msg.get("account_email", "")
        hdr_labels = [lbl_subject, lbl_from]
        if is_main:
            # Real To: (all addresses the mail was sent to), not just your
            # own receiving account — and a Cc: row plus an "+N more"
            # recipient count, so it's visible at a glance whether this went
            # to more people than you (Issu 2026-08-04: previously "To:" only
            # ever showed your own account address, no Cc: shown at all).
            # ── Long recipient lists fold away (Issu 2026-08-08) ───────────
            # "Jag fick ett mail med supermånga mottagare … det tar mycket
            # plats, innan meddelandet." A circular to fifty people put a
            # screenful of strangers' addresses between him and the text he
            # actually wanted to read. Anything past `recipients_max` is
            # folded behind a one-line summary you can click open; and a
            # sender who ALWAYS does this can be told to never show them at
            # all (right-click the line).
            sender_addr = (parseaddr(msg.get("from", ""))[1]
                           or msg.get("from", "")).lower()
            never = sender_addr in {
                (s or "").lower()
                for s in (self.cfg.get("hide_recipients_from") or [])}
            limit = int(self.cfg.get("recipients_max", 5) or 0)

            def _recip_row(caption, value):
                """One To:/Cc: line, folded when it is long."""
                addrs = _parse_addr_list(value)
                n = len(addrs)
                folded = never or (limit > 0 and n > limit)
                row = tk.Frame(hdr, bg=bg_hdr)
                row.pack(fill="x")
                state = {"open": False}
                lbl = tk.Label(row, text="", bg=bg_hdr, fg=fg_meta,
                               font=("Segoe UI", 9), anchor="w",
                               wraplength=560 - indent, justify="left")
                lbl.pack(side="left", fill="x", expand=True)
                more = tk.Label(row, text="", bg=bg_hdr, fg=C_ACCENT,
                                font=("Segoe UI", 8, "underline"),
                                cursor="hand2")

                def paint():
                    if not folded or state["open"]:
                        lbl.configure(text=f"{caption}  {value}")
                        more.configure(text=("  ▴ hide" if folded else ""))
                    else:
                        shown = ", ".join(addrs[:1]) if addrs else ""
                        why = ("hidden for this sender" if never
                               else f"{n} recipients")
                        lbl.configure(
                            text=f"{caption}  {shown}"
                                 + (f"   … and {n - 1} more" if n > 1 else "")
                                 + f"   ({why})")
                        more.configure(text="  ▾ show all")
                    if folded:
                        more.pack(side="right")

                def toggle(_e=None):
                    state["open"] = not state["open"]
                    paint()

                paint()
                more.bind("<Button-1>", toggle)
                lbl.bind("<Double-Button-1>", toggle)
                for w in (row, lbl):
                    w.bind("<Button-3>",
                           lambda e, s=sender_addr, a=addrs, c=caption:
                               self._recipients_menu(e, s, addrs=a, caption=c))
                # Deliberately NOT added to hdr_labels: that list gets a blanket
                # Button-3 → _header_context_menu at the end of the header, and
                # since the label fills the row it would have replaced the menu
                # just bound above — which is why right-clicking a To:/Cc: line
                # never showed the recipient menu at all (found 2026-08-29).
                return lbl

            to_hdr = msg.get("_to_hdr", "") or to_acct
            _recip_row("To:", to_hdr if to_hdr else "")

            cc_hdr = msg.get("_cc_hdr", "")
            if cc_hdr:
                _recip_row("Cc:", cc_hdr)

            my_emails = [a.get("email") for a in getattr(self, "_accounts", [])]
            others = _other_recipients(msg, my_emails)
            if others:
                n = len(others)
                lbl_others = tk.Label(
                    hdr, text=f"↳  +{n} more recipient{'s' if n > 1 else ''} "
                               f"besides you",
                    bg=bg_hdr, fg=C_ACCENT, font=("Segoe UI", 8),
                    anchor="w")
                lbl_others.pack(fill="x")
                hdr_labels.append(lbl_others)

            # The same mail arrived in more than one of YOUR accounts and the
            # All-Accounts view folded the copies into this one row. Say so —
            # collapsing a duplicate must never hide the fact that it reached
            # both mailboxes (Issu 2026-08-08).
            also = msg.get("_also_in") or []
            if also:
                lbl_also = tk.Label(
                    hdr,
                    text="⧉  the same message also arrived in:  "
                         + ", ".join(also),
                    bg=bg_hdr, fg="#ffd08a", font=("Segoe UI", 8),
                    anchor="w", wraplength=560 - indent, justify="left")
                lbl_also.pack(fill="x")
                hdr_labels.append(lbl_also)

        # ── Date — short by default, exact on click (Issu 2026-08-29) ─────
        # "Yesterday" is the right thing to read almost always, so it stays;
        # but it hides the clock completely, and sometimes the clock is the
        # whole point. One click swaps this line for the full timestamp (and
        # clicking again puts it back) — nothing is hidden behind a menu, and
        # nothing extra is shown to anyone who does not ask for it.
        _date_state = {"exact": False}
        lbl_date = tk.Label(hdr, text=f"Date:  {msg.get('date','')}  🕐",
                            bg=bg_hdr, fg=fg_meta, font=("Segoe UI", 8),
                            anchor="w", cursor="hand2",
                            wraplength=560 - indent, justify="left")
        lbl_date.pack(fill="x", pady=(2 if is_main else 0, 0))

        def _toggle_date(_e=None, m=msg, w=lbl_date, st=_date_state):
            st["exact"] = not st["exact"]
            if st["exact"]:
                w.configure(text=f"Date:  {_exact_time(m)}  🕐", fg=C_ACCENT)
            else:
                w.configure(text=f"Date:  {m.get('date','')}  🕐", fg=fg_meta)

        lbl_date.bind("<Button-1>", _toggle_date)
        add_tooltip(lbl_date, "Click for the exact time this message was "
                              "sent — click again for the short form.")
        hdr_labels.append(lbl_date)
        for _w in hdr_labels:
            _w.bind("<Button-3>", _hdr_rclick)

        # ── Phishing warning banner (DEL 04e) ────────────────────────────
        # Only on the opened message: a red bar on every quoted message in a
        # thread would train you to ignore it, which is the opposite of the
        # point. Nothing is hidden or deleted — you are told what was found.
        if is_main:
            # Cached on the message: the reading pane is redrawn every time
            # you click a row or expand a thread, and re-running several
            # regexes over a big HTML mail each time is pure waste. Message
            # dicts are rebuilt on every fetch, so the cache cannot go stale.
            warnings = msg.get("_phish")
            if warnings is None:
                try:
                    warnings = _phishing_scan(
                        msg,
                        trusted=_is_trusted_sender(self._blocklist_store, msg),
                        brand_level=self.cfg.get("phish_brand_level", "balanced"))
                except Exception as e:
                    log.warning("Phishing scan failed: %s", e)
                    warnings = []
                msg["_phish"] = warnings
            if warnings:
                ban = tk.Frame(outer, bg=C_WARN_BG, padx=12, pady=8)
                ban.pack(fill="x")
                tk.Label(ban, text="⚠  This message looks like phishing",
                         bg=C_WARN_BG, fg="#ffffff",
                         font=("Segoe UI", 10, "bold"),
                         anchor="w").pack(fill="x")
                for w in warnings[:5]:
                    tk.Label(ban, text="•  " + w, bg=C_WARN_BG, fg=C_WARN_FG,
                             font=("Segoe UI", 9), anchor="w", justify="left",
                             wraplength=540 - indent).pack(fill="x", pady=(3, 0))
                tk.Label(ban,
                         text="Do not click links or open attachments unless "
                              "you are certain. Nothing has been deleted — "
                              "this is only a warning.",
                         bg=C_WARN_BG, fg="#ffbdbd",
                         font=("Segoe UI", 8, "italic"), anchor="w",
                         justify="left", wraplength=540 - indent
                         ).pack(fill="x", pady=(6, 0))
                # A warning you cannot answer is a warning you learn to
                # ignore. If this sender is fine, say so once and the
                # heuristics stop crying wolf for them — except for
                # dangerous attachments, which stay loud (see
                # _UNSUPPRESSABLE).
                if not _is_trusted_sender(self._blocklist_store, msg):
                    trust = tk.Label(ban,
                                     text="✔  Not phishing — trust this sender",
                                     bg=C_WARN_BG, fg="#ffffff",
                                     font=("Segoe UI", 8, "underline"),
                                     cursor="hand2", anchor="w")
                    trust.pack(fill="x", pady=(6, 0))
                    trust.bind("<Button-1>",
                               lambda e, m=msg: self._trust_sender(m))
                    # Trust the whole domain — for relays like boardgamegeek.com
                    # where each message is from a different member address but
                    # the same domain (Issu 2026-08-01).
                    dom = (parseaddr(msg.get("from", ""))[1] or "").split("@")[-1]
                    if dom:
                        trust_dom = tk.Label(
                            ban,
                            text=f"✔  Trust the whole domain  (@{dom})",
                            bg=C_WARN_BG, fg="#ffffff",
                            font=("Segoe UI", 8, "underline"),
                            cursor="hand2", anchor="w")
                        trust_dom.pack(fill="x", pady=(3, 0))
                        trust_dom.bind("<Button-1>",
                                       lambda e, m=msg: self._trust_domain(m))

        # ── "You sent this to yourself" notice (DEL 04g) ──────────────────
        # Gmail keeps ONE message with several labels, so a mail to yourself
        # is not an Inbox copy plus a Sent copy — it is a single message
        # wearing both labels. Deleting it "from Sent" therefore takes it out
        # of the Inbox too. That surprises people badly, so it is said out
        # loud, on the message it applies to, instead of being buried in a
        # help file.
        if is_main and not msg.get("_note_path") and _is_self_message(msg):
            note = tk.Frame(outer, bg=C_BG3, padx=12, pady=6)
            note.pack(fill="x")
            tk.Label(note, text="↩  You sent this to yourself",
                     bg=C_BG3, fg=C_ACCENT, font=("Segoe UI", 9, "bold"),
                     anchor="w").pack(fill="x")
            tk.Label(note,
                     text="On Gmail this is ONE message carrying both the "
                          "Inbox and the Sent label — not two copies. Deleting "
                          "it from Sent would remove it from the Inbox as "
                          "well. F(re)email cannot do that: Delete here only "
                          "hides it from this view.",
                     bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8),
                     anchor="w", justify="left",
                     wraplength=540 - indent).pack(fill="x")
            tip = tk.Label(note,
                           text="🗒  For notes to yourself, use Notes instead — "
                                "a file on your own disk that no server can "
                                "touch.",
                           bg=C_BG3, fg=C_BTN_NOTE,
                           font=("Segoe UI", 8, "underline"), cursor="hand2",
                           anchor="w", justify="left",
                           wraplength=540 - indent)
            tip.pack(fill="x", pady=(4, 0))
            tip.bind("<Button-1>",
                     lambda e: self._select_folder(self._current_acct, "Notes"))

        # ── A delivery failure, explained (DEL 04p) ───────────────────────
        if is_main and _is_bounce(msg):
            d = _bounce_details(msg)
            bf = tk.Frame(outer, bg="#5a3a12", padx=12, pady=8)
            bf.pack(fill="x")
            tk.Label(bf, text="📮  This is a delivery failure",
                     bg="#5a3a12", fg="#ffd08a",
                     font=("Segoe UI", 10, "bold"),
                     anchor="w").pack(fill="x")
            if d["recipient"]:
                tk.Label(bf, text=f"Did not reach:  {d['recipient']}",
                         bg="#5a3a12", fg="#ffffff",
                         font=("Segoe UI", 9, "bold"), anchor="w",
                         wraplength=540 - indent).pack(fill="x", pady=(4, 0))
            tk.Label(bf, text=d["cause"] + (f"   ({d['code']})"
                                            if d["code"] else ""),
                     bg="#5a3a12", fg="#ffe9c9", font=("Segoe UI", 9),
                     anchor="w", justify="left",
                     wraplength=540 - indent).pack(fill="x", pady=(4, 0))
            tk.Label(bf, text="→  " + d["advice"], bg="#5a3a12", fg="#ffe9c9",
                     font=("Segoe UI", 8), anchor="w", justify="left",
                     wraplength=540 - indent).pack(fill="x", pady=(2, 0))
            # Fix & resend — rebuilds the original with only the failed
            # recipient, so you just correct the address and send (Issu #18).
            retry = tk.Button(
                bf, text="↻  Fix the address & resend",
                bg=C_BTN_NEW, fg=C_BTN_FG, font=("Segoe UI", 9, "bold"),
                relief="flat", cursor="hand2", padx=10, pady=3,
                command=lambda m=msg: self._retry_bounce(m))
            retry.pack(anchor="w", pady=(8, 0))
            add_tooltip(retry,
                        "Opens a new message with the original subject and text, "
                        "addressed only to the address that failed. Correct it "
                        "and send again — no copy-paste.")

        # ── An attachment that was promised but never came (DEL 04p) ──────
        if is_main:
            promised = _promised_attachment_missing(msg)
            if promised:
                pf = tk.Frame(outer, bg=C_BG3, padx=12, pady=5)
                pf.pack(fill="x")
                tk.Label(pf,
                         text=f"📎  They wrote “{promised}” — but nothing is "
                              f"attached.",
                         bg=C_BG3, fg="#ffd08a", font=("Segoe UI", 9, "bold"),
                         anchor="w", justify="left",
                         wraplength=540 - indent).pack(fill="x")
                tk.Label(pf, text="Worth asking now rather than tomorrow.",
                         bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8),
                         anchor="w").pack(fill="x")

        if not is_main:
            tk.Frame(outer, bg=C_SEP, height=1).pack(fill="x")

        # ── Which parcel is this? (DEL 09m) ───────────────────────────────
        # Above the attachments, because the answer is what you came for: the
        # town it is going to and the title of the game. Neither is anywhere
        # in the mail itself — both are read out of the attached PDFs.
        if is_main:
            self._render_shipping_strip(outer, msg, indent)

        # ── Attachments — ABOVE the body so a mail with files shows them at
        # once, instead of forcing a scroll to the very end (Issu 2026-08-01).
        self._render_attachment_list(outer, msg, is_main, bg_hdr, fg_meta)

        # ── Body ─────────────────────────────────────────────────────────
        # ── One of your own unsent drafts (Issu 2026-08-07) ───────────────
        if is_main and msg.get("_local_draft"):
            df = tk.Frame(outer, bg="#1e3a1e", padx=14, pady=10)
            df.pack(fill="x")
            tk.Label(df, text="✎  This is your own unsent draft",
                     bg="#1e3a1e", fg="#a8e6a8", font=("Segoe UI", 10, "bold"),
                     anchor="w").pack(fill="x")
            tk.Label(df, text="It is saved on this computer and has not been "
                              "sent to anyone. It is not on Gmail.",
                     bg="#1e3a1e", fg="#cfeccf", font=("Segoe UI", 8),
                     anchor="w", justify="left",
                     wraplength=540 - indent).pack(fill="x", pady=(2, 0))
            drow = tk.Frame(df, bg="#1e3a1e")
            drow.pack(fill="x", pady=(8, 0))
            tk.Button(drow, text="✎  Continue writing", bg=C_BTN_NEW,
                      fg=C_BTN_FG, font=("Segoe UI", 9, "bold"), relief="flat",
                      cursor="hand2", padx=10, pady=3,
                      command=lambda m=msg: self._open_local_draft(m)
                      ).pack(side="left")
            tk.Button(drow, text="🗑  Throw this draft away", bg=C_BTN_DEL,
                      fg=C_BTN_FG, font=("Segoe UI", 9), relief="flat",
                      cursor="hand2", padx=10, pady=3,
                      command=lambda m=msg: self._delete_local_draft(m)
                      ).pack(side="left", padx=6)

        if is_main and not msg.get("_body_loaded", True) and msg.get("_body_error"):
            # ── The download did not work — SAY SO (Issu 2026-08-07) ─────────
            # This used to sit on "⏳ Loading the full message…" for ever with
            # no explanation and no way out, which is what turned one shipping
            # receipt into a twenty-minute hunt. Now it explains itself and
            # offers the two things worth doing next.
            errf = tk.Frame(outer, bg="#5a3a12", padx=14, pady=12)
            errf.pack(fill="x")
            tk.Label(errf, text="⚠  Could not open this message",
                     bg="#5a3a12", fg="#ffd08a", font=("Segoe UI", 10, "bold"),
                     anchor="w").pack(fill="x")
            tk.Label(errf, text=msg.get("_body_error", ""),
                     bg="#5a3a12", fg="#ffe9c9", font=("Segoe UI", 9),
                     anchor="w", justify="left",
                     wraplength=540 - indent).pack(fill="x", pady=(4, 0))
            tk.Label(errf,
                     text="The list you are looking at was made a moment ago; "
                          "the message has moved since. Refreshing the folder "
                          "puts the list back in step with the server.",
                     bg="#5a3a12", fg="#ffe9c9", font=("Segoe UI", 8),
                     anchor="w", justify="left",
                     wraplength=540 - indent).pack(fill="x", pady=(4, 0))
            brow = tk.Frame(errf, bg="#5a3a12")
            brow.pack(fill="x", pady=(8, 0))
            tk.Button(brow, text="↻  Try again", bg=C_BTN_NEW, fg=C_BTN_FG,
                      font=("Segoe UI", 9, "bold"), relief="flat",
                      cursor="hand2", padx=10, pady=3,
                      command=lambda m=msg: self._retry_body_fetch(m)
                      ).pack(side="left")
            tk.Button(brow, text="⟳  Refresh this folder", bg=C_BTN_STD,
                      fg=C_BTN_FG, font=("Segoe UI", 9), relief="flat",
                      cursor="hand2", padx=10, pady=3,
                      # self.refresh does not exist and never did. This is read
                      # when the button is BUILT, not when it is pressed, so
                      # the whole "the body could not be downloaded" panel
                      # raised AttributeError instead of appearing — the one
                      # moment you most need it (found by test_attrs.py,
                      # 2026-08-18).
                      command=self._refresh_messages).pack(side="left", padx=6)
        elif is_main and not msg.get("_body_loaded", True):
            # Only the folder LIST was sped up (headers first) — the message
            # itself is being fetched right now and will redraw the instant
            # it lands, usually well under a second (Issu 2026-08-06).
            load = tk.Frame(outer, bg=C_BG2, padx=14, pady=14)
            load.pack(fill="x")
            tk.Label(load, text="⏳  Loading the full message…",
                    bg=C_BG2, fg=C_FG_DIM, font=("Segoe UI", 9, "italic"),
                    anchor="w").pack(fill="x")
        elif is_main:
            # A read-only Text so you can select a piece and fold it away; any
            # already-hidden parts show as inline "click to show" markers (04t).
            self._render_body_with_hiding(outer, msg, fg_subject, font_body)
        else:
            # Quoted context messages stay a simple, truncated label — you fold
            # the message you are working on, not the history behind it.
            #
            # The truncation used to be FINAL: 240 characters and the rest of
            # that message did not exist on screen at all. For a threaded
            # BoardGameGeek conversation that is exactly the wrong 240 —
            # everything worth having in a geekmail sits at the BOTTOM (the
            # link to the original message is the last line of every one), so
            # the older messages in the thread showed their greeting and hid
            # their link (Issu 2026-08-17). It now opens, on one click, into
            # the same read-only Text the opened message uses, which also makes
            # its links clickable instead of merely visible.
            full_txt = msg.get("body", "") or ""
            ctx_key  = _msg_key(msg)
            opened   = ctx_key in getattr(self, "_ctx_expanded", set())
            if opened:
                ct = tk.Text(outer, wrap="word", bg=C_BG2, fg=fg_subject,
                             font=font_body, relief="flat", highlightthickness=0,
                             bd=0, padx=14, pady=10, cursor="arrow", height=1,
                             selectbackground=C_ACCENT,
                             selectforeground="#ffffff",
                             insertofftime=0, insertontime=9999999,
                             exportselection=False)
                no_blink(ct)
                self._attach_nav(ct)
                self._insert_text_with_links(
                    ct,
                    _collapse_blank_runs(full_txt)
                    if self.cfg.get("collapse_blank_lines", True) else full_txt,
                    msg)

                def _ctx_readonly(e):
                    if (e.state & 0x4) and e.keysym.lower() in ("c", "a"):
                        return
                    if e.keysym in ("Left", "Right", "Up", "Down", "Home",
                                    "End", "Prior", "Next"):
                        return
                    return "break"
                ct.bind("<Key>", _ctx_readonly)
                ct.bind("<Button-3>",
                        lambda e, w=ct, m=msg: self._body_context_menu(e, w, m))
                ct.pack(fill="x")
                self._rp_texts.append(ct)
            else:
                short = (full_txt[:240].rstrip() + " […]"
                         if len(full_txt) > 240 else full_txt)
                tk.Label(outer, text=short, bg=C_BG2, fg=fg_subject,
                         font=font_body, anchor="nw", justify="left",
                         wraplength=560 - indent, padx=14,
                         pady=10).pack(fill="x")
            if len(full_txt) > 240:
                more = tk.Label(
                    outer,
                    text=("▴  Shorten this message again" if opened else
                          "▾  Show the whole message"),
                    bg=C_BG2, fg=C_ACCENT, cursor="hand2",
                    font=("Segoe UI", 8, "underline"), anchor="w", padx=14)
                more.pack(fill="x", pady=(0, 4))
                more.bind("<Button-1>",
                          lambda e, k=ctx_key, m=msg:
                              self._toggle_context_body(k, m))

        # ("View formatted (HTML)" used to sit HERE, under the body. It is now
        # rendered at the TOP by _render_html_row — see _render_message_block.)

        # (Attachments render ABOVE the body now — see _render_attachment_list,
        # called before the body. The per-message action buttons render at the
        # TOP via _render_message_actions() when that reader toggle is on.)

    def _render_unsub_row(self, outer, msg):
        """The newsletter strip: unsubscribe, and every link this mail has.

        Both of these already existed — behind the "message actions" toggle,
        which is OFF by default. That is why Issu, looking at an estore
        newsletter, had "en länk som jag inte kan klicka på": the link lived
        inside an HTML href, and the one control that could reach it was on a
        strip he had never turned on (2026-08-29).

        So this row is always drawn — but ONLY on mail that has an unsubscribe
        route, or whose links are hidden inside HTML. An ordinary plain-text
        message already has clickable links in the pane and gets nothing extra
        to read past."""
        unsub = _find_unsubscribe(msg)
        has_route = bool(unsub.get("mailto") or unsub.get("http"))
        links = _links_in_message(msg)
        hidden_links = bool(links) and bool((msg.get("_html") or "").strip())
        if not (has_route or hidden_links):
            return

        row = tk.Frame(outer, bg=C_BG2, padx=14)
        row.pack(fill="x", pady=(0, 4))

        if has_route:
            already = _unsub_already_done(self._unsub_store, msg)
            b = tk.Button(
                row,
                text=("↺ Unsubscribe again…" if already else "✖ Unsubscribe…"),
                bg=(C_BTN_STD if already else C_BTN_LATER), fg=C_BTN_FG,
                font=("Segoe UI", 8, "bold"), relief="flat", cursor="hand2",
                padx=10, pady=2,
                command=lambda m=msg: self._unsubscribe_dialog(m))
            b.pack(side="left")
            bits = []
            if unsub.get("one_click"):
                bits.append("one click, no browser")
            elif unsub.get("http"):
                bits.append("web page")
            if unsub.get("mailto"):
                bits.append("or by e-mail")
            add_tooltip(b, "Ways out of this list: "
                           + (", ".join(bits) or "a link in the message")
                           + f".\nFound in the {unsub.get('source','')} of the "
                             "message.\n\nThe page can open in F(re)email's own "
                             "mini view — no JavaScript, no images, and your "
                             "real browser is not involved.")
            if already:
                tk.Label(row,
                         text="  (already unsubscribed "
                              + (already.get("when", "") or "")[:10] + ")",
                         bg=C_BG2, fg=C_FG_DIM,
                         font=("Segoe UI", 8, "italic")).pack(side="left")
            elif unsub.get("one_click"):
                tk.Label(row, text="  ⚡ one click is enough for this one",
                         bg=C_BG2, fg="#a8e6a8",
                         font=("Segoe UI", 8)).pack(side="left")

        if links:
            b2 = tk.Button(row, text=f"🌐 Links ({len(links)})…",
                           bg=C_BTN_STD, fg=C_BTN_FG, font=("Segoe UI", 8),
                           relief="flat", cursor="hand2", padx=10, pady=2,
                           command=lambda m=msg: self._links_popup(m))
            b2.pack(side="left", padx=(6, 0))
            add_tooltip(b2, "Every link in this message, including the ones "
                            "that only exist inside the HTML and cannot be "
                            "clicked in the text view.\n\nEach one can be "
                            "opened here in the mini view, opened in your real "
                            "browser, or copied — and the menu always shows "
                            "where it really goes.")

    def _render_html_row(self, outer, msg):
        """The "🌐 View formatted (HTML)" link and its "Always" tick-box.

        Rendered at the TOP of the opened message (Issu 2026-08-16). Nothing at
        all is drawn for a message with no HTML part, so a plain mail is not
        given a row of empty controls.

        The åäö tick-box lives here too (Issu 2026-08-18: "jag hade gärna sett
        checkbox efter Always"). That means the row also has to appear for a
        PLAIN message that needs the repair — the Dancover mail that started
        this had its Swedish mangled and the control would otherwise have been
        invisible on exactly the mail it was built for."""
        has_html = bool((msg.get("_html") or "").strip())
        needs_enc = bool(msg.get("_body_raw_enc")) or _looks_quoted_printable(
            msg.get("body") or "")
        if not (has_html or needs_enc):
            return
        html_row = tk.Frame(outer, bg=C_BG2)
        html_row.pack(fill="x", pady=(0, 4))
        if has_html:
            html_lbl = tk.Label(html_row,
                                text="🌐  View formatted (HTML) in popup",
                                bg=C_BG2, fg=C_ACCENT, cursor="hand2",
                                font=("Segoe UI", 9, "underline"),
                                anchor="w", padx=14)
            html_lbl.pack(side="left")
            html_lbl.bind("<Button-1>",
                          lambda e, mm=msg: self._show_html_popup(mm))
            html_lbl.bind("<Enter>",
                          lambda e: html_lbl.configure(fg="#b4d4ff"))
            html_lbl.bind("<Leave>", lambda e: html_lbl.configure(fg=C_ACCENT))
        # "Always" makes HTML the permanent choice: an HTML message then
        # opens its formatted view by itself (Issu 2026-08-01). Turning it
        # off goes back to reading the plain text here.
        if has_html:
            self._always_html_var = tk.BooleanVar(
                value=bool(self.cfg.get("always_html_view", False)))
            tk.Checkbutton(html_row, text="Always (open HTML automatically)",
                           variable=self._always_html_var,
                           command=self._toggle_always_html,
                           bg=C_BG2, fg=C_FG_DIM, selectcolor=C_BG1,
                           activebackground=C_BG2, activeforeground=C_FG,
                           font=("Segoe UI", 8), highlightthickness=0,
                           relief="flat").pack(side="left", padx=(12, 0))

        # ── Right after "Always", as asked ───────────────────────────────────
        # Same tk variable as the Tools-menu entry, so ticking it in either
        # place shows in both. Only drawn when this message actually needs it,
        # so it never becomes one more permanent control to read past.
        if needs_enc and getattr(self, "_fix_enc_var", None) is not None:
            cb = tk.Checkbutton(html_row, text="Fix åäö (=C3=A5)",
                                variable=self._fix_enc_var,
                                command=self._toggle_fix_encoding,
                                bg=C_BG2, fg=C_FG_DIM, selectcolor=C_BG1,
                                activebackground=C_BG2, activeforeground=C_FG,
                                font=("Segoe UI", 8), highlightthickness=0,
                                relief="flat")
            cb.pack(side="left", padx=(12, 0))
            add_tooltip(cb, "This message arrived as quoted-printable that was "
                            "never decoded — “=C3=A5” is å, “=C3=A4” is ä, and "
                            "a lone “=” at the end of a line is why the lines "
                            "break mid-word.\n\nTicking this decodes it here "
                            "and in every message you open from now on. "
                            "Untick to see it exactly as it arrived.")

    # ── DEL 09m — the facts inside a shipping receipt ────────────────────────
    def _ship_facts(self, msg, compute=True) -> dict:
        """Town, country, title, buyer, carrier for one shipping receipt —
        {} when the message is not one.

        Three layers, and all three earn their keep: a per-session memo (the
        message LIST asks for every visible row on every redraw), then
        shipping.json on disk (so the rows are filled in the second the
        program starts, long before any body has been downloaded again), and
        only then the PDFs themselves."""
        if not isinstance(msg, dict) or msg.get("_note_path"):
            return {}
        key = _msg_key(msg)
        if not key:
            return {}
        if key in self._ship_memo:
            return self._ship_memo[key]
        stored = (self._ship_store.get("facts") or {}).get(key)
        if isinstance(stored, dict) and stored.get("v") == _SHIP_FACTS_V:
            self._ship_memo[key] = stored
            return stored
        if not compute or not _ship_is_shipping_mail(msg):
            # A cached entry from an older build is still better than nothing
            # when the message itself is out of reach.
            if isinstance(stored, dict):
                self._ship_memo[key] = stored
                return stored
            return {}
        if not msg.get("_body_loaded", True):
            return {}                      # headers only so far — ask again later
        data = msg.get("_attachment_data") or {}
        if msg.get("attachments") and not any(data.values()):
            return stored if isinstance(stored, dict) else {}
        try:
            facts = _shipping_facts(msg.get("body", ""), data,
                                    sender=msg.get("from", ""))
        except Exception as e:
            log.debug("shipping facts failed: %s", e)
            facts = {}
        self._ship_memo[key] = facts
        if facts:
            facts["v"] = _SHIP_FACTS_V
            self._ship_store.setdefault("facts", {})[key] = facts
            _ship_prune(self._ship_store)
            was_dirty, self._ship_dirty = self._ship_dirty, True
            if not was_dirty:              # one write, not one per message
                try:
                    self.root.after(2000, self._ship_flush)
                except Exception:
                    self._ship_flush()
        return facts

    def _ship_flush(self):
        if self._ship_dirty:
            self._ship_dirty = False
            _save_ship_facts(self._ship_store)

    def _ship_qr_name(self, msg) -> str:
        """The QR-code image among the attachments, if there is one."""
        for n in (msg.get("attachments") or []):
            low = n.lower()
            if low.endswith((".png", ".jpg", ".jpeg", ".gif", ".webp")) \
                    and "qr" in low:
                return n
        return ""

    @staticmethod
    def _ship_menu_label(name: str, room: int = 58) -> str:
        """A filename short enough for a context-menu line. The Save dialog
        still opens with the whole thing."""
        if len(name) <= room:
            return name
        return name[:room - 12] + "…" + name[-11:]

    def _render_shipping_strip(self, outer, msg, indent=0):
        """The one-line answer to "which parcel is this?", at the very top of
        an opened shipping receipt (Issu 2026-08-23)."""
        facts = self._ship_facts(msg)
        # Carrier-only facts (a bare drop-off receipt) are enough for the
        # FILENAME but not worth a strip that would read "📦" and nothing.
        if not facts or not (facts.get("place") or facts.get("city")
                             or facts.get("title")):
            return
        BG, FG, DIM = "#12352a", "#b9f0d2", "#7fbfa2"
        f = tk.Frame(outer, bg=BG, padx=12, pady=6)
        f.pack(fill="x")
        head = facts.get("place") or facts.get("city") or ""
        if facts.get("abroad") and facts.get("city") and facts.get("country"):
            head = f"{facts['country']}  ({facts['city']})"
        title = facts.get("title", "")
        tk.Label(f, text="📦  " + "   —   ".join([x for x in (head, title) if x]),
                 bg=BG, fg=FG, font=("Segoe UI", 10, "bold"), anchor="w",
                 justify="left", wraplength=540 - indent).pack(fill="x")
        detail = []
        who = facts.get("recipient", "")
        if facts.get("alias") and facts["alias"] != who:
            who = f"{who} ({facts['alias']})" if who else facts["alias"]
        if who:
            detail.append(who)
        car = facts.get("carrier_short") or _ship_carrier_short(
            facts.get("carrier", ""))
        if car:
            # The short name, the same one that goes into the filename, so he
            # can see what he is about to save.
            detail.append(car
                          + (f" {facts['weight']}" if facts.get("weight") else "")
                          + (f" · {facts['amount']}" if facts.get("amount") else ""))
        if facts.get("tracking"):
            detail.append("nr " + facts["tracking"])
        if facts.get("item_no"):
            detail.append("objekt " + facts["item_no"])
        if detail:
            tk.Label(f, text="        " + "   ·   ".join(detail), bg=BG, fg=DIM,
                     font=("Segoe UI", 8), anchor="w", justify="left",
                     wraplength=540 - indent).pack(fill="x", pady=(2, 0))
        qr = self._ship_qr_name(msg)
        if qr and (msg.get("_attachment_data") or {}).get(qr):
            pretty = _ship_prefixed_name(facts, qr)
            if pretty != qr:
                b = tk.Button(f, text=f"💾  Save the QR code as "
                                      f"“{self._ship_menu_label(pretty, 46)}”",
                              bg=C_BTN_STD, fg=C_BTN_FG, font=("Segoe UI", 8),
                              relief="flat", cursor="hand2", padx=8, pady=2,
                              command=lambda m=msg, n=qr:
                                  self._save_attachment(m, n, prefixed=True))
                b.pack(anchor="w", pady=(5, 0))
                add_tooltip(b, "Saves it as\n" + pretty +
                            "\n\nThe “00-” keeps the parcels you "
                            "still have to hand in at the top of the folder.")

    def _render_attachment_list(self, outer, msg, is_main, bg_hdr, fg_meta):
        """The 📎 attachment list. Rendered ABOVE the body (Issu: "attachments
        längst ned = måste alltid scrolla") so a mail with files shows them at
        once. Left-click opens; right-click = Save / Save all / Open with…."""
        attachments = msg.get("attachments") or []
        if not attachments:
            return
        attach_fg = C_ACCENT if is_main else "#4a6a8a"
        af = tk.Frame(outer, bg=bg_hdr)
        af.pack(fill="x")
        tk.Frame(af, bg=C_SEP, height=1).pack(fill="x")
        hrow = tk.Frame(af, bg=bg_hdr)
        hrow.pack(fill="x", pady=(6, 2))
        tk.Label(hrow, text=f"📎 {len(attachments)} attachment(s):",
                 bg=bg_hdr, fg=fg_meta, font=("Segoe UI", 8, "bold"),
                 anchor="w", padx=10).pack(side="left")
        # "Save all" right here — the whole set to a folder in one go (04u).
        if is_main:
            tk.Button(hrow, text="💾 Save all…", bg=C_BTN_STD, fg=C_BTN_FG,
                      font=("Segoe UI", 8), relief="flat", cursor="hand2",
                      padx=8, pady=1,
                      command=lambda m=msg: self._save_all_attachments(m)
                      ).pack(side="right", padx=(0, 10))
        for fname in attachments:
            a_lbl = tk.Label(af, text=f"   📄 {fname}", bg=bg_hdr,
                             fg=attach_fg,
                             font=("Segoe UI", 9 if is_main else 8),
                             anchor="w", cursor="hand2", padx=10, pady=1)
            a_lbl.pack(fill="x")
            # Left-click → open in the default viewer / image popup.
            a_lbl.bind("<Button-1>",
                       lambda e, m=msg, fn=fname: self._open_attachment(m, fn))
            # Right-click → Save / Save all / Open with a program you choose.
            if is_main:
                a_lbl.bind("<Button-3>",
                           lambda e, m=msg, fn=fname:
                               self._attachment_context_menu(e, m, fn))
            a_lbl.bind("<Enter>", lambda e, w=a_lbl: w.configure(fg="#b4d4ff"))
            a_lbl.bind("<Leave>",
                       lambda e, w=a_lbl, c=attach_fg: w.configure(fg=c))
        if is_main:
            hint = ("       left-click opens · right-click for "
                    "Save / Save all / Open with…")
            if self._ship_facts(msg):
                hint += " · and “00-town---title---”"
            tk.Label(af, text=hint,
                     bg=bg_hdr, fg=C_FG_DIM,
                     font=("Segoe UI", 7, "italic"),
                     anchor="w", padx=10).pack(fill="x")
        tk.Frame(af, bg=bg_hdr, height=6).pack(fill="x")

    def _render_message_actions(self, outer, msg):
        """The per-message action buttons (DEL 09b), on TWO rows so the long
        set is readable. Rendered at the TOP of the opened message when the
        reader "Message actions" toggle is on."""
        wrap = tk.Frame(outer, bg=C_BG2, padx=10, pady=6)
        wrap.pack(fill="x")
        row1 = tk.Frame(wrap, bg=C_BG2); row1.pack(fill="x")
        row2 = tk.Frame(wrap, bg=C_BG2); row2.pack(fill="x", pady=(4, 0))

        def _act_btn(parent, text, colour, cmd):
            tk.Button(parent, text=text, bg=colour, fg=C_BTN_FG,
                      font=("Segoe UI", 8), relief="flat",
                      cursor="hand2", padx=8, pady=3, command=cmd
                      ).pack(side="left", padx=(0, 6))

        if msg.get("_followup"):
            it = msg["_followup"]
            _act_btn(row1, "📂 Open the message", C_BTN_NEW,
                     lambda i=it: self._open_followup_message(i))
            if not it.get("done") or _followup_is_floating(it):
                _act_btn(row1, "✏ Change reminder", C_BTN_STD,
                         lambda i=it, m=msg: FollowUpDialog(
                             self.root, self, m, existing=i,
                             on_saved=self._followups_changed))
                _act_btn(row1, ("✔ Done — finished" if it.get("float")
                                else "✔ Stop reminding"), C_BTN_DEL,
                         lambda i=it: (_followup_stop(
                             self._followup_store, i.get("id", "")),
                             self._followups_changed()))
            else:
                _act_btn(row1, "🗑 Remove from the list", C_BTN_DEL,
                         lambda i=it: (_followup_remove(
                             self._followup_store, i.get("id", "")),
                             self._followups_changed()))
        elif msg.get("_note_path"):
            _act_btn(row1, "💾 Save as PDF", C_BTN_STD,
                     lambda m=msg: self._save_msg_pdf(m))
            _act_btn(row1, "🗑 Delete note", C_BTN_DEL,
                     lambda m=msg: self._delete_note(m))
            tk.Label(row1, text="local note — never sent anywhere",
                     bg=C_BG2, fg=C_FG_DIM,
                     font=("Segoe UI", 8, "italic")).pack(side="left", padx=6)
        elif msg.get("_snooze_key"):
            _act_btn(row1, "⏰ Unsnooze now", C_BTN_NEW,
                     lambda m=msg: (self._unsnooze(m["_snooze_key"]),
                                    self._refresh_messages()))
        else:
            # Row 1 — the everyday actions.
            _act_btn(row1, "💾 Save as PDF", C_BTN_STD,
                     lambda m=msg: self._save_msg_pdf(m))
            if len([x for x in self._messages
                    if x.get("thread_id") == msg.get("thread_id")]) > 1:
                _act_btn(row1, "📚 Thread as PDF", C_BTN_STD,
                         lambda m=msg: self._save_thread_pdf(m))
            has_invite = bool(_find_ics_in_message(msg))
            _act_btn(row1, "📅 Add to calendar" if has_invite
                     else "📅 Make appointment",
                     C_BTN_NEW if has_invite else C_BTN_STD,
                     lambda m=msg: self._add_message_to_calendar(m))
            _act_btn(row1, "⏰ Notify me", C_BTN_STD,
                     lambda m=msg: self._snooze_from_pane(m))
            _act_btn(row1, "🗒 Save to Notes", C_BTN_NOTE,
                     lambda m=msg: self._save_message_as_note(m))
            _act_btn(row1, "🔔 Remind me…", C_FOLLOWUP,
                     lambda m=msg: self._followup_dialog(m))
            if msg.get("_float"):
                _act_btn(row1, "✔ Done — reminder finished", C_BTN_NEW,
                         lambda m=msg: self._followup_resolve_msg(m))
            # Row 2 — tagging, rules, and the more technical bits.
            _act_btn(row2, "🏷 Tags…", C_BTN_STD,
                     lambda m=msg: self._tags_popup(m))
            _act_btn(row2, "📇 Show all from this sender", C_BTN_STD,
                     lambda m=msg: self._all_from_sender(m))
            _act_btn(row2, "📋 Rules for sender…", C_BTN_STD,
                     lambda m=msg: self._sender_rules_dialog(m))
            _act_btn(row2, "📄 Source", C_BTN_STD,
                     lambda m=msg: self._show_message_source(m))
            if _links_in_message(msg):
                _act_btn(row2, "🌐 Open link…", C_BTN_STD,
                         lambda m=msg: self._links_popup(m))
            for t in _tags_of(self._tag_store, msg):
                tk.Label(row2, text=f" {t.get('icon','●')} {t['name']} ",
                         bg=t.get("color", C_BG3), fg="#ffffff",
                         font=("Segoe UI", 8, "bold")).pack(side="left", padx=2)
            unsub = _find_unsubscribe(msg)
            if unsub.get("mailto") or unsub.get("http"):
                _act_btn(row2, "✖ Unsubscribe…", C_BTN_LATER,
                         lambda m=msg: self._unsubscribe_dialog(m))
            if msg.get("_filter_names"):
                tk.Label(row2, text="filter: " + ", ".join(msg["_filter_names"]),
                         bg=C_BG2, fg=C_FG_DIM,
                         font=("Segoe UI", 8, "italic")).pack(side="left", padx=6)

        tk.Frame(outer, bg=C_SEP, height=1).pack(fill="x", pady=(6, 0))

    # ── Sending ───────────────────────────────────────────────────────────────
    #
    # There is deliberately NO send_mail() any more. Everything outgoing goes
    # through queue_send() → the outbox → _send_outbox_item() (DEL 09b).
    #
    # The old send_mail() called SMTP directly, and it survived as dead code
    # after the outbox was introduced. That is a trap worth removing rather
    # than keeping: anyone (human or AI) adding a new "just send this" path
    # would have found it, called it, and quietly bypassed undo-send, the
    # scheduler, the attachment-size check and the failure handling — a
    # message would leave with no way to stop it. One door only.

    # ── Open an attachment in an external popup (not in the main window) ───────
    def _open_attachment(self, msg, fname):
        data = (msg.get("_attachment_data") or {}).get(fname)
        if not data:
            messagebox.showinfo(
                "Attachment",
                "Attachment data is not available for this message "
                "(demo data has no real files).", parent=self.root)
            return
        # Images get an in-app preview popup; everything else opens in the OS
        # default viewer (still a separate window, never the main pane).
        ext = os.path.splitext(fname)[1].lower()
        if ext in (".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp"):
            if self._show_image_popup(fname, data):
                return
        try:
            safe = _re.sub(r'[\\/:*?"<>|]', "_", fname)
            path = os.path.join(tempfile.gettempdir(), f"freemail_{safe}")
            with open(path, "wb") as f:
                f.write(data)
            if platform.system() == "Windows":
                open_path(path)            # opens in the OS default viewer
            elif platform.system() == "Darwin":
                os.system(f'open "{path}"')
            else:
                os.system(f'xdg-open "{path}"')
        except Exception as e:
            messagebox.showerror("Attachment",
                                 f"Could not open attachment:\n{e}",
                                 parent=self.root)

    # ── Attachment right-click: Save / Save all / Open with… (DEL 04u) ────────
    def _attachment_data(self, msg, fname):
        """The bytes of one attachment, or None (with a friendly notice)."""
        data = (msg.get("_attachment_data") or {}).get(fname)
        if not data:
            messagebox.showinfo(
                "Attachment",
                "Attachment data is not available for this message "
                "(demo data has no real files).", parent=self.root)
            return None
        return data

    def _attachment_temp_path(self, fname, data) -> str:
        """Write the bytes to a temp file and return its path."""
        safe = _re.sub(r'[\\/:*?"<>|]', "_", fname)
        path = os.path.join(tempfile.gettempdir(), f"freemail_{safe}")
        with open(path, "wb") as f:
            f.write(data)
        return path

    def _attach_dialog_dir(self):
        """The folder the attachment Save dialogs always start in: my fixed
        default (ATTACH_SAVE_DIR_DEFAULT). Without it the dialog started in
        whatever folder Windows remembered - ToDo 2026-11-01. Falls back to
        the last folder used if that folder does not exist."""
        if os.path.isdir(ATTACH_SAVE_DIR_DEFAULT):
            return ATTACH_SAVE_DIR_DEFAULT
        return self.cfg.get("attach_save_dir", "") or None

    def _attachment_context_menu(self, event, msg, fname):
        ext = os.path.splitext(fname)[1].lower()
        m = tk.Menu(self.root, tearoff=0, bg=C_BG2, fg=C_FG,
                    activebackground=C_BG4, activeforeground=C_FG)
        m.add_command(label="Open  (default viewer)",
                      command=lambda: self._open_attachment(msg, fname))
        # Remembered programs for this extension become one-click choices.
        apps = (self.cfg.get("open_with_apps") or {}).get(ext, [])
        for app in apps:
            nm = app.get("name") or os.path.basename(app.get("path", ""))
            m.add_command(label=f"Open with  {nm}",
                          command=lambda a=app: self._open_attachment_with(
                              msg, fname, a))
        m.add_command(label="Open with…  (choose a program)",
                      command=lambda: self._open_attachment_with_dialog(msg, fname))
        if apps:
            m.add_command(label="Forget the programs for this type",
                          command=lambda e=ext: self._forget_open_with(e))
        m.add_separator()
        m.add_command(label="Save as…",
                      command=lambda: self._save_attachment(msg, fname))
        m.add_command(label="Save all attachments…",
                      command=lambda: self._save_all_attachments(msg))
        # ── The shipping name (DEL 09m) ──────────────────────────────────────
        # "istället för att spara med qr-filens namn, lägger till prefix:
        #  00-Stad---Titel---". QrCode-3505190755.png says nothing in a
        # folder of thirty of them; this one sorts to the top and names the
        # town and the game. Offered on EVERY attachment of the receipt, so
        # the fraktsedel and the kvitto can be filed the same way.
        facts = self._ship_facts(msg)
        pretty = _ship_prefixed_name(facts, fname) if facts else fname
        if facts and pretty != fname:
            m.add_separator()
            m.add_command(
                label=f"📦  Save as “{self._ship_menu_label(pretty)}”…",
                command=lambda: self._save_attachment(msg, fname,
                                                      prefixed=True))
            m.add_command(
                label="📦  Save all of them with that prefix…",
                command=lambda: self._save_all_attachments(msg, prefixed=True))
        try:
            m.tk_popup(event.x_root, event.y_root)
        finally:
            m.grab_release()

    def _launch_with_program(self, program_path, file_path):
        """Open a file with a chosen program. A .py/.pyw target is run through
        Python; anything else is launched directly."""
        import subprocess
        try:
            ext = os.path.splitext(program_path)[1].lower()
            if ext in (".py", ".pyw"):
                exe = sys.executable or "python"
                # Prefer pythonw.exe for GUI tools so no console flashes up.
                if os.path.basename(exe).lower().startswith("python") \
                        and "w" not in os.path.basename(exe).lower():
                    cand = os.path.join(os.path.dirname(exe), "pythonw.exe")
                    if os.path.isfile(cand):
                        exe = cand
                args = [exe, program_path, file_path]
            else:
                args = [program_path, file_path]
            subprocess.Popen(args)
            return True
        except Exception as e:
            messagebox.showerror("Open with",
                                 f"Could not start the program:\n{e}",
                                 parent=self.root)
            return False

    def _open_attachment_with(self, msg, fname, app):
        data = self._attachment_data(msg, fname)
        if data is None:
            return
        prog = app.get("path", "")
        if not prog or not os.path.isfile(prog):
            messagebox.showwarning(
                "Open with",
                f"The program is no longer at:\n{prog}\n\n"
                "Pick it again with “Open with… (choose a program)”.",
                parent=self.root)
            return
        try:
            path = self._attachment_temp_path(fname, data)
        except Exception as e:
            messagebox.showerror("Open with", f"Could not prepare the file:\n{e}",
                                 parent=self.root)
            return
        self._launch_with_program(prog, path)

    def _open_attachment_with_dialog(self, msg, fname):
        data = self._attachment_data(msg, fname)
        if data is None:
            return
        from tkinter import filedialog
        prog = filedialog.askopenfilename(
            parent=self.root, title=f"Choose a program to open {fname}",
            filetypes=[("Programs", "*.exe *.bat *.cmd *.py *.pyw"),
                       ("All files", "*.*")])
        if not prog:
            return
        name = os.path.splitext(os.path.basename(prog))[0]
        # Remember it for this extension so it is a one-click choice next time.
        ext = os.path.splitext(fname)[1].lower()
        store = self.cfg.setdefault("open_with_apps", {})
        lst = store.setdefault(ext, [])
        if not any(a.get("path", "").lower() == prog.lower() for a in lst):
            lst.append({"name": name, "path": prog})
            _save_settings(self.cfg)
        try:
            path = self._attachment_temp_path(fname, data)
        except Exception as e:
            messagebox.showerror("Open with", f"Could not prepare the file:\n{e}",
                                 parent=self.root)
            return
        self._launch_with_program(prog, path)

    def _forget_open_with(self, ext):
        store = self.cfg.setdefault("open_with_apps", {})
        if ext in store:
            store.pop(ext, None)
            _save_settings(self.cfg)
            self._flash(f"Forgot the programs for {ext or 'this type'}")
        if self._selected_msg:
            self._show_message_in_reading_pane(self._selected_msg)

    def _save_attachment(self, msg, fname, prefixed=False):
        data = self._attachment_data(msg, fname)
        if data is None:
            return
        from tkinter import filedialog
        ext = os.path.splitext(fname)[1]
        # prefixed = the shipping name, "00-Tyskland---Tärning, svaga
        # siffror---QrCode-3505190755.png" (DEL 09m).
        initial = (_ship_prefixed_name(self._ship_facts(msg), fname)
                   if prefixed else fname)
        path = filedialog.asksaveasfilename(
            parent=self.root, title="Save attachment as",
            initialfile=initial,
            initialdir=self._attach_dialog_dir(),
            defaultextension=ext,
            filetypes=[("This file type", f"*{ext}") if ext else
                       ("All files", "*.*"), ("All files", "*.*")])
        if not path:
            return
        try:
            with open(path, "wb") as f:
                f.write(data)
            self.cfg["attach_save_dir"] = os.path.dirname(path)
            _save_settings(self.cfg)
            self._flash(f"Saved {os.path.basename(path)}")
        except Exception as e:
            messagebox.showerror("Save attachment",
                                 f"Could not save the file:\n{e}",
                                 parent=self.root)

    def _save_all_attachments(self, msg, prefixed=False):
        names = msg.get("attachments") or []
        store = msg.get("_attachment_data") or {}
        facts = self._ship_facts(msg) if prefixed else {}
        have = [n for n in names if store.get(n)]
        if not have:
            messagebox.showinfo(
                "Save all",
                "There are no attachment files to save "
                "(demo data has no real files).", parent=self.root)
            return
        from tkinter import filedialog
        folder = filedialog.askdirectory(
            parent=self.root, title=f"Save all {len(have)} attachment(s) into…",
            initialdir=self._attach_dialog_dir(),
            mustexist=True)
        if not folder:
            return
        saved, errors = 0, []
        for n in have:
            try:
                # Never overwrite: add " (2)", " (3)" … if the name is taken.
                out_name = _ship_prefixed_name(facts, n) if facts else n
                target = os.path.join(folder, out_name)
                base, ext = os.path.splitext(out_name)
                k = 2
                while os.path.exists(target):
                    target = os.path.join(folder, f"{base} ({k}){ext}")
                    k += 1
                with open(target, "wb") as f:
                    f.write(store[n])
                saved += 1
            except Exception as e:
                errors.append(f"{n}: {e}")
        self.cfg["attach_save_dir"] = folder
        _save_settings(self.cfg)
        if errors:
            messagebox.showwarning(
                "Save all",
                f"Saved {saved} of {len(have)}.\n\nProblems:\n"
                + "\n".join(errors[:8]), parent=self.root)
        else:
            self._flash(f"Saved {saved} attachment(s)")

    def _show_image_popup(self, fname, data) -> bool:
        """Preview an image attachment in a popup Toplevel. Returns True on
        success, False to let the caller fall back to the OS viewer."""
        try:
            import io
            from PIL import Image, ImageTk
        except Exception:
            return False
        try:
            img = Image.open(io.BytesIO(data))
            img.load()
        except Exception as e:
            log.warning("Image preview failed for %s: %s", fname, e)
            return False
        w, h = img.size
        scale = min(900 / w, 680 / h, 1.0)
        if scale < 1.0:
            img = img.resize((max(1, int(w * scale)), max(1, int(h * scale))),
                             Image.LANCZOS)
        top = tk.Toplevel(self.root)
        top.title(f"{fname}  ({w}×{h})")
        top.configure(bg=C_BG1)
        top.transient(self.root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())
        photo = ImageTk.PhotoImage(img)
        lbl = tk.Label(top, image=photo, bg=C_BG1)
        lbl.image = photo            # keep a reference so it isn't GC'd
        lbl.pack(padx=8, pady=8)
        _center_over(top, self.root, img.size[0] + 16, img.size[1] + 16)
        return True

    def _toggle_always_html(self):
        """Remember whether HTML messages should open their formatted view by
        themselves (the "Always" checkbox next to the HTML link)."""
        on = bool(self._always_html_var.get())
        self.cfg["always_html_view"] = on
        _save_settings(self.cfg)
        # If the message in front of you is HTML, honour the new choice at once.
        if on and self._selected_msg and (self._selected_msg.get("_html") or "").strip():
            self._show_html_popup(self._selected_msg, auto=True)

    def _show_html_popup(self, msg, auto=False):
        """Render an HTML message in a popup (not the main pane). Remote images
        are blocked by default; a checkbox can load them on demand.

        auto=True is the "Always open HTML" path: it reuses ONE window and does
        not grab focus, so clicking through HTML mail doesn't fight you for the
        keyboard on every message (Issu 2026-08-01)."""
        html = msg.get("_html") or ""
        if not html.strip():
            if not auto:
                messagebox.showinfo("HTML view", "This message has no HTML part.",
                                    parent=self.root)
            return
        try:
            from tkinterweb import HtmlFrame
        except Exception:
            messagebox.showinfo(
                "HTML view",
                "HTML rendering needs the 'tkinterweb' package:\n\n"
                "    pip install tkinterweb", parent=self.root)
            return

        # Auto mode reuses a single window so clicking through mail doesn't leave
        # a trail of HTML popups; the manual link always opens a fresh one.
        if auto:
            prev = getattr(self, "_html_auto_win", None)
            if prev is not None:
                try:
                    prev.destroy()
                except Exception:
                    pass
        top = tk.Toplevel(self.root)
        top.title(f"HTML — {msg.get('subject','')}")
        top.configure(bg=C_BG2)
        _center_over(top, self.root, 820, 640)
        top.transient(self.root)
        if auto:
            self._html_auto_win = top
        else:
            top.grab_set()
            top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())

        bar = tk.Frame(top, bg=C_BG1)
        bar.pack(fill="x")
        load_imgs = tk.BooleanVar(value=False)
        frame_holder = {"frame": None}

        def _render():
            if frame_holder["frame"] is not None:
                frame_holder["frame"].destroy()
            f = HtmlFrame(top, messages_enabled=False)
            content = html if load_imgs.get() else _strip_remote_images(html)
            try:
                f.load_html(content)
            except Exception as e:
                log.warning("HTML render failed: %s", e)
                f.load_html("<pre>Could not render HTML.</pre>")
            f.pack(fill="both", expand=True)
            frame_holder["frame"] = f

        tk.Checkbutton(bar, text="Load remote images (may contact senders)",
                       variable=load_imgs, command=_render,
                       bg=C_BG1, fg=C_FG_DIM, selectcolor=C_BG2,
                       activebackground=C_BG1, activeforeground=C_FG,
                       font=("Segoe UI", 8), highlightthickness=0,
                       relief="flat", padx=8, pady=3).pack(side="left")
        tk.Button(bar, text="Close", bg=C_BTN_STD, fg=C_BTN_FG, relief="flat",
                  padx=12, cursor="hand2",
                  command=top.destroy).pack(side="right", padx=6, pady=3)
        # Copy OR open any link in this HTML mail (DHL tracking links etc.) —
        # rendered HTML can be awkward to select from, so the reliable path is
        # right here.
        if _links_in_message(msg):
            tk.Button(bar, text="🌐 Links…", bg=C_BTN_STD, fg=C_BTN_FG,
                      relief="flat", padx=12, cursor="hand2",
                      command=lambda mm=msg: self._links_popup(mm)
                      ).pack(side="right", padx=6, pady=3)
        # Copy the whole message as text — the formatted (HTML) view often can't
        # be selected with the mouse, so this is the reliable way to copy from a
        # DHL-style mail (Issu: "om jag väljer formatted kan jag inte markera
        # och kopiera"). The text carries link URLs too, from _html_to_text.
        def _copy_all_text(mm=msg):
            body = (mm.get("body") or "").strip() or _html_to_text(
                mm.get("_html") or "")
            self._copy_to_clipboard(body, "Message text copied")
        tk.Button(bar, text="📋 Copy text", bg=C_BTN_STD, fg=C_BTN_FG,
                  relief="flat", padx=12, cursor="hand2",
                  command=_copy_all_text).pack(side="right", padx=6, pady=3)
        _render()

    def _flash(self, msg):
        """1-second auto-close confirmation popup (no buttons)."""
        try:
            w = tk.Toplevel(self.root)
            w.overrideredirect(True)
            w.configure(bg=C_BG3)
            x = self.root.winfo_x() + self.root.winfo_width()  // 2 - 130
            y = self.root.winfo_y() + self.root.winfo_height() // 2 - 24
            w.geometry(f"260x48+{x}+{y}")
            tk.Label(w, text=f"✔  {msg}", bg="#1a5c2a", fg="#90ee90",
                     font=("Segoe UI", 11, "bold")).pack(expand=True, fill="both")
            w.after(1000, w.destroy)
        except Exception:
            pass

    def _copy_to_clipboard(self, text, flash_msg="Copied"):
        """Put text on the clipboard and show the 1-second confirmation."""
        try:
            self.root.clipboard_clear()
            self.root.clipboard_append(text)
            self._flash(flash_msg)
        except Exception as e:
            log.warning("clipboard copy failed: %s", e)

    def _body_context_menu(self, event, widget, msg):
        """Right-click menu for a reading-pane body Text: Copy / Select all."""
        try:
            has_sel = bool(widget.tag_ranges("sel"))
        except Exception:
            has_sel = False

        def _copy_sel():
            try:
                sel = widget.get("sel.first", "sel.last")
            except Exception:
                sel = ""
            if sel:
                self._copy_to_clipboard(sel, "Copied")

        def _copy_all():
            self._copy_to_clipboard(widget.get("1.0", "end-1c"), "Whole message copied")

        def _select_all():
            widget.tag_add("sel", "1.0", "end-1c")
            widget.focus_set()

        m = tk.Menu(self.root, tearoff=0, bg=C_BG2, fg=C_FG,
                    activebackground=C_BG4, activeforeground=C_FG)
        m.add_command(label="Copy", command=_copy_sel,
                      state=("normal" if has_sel else "disabled"))
        m.add_command(label="Copy whole message", command=_copy_all)
        m.add_separator()
        m.add_command(label="Select all", command=_select_all)

        # ── ✉ Address mail (manual) — Issu 2026-09-23 ────────────────────────
        # Save the selected text as THE address part: the ✉ turns green and
        # clicking it later pops that text up, so he never has to hunt for where
        # in the mail the address was. Marking the whole mail (no selection) is
        # the lighter variant; both live here, plus in the list right-click.
        m.add_separator()
        _amarked = _addr_is_marked(self._address_store, msg)
        m.add_command(
            label="✉  Save selection as this mail's address",
            state=("normal" if has_sel else "disabled"),
            command=lambda: self._addr_save_selection(
                msg, widget.get("sel.first", "sel.last") if has_sel else ""))
        m.add_command(
            label=("✉  Unmark as address mail" if _amarked
                   else "✉  Mark as address mail (whole mail)"),
            command=lambda: self._addr_toggle_mark(msg))
        # Standing "never show me this again" (DEL 04t2). Right where you are
        # when you notice the junk, rather than in a menu you have to go and
        # find — and it asks before saving, since a rule built from a
        # selection is easy to make wider than you meant.
        m.add_separator()
        m.add_command(
            label="🚫  Always hide text like this (from this sender)…",
            state=("normal" if has_sel else "disabled"),
            command=lambda: self._add_trim_rule_from_text(
                msg, widget.get("sel.first", "sel.last") if has_sel else ""))
        # …and the same thing without having to select anything first: the line
        # you right-clicked ON (Issu 2026-08-17). Selecting a line by dragging
        # is fiddly, and half the time what you want gone is one line.
        line = self._clicked_line(widget, event)
        if line:
            m.add_command(
                label=f"🚫  Never show this line again…   “{line[:38]}"
                      f"{'…' if len(line) > 38 else ''}”",
                command=lambda ln=line: self._hide_line_forever(msg, ln))
        if line and _ATTRIB_RE.search(line):
            m.add_command(
                label="🚫  Never show a “… wrote:” line with nothing under it",
                command=lambda: self._enable_orphan_rule(msg))
        m.add_command(label="Hide-boilerplate rules…",
                      command=self._trim_rules_dialog)
        try:
            m.tk_popup(event.x_root, event.y_root)
        finally:
            m.grab_release()

    def _add_recipient_copy_items(self, m, msg):
        """Add "copy one of the recipients" entries to an open menu.

        Copying the SENDER was the only address any menu could give you (Issu
        2026-08-29: "jag kan bara copy senders adress… jag kanske vill kopiera
        en av mottagarna, som inte är jag… eller kanske t.o.m. som är jag").
        Half the time the address you want is a recipient: the colleague who
        was cc'd, or the alias of your OWN that the mail was really sent to —
        which is not necessarily the account you are reading it in, so your own
        addresses are offered too and simply marked "(you)".

        Each list goes in its own submenu, so a fifty-name circular cannot push
        the rest of the menu off the bottom of the screen. Returns True if it
        added anything."""
        to_val = msg.get("_to_hdr", "") or msg.get("account_email", "") or ""
        cc_val = msg.get("_cc_hdr", "") or ""
        mine   = self._my_addresses()
        added  = False
        for cap, hdr_val in (("To", to_val), ("Cc", cc_val)):
            people = _parse_addr_list(hdr_val)
            if not people:
                continue
            sub = tk.Menu(m, tearoff=0, bg=C_BG2, fg=C_FG,
                          activebackground=C_BG4, activeforeground=C_FG)
            for a in people:
                you = "   (you)" if a.strip().lower() in mine else ""
                sub.add_command(label=f"📋  Copy  {a}{you}",
                                command=lambda x=a: self._copy_to_clipboard(
                                    x, "Address copied"))
            if len(people) > 1:
                sub.add_separator()
                sub.add_command(
                    label=f"📋  Copy all {len(people)} as one line",
                    command=lambda x=list(people): self._copy_to_clipboard(
                        ", ".join(x), f"{len(x)} addresses copied"))
            m.add_cascade(label=f"Copy {cap} recipient  ({len(people)})",
                          menu=sub)
            added = True

        # De-duplicate across To: and Cc:, keeping order — the same person on
        # both is one address, and pasting it twice into a new mail is a small
        # mess you would then have to clean up by hand.
        seen, allr = set(), []
        for a in _parse_addr_list(to_val) + _parse_addr_list(cc_val):
            if a.lower() not in seen:
                seen.add(a.lower()); allr.append(a)
        if len(allr) > 1:
            m.add_command(
                label=f"Copy every recipient  ({len(allr)}, To + Cc)",
                command=lambda x=allr: self._copy_to_clipboard(
                    ", ".join(x), f"{len(x)} addresses copied"))
            added = True
        return added

    def _header_context_menu(self, event, msg):
        """Right-click the top of a message (subject / From / To / Date) to COPY
        it — those are plain Labels you cannot drag-select, so copying was
        impossible (Issu 2026-08-02: "kan inte markera copy i övre delen")."""
        frm_name = msg.get("from_name", "") or ""
        frm_addr = parseaddr(msg.get("from", ""))[1] or msg.get("from", "") or ""
        subject  = msg.get("subject", "") or ""
        to_acct  = msg.get("account_email", "") or ""
        date     = msg.get("date", "") or ""
        # "Copy all header fields" now carries the REAL To:/Cc: and the exact
        # time rather than your own account address and the word "Yesterday"
        # (Issu 2026-08-29) — a pasted header that says "Yesterday" is useless
        # the moment you paste it anywhere you will read again tomorrow.
        whole = (f"Subject: {subject}\nFrom: {frm_name} <{frm_addr}>\n"
                 f"To: {msg.get('_to_hdr', '') or to_acct}\n")
        if msg.get("_cc_hdr"):
            whole += f"Cc: {msg.get('_cc_hdr')}\n"
        whole += f"Date: {_exact_time(msg) or date}"
        m = tk.Menu(self.root, tearoff=0, bg=C_BG2, fg=C_FG,
                    activebackground=C_BG4, activeforeground=C_FG)
        if frm_addr:
            m.add_command(label=f"Copy sender address  ({frm_addr})",
                          command=lambda: self._copy_to_clipboard(
                              frm_addr, "Address copied"))
        if frm_name:
            m.add_command(label="Copy sender name",
                          command=lambda: self._copy_to_clipboard(
                              frm_name, "Name copied"))
        if subject:
            m.add_command(label="Copy subject",
                          command=lambda: self._copy_to_clipboard(
                              subject, "Subject copied"))

        self._add_recipient_copy_items(m, msg)

        # ── Exact time (Issu 2026-08-29) ─────────────────────────────────
        m.add_separator()
        exact = _exact_time(msg)
        m.add_command(label=f"🕐  {exact}", state="disabled")
        m.add_command(label="📋  Copy the exact time",
                      command=lambda t=exact: self._copy_to_clipboard(
                          t, "Exact time copied"))

        m.add_separator()
        m.add_command(label="Copy all header fields",
                      command=lambda: self._copy_to_clipboard(
                          whole, "Header copied"))
        try:
            m.tk_popup(event.x_root, event.y_root)
        finally:
            m.grab_release()

    def _link_context_menu(self, event, url, msg):
        """Right-click menu for a link inside a plain-text body: Open / Copy."""
        m = tk.Menu(self.root, tearoff=0, bg=C_BG2, fg=C_FG,
                    activebackground=C_BG4, activeforeground=C_FG)
        m.add_command(label="Open link",
                      command=lambda u=url, mm=msg: self._open_url(u, mm))
        m.add_command(label="Copy link address",
                      command=lambda u=url: self._copy_to_clipboard(u, "Link copied"))
        try:
            m.tk_popup(event.x_root, event.y_root)
        finally:
            m.grab_release()

    def _remember_recipients(self, payload, is_reply):
        """Auto-save the people a message went to, into the address book.

        On for replies by default, off for brand-new mail by default (Issu
        2026-08-01) — both are settings. Idempotent (merge de-dupes on
        address), so it never grows duplicates."""
        if is_reply:
            if not self.cfg.get("autosave_reply_contacts", True):
                return
        else:
            if not self.cfg.get("autosave_sent_contacts", False):
                return
        raw = []
        for field in ("to", "cc"):
            raw += _re.split(r"[;,]", payload.get(field, "") or "")
        raw += list(payload.get("bcc", []) or [])
        me = (parseaddr(payload.get("from", ""))[1] or "").strip().lower()
        people = []
        for a in raw:
            name, email_ = parseaddr((a or "").strip())
            email_ = (email_ or "").strip()
            # Skip yourself (the BCC-to-self privacy trick would otherwise add
            # your own address every time).
            if email_ and "@" in email_ and email_.lower() != me:
                people.append({"name": name.strip(), "email": email_})
        if not people:
            return
        try:
            if _merge_contacts(self._addressbook_store, people):
                _save_addressbook(self._addressbook_store)
        except Exception as e:
            log.warning("auto-save contacts failed: %s", e)

    # ── Address book ──────────────────────────────────────────────────────────
    def _addressbook_dialog(self, prefill_name="", prefill_email="", parent=None):
        store = self._addressbook_store
        # A transient dialog whose master is MINIMISED is hidden by Windows, but
        # grab_set() still locks every window of the program — so the book was
        # invisible and Freemail (and the half-written mail in front of it)
        # looked frozen (Issu 2026-10-10, opened from the compose window's 📖
        # picker while the main window was minimised). Hang it on the window the
        # user is actually looking at, and never on one that is not showing.
        master = parent if parent is not None else self.root
        try:
            if (not master.winfo_exists()
                    or master.state() in ("iconic", "withdrawn")):
                master = None
        except Exception:
            master = None
        top = tk.Toplevel(master or self.root)
        top.title("Address book — F(re)email")
        top.configure(bg=C_BG3)
        # Taller than it was: the two "remember people I write to" switches now
        # live at the bottom, and the contact list must not shrink for them.
        _center_over(top, master or self.root, 620, 690)
        if master is not None:
            top.transient(master)
        top.deiconify()
        top.lift()
        try:
            top.grab_set()
        except Exception as e:
            log.warning("address book: grab_set failed (%s) — opening "
                        "without a grab", e)
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())

        tk.Label(top, text="👥  Address book", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 13, "bold")).pack(pady=(14, 2))
        tk.Label(top,
                 text="Saved contacts. Names here auto-complete the To: field "
                      "when you compose a message.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8),
                 wraplength=560, justify="center").pack(pady=(0, 8))

        # Search/filter box
        fr = tk.Frame(top, bg=C_BG3, padx=16); fr.pack(fill="x")
        tk.Label(fr, text="Filter:", bg=C_BG3, fg=C_FG_DIM, width=10, anchor="e",
                 font=("Segoe UI", 9)).pack(side="left")
        e_filter = tk.Entry(fr, bg=C_BG2, fg=C_FG, relief="flat",
                            insertbackground=C_ACCENT, font=("Segoe UI", 9),
                            insertofftime=0, insertontime=9999999)
        no_blink(e_filter); e_filter.pack(side="left", fill="x", expand=True, ipady=2)

        # Scrollable people list
        list_wrap = tk.Frame(top, bg=C_BG2)
        list_wrap.pack(fill="both", expand=True, padx=16, pady=(6, 6))
        lcanvas = tk.Canvas(list_wrap, bg=C_BG2, highlightthickness=0, height=180)
        lsb = tk.Scrollbar(list_wrap, orient="vertical", command=lcanvas.yview,
                           bg=C_BG3, troughcolor=C_BG1)
        lsb.pack(side="right", fill="y")
        lcanvas.configure(yscrollcommand=lsb.set)
        lcanvas.pack(fill="both", expand=True)
        linner = tk.Frame(lcanvas, bg=C_BG2)
        lwin = lcanvas.create_window((0, 0), window=linner, anchor="nw")
        linner.bind("<Configure>",
                    lambda e: lcanvas.configure(scrollregion=lcanvas.bbox("all")))
        lcanvas.bind("<Configure>",
                     lambda e: lcanvas.itemconfig(lwin, width=e.width))
        _bind_mousewheel(linner, lcanvas)

        # Which contact the form below is editing right now. idx is the index
        # into store["people"]; email is what it was called when the edit
        # started, so a RENAMED address replaces the old record instead of
        # leaving a twin behind (Issu 2026-08-25).
        editing = {"idx": None, "email": None}

        def _render_list():
            for w in linner.winfo_children():
                w.destroy()
            q = e_filter.get().strip().lower()
            people = store.get("people", [])
            shown = [(i, p) for i, p in enumerate(people)
                     if not q or q in p.get("name", "").lower()
                     or q in p.get("email", "").lower()
                     or q in p.get("group", "").lower()]
            if not shown:
                tk.Label(linner, text="(no matching contacts)",
                         bg=C_BG2, fg=C_FG_DIM, font=("Segoe UI", 9, "italic"),
                         anchor="w", padx=8, pady=8).pack(fill="x")
                return
            for i, p in shown:
                picked = (editing["idx"] == i)
                row = tk.Frame(linner,
                               bg=C_MSG_SEL if picked
                               else (C_BG3 if i % 2 else C_BG2))
                row.pack(fill="x", pady=1)
                # ★ toggles Favorite (shown first in the compose recipient
                # picker) — Issu 2026-08-01.
                def _toggle_fav(idx=i):
                    ppl = store.get("people", [])
                    if 0 <= idx < len(ppl):
                        ppl[idx]["favorite"] = not ppl[idx].get("favorite")
                        _save_addressbook(store)
                        _render_list()
                is_fav = bool(p.get("favorite"))
                tk.Button(row, text="★" if is_fav else "☆",
                          bg=row["bg"], fg="#ffcf5a" if is_fav else C_FG_DIM,
                          relief="flat", font=("Segoe UI", 10),
                          cursor="hand2", bd=0, activebackground=row["bg"],
                          command=_toggle_fav).pack(side="left", padx=(4, 0))
                txt = f"  {p.get('name','') or p.get('email','')}   <{p.get('email','')}>"
                if p.get("group"):
                    txt += f"   ·   {p['group']}"
                lbl = tk.Label(row, text=txt, bg=row["bg"],
                               fg=C_ACCENT if picked else C_FG,
                               font=("Segoe UI", 9), anchor="w", cursor="hand2")
                lbl.pack(side="left", fill="x", expand=True)
                # Click the row → it drops into the form below (Issu
                # 2026-08-25: "jag kan inte klicka på någon kontakt och få dem
                # till den rutan, för att redigera"). Both the row and its
                # label carry the binding, so the gap after the text works too.
                for w in (row, lbl):
                    w.bind("<Button-1>", lambda e, idx=i: _edit_contact(idx))
                tk.Button(row, text="✕", bg=C_BTN_DEL, fg=C_BTN_FG, relief="flat",
                          font=("Segoe UI", 8, "bold"), cursor="hand2",
                          command=lambda idx=i: _delete_contact(idx)).pack(
                              side="right", padx=4, pady=2)

        def _delete_contact(idx):
            ppl = store.get("people", [])
            if not (0 <= idx < len(ppl)):
                return
            ppl.pop(idx)
            _save_addressbook(store)
            # The form was pointing at a row number that has just moved.
            if editing["idx"] is not None:
                _clear_form()
            else:
                _render_list()

        e_filter.bind("<KeyRelease>", lambda e: _render_list())
        _render_list()

        # Add form
        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x", padx=16, pady=4)
        form = tk.Frame(top, bg=C_BG3, padx=16); form.pack(fill="x")
        l_mode = tk.Label(form, text="New contact — or click one in the list "
                                     "above to edit it",
                          bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                          anchor="w")
        l_mode.pack(fill="x", pady=(2, 0))
        def _field(label, val=""):
            r = tk.Frame(form, bg=C_BG3); r.pack(fill="x", pady=2)
            tk.Label(r, text=label, bg=C_BG3, fg=C_FG_DIM, width=10, anchor="e",
                     font=("Segoe UI", 9)).pack(side="left")
            e = tk.Entry(r, bg=C_BG2, fg=C_FG, relief="flat",
                         insertbackground=C_ACCENT, font=("Segoe UI", 9),
                         insertofftime=0, insertontime=9999999)
            no_blink(e); e.pack(side="left", fill="x", expand=True, ipady=2)
            if val:
                e.insert(0, val)
            return e
        e_name  = _field("Name:", prefill_name)
        e_email = _field("Email:", prefill_email)
        e_group = _field("Group:")

        def _clear_form():
            """Back to "new contact" — nothing selected, fields empty."""
            editing["idx"] = None
            editing["email"] = None
            for e in (e_name, e_email, e_group):
                e.delete(0, "end")
            l_mode.config(text="New contact — or click one in the list above "
                               "to edit it", fg=C_FG_DIM)
            b_add.config(text="➕ Add / update")
            _render_list()

        def _edit_contact(idx):
            """A row was clicked: put it in the form, ready to change."""
            ppl = store.get("people", [])
            if not (0 <= idx < len(ppl)):
                return
            p = ppl[idx]
            editing["idx"] = idx
            editing["email"] = (p.get("email") or "").strip()
            e_name.delete(0, "end");  e_name.insert(0, p.get("name", "") or "")
            e_email.delete(0, "end"); e_email.insert(0, p.get("email", "") or "")
            e_group.delete(0, "end"); e_group.insert(0, p.get("group", "") or "")
            l_mode.config(
                text=f"Editing  {p.get('name') or p.get('email') or ''}  "
                     f"— change anything and press Save changes",
                fg=C_ACCENT)
            b_add.config(text="💾 Save changes")
            _render_list()
            e_name.focus_set()

        def _add():
            name = e_name.get().strip(); email = e_email.get().strip()
            if not email:
                self._flash("Email is required"); return
            # Clean here too, so a corrupt address cannot be stored by hand and
            # then handed back out by autocomplete for years (Issu 2026-08-01).
            clean, changed = _clean_one_address(email)
            if changed:
                log.error("ADDRESS CORRUPTION [address book form]: %r → %r    %s",
                          email, clean, _addr_forensics(email))
                email = (parseaddr(clean)[1] or clean).strip()
                e_email.delete(0, "end"); e_email.insert(0, email)
            # The never-save list stops the AUTOMATIC paths outright, but here
            # a person typed the address on purpose — so it asks instead of
            # refusing (Issu 2026-08-25).
            rule = _never_save_match(email, store.get("never_save", []))
            if rule and not messagebox.askyesno(
                    "Never-save list",
                    f"{email}\n\nmatches your never-save rule\n"
                    f"    {_NEVER_KIND_LABEL.get(rule.get('kind'), rule.get('kind'))}"
                    f"  “{rule.get('value')}”\n\n"
                    "Rules only stop addresses being saved automatically.\n"
                    "Add this one by hand anyway?", parent=top):
                return
            people = store.setdefault("people", [])
            # Keep the ★ and anything else already known about this person, so
            # editing a name does not quietly un-favorite them.
            old = {}
            if editing["idx"] is not None and 0 <= editing["idx"] < len(people):
                old = dict(people[editing["idx"]])
            else:
                for p in people:
                    if (p.get("email") or "").lower() == email.lower():
                        old = dict(p); break
            drop = {email.lower()}
            if editing["email"]:
                drop.add(editing["email"].lower())   # the address it had before
            people[:] = [p for p in people
                         if (p.get("email") or "").lower() not in drop]
            old.update({"name": name, "email": email,
                        "group": e_group.get().strip()})
            people.append(old)
            people.sort(key=lambda p: (p.get("name") or p.get("email") or "").lower())
            _save_addressbook(store)
            was_edit = editing["idx"] is not None
            _clear_form()
            self._flash("Contact updated" if was_edit else "Contact added")
        brow = tk.Frame(form, bg=C_BG3); brow.pack(anchor="w", padx=(82, 0),
                                                   pady=(4, 2))
        b_add = tk.Button(brow, text="➕ Add / update", bg=C_BTN_NEW, fg=C_BTN_FG,
                          relief="flat", padx=10, pady=3, cursor="hand2",
                          command=_add)
        b_add.pack(side="left")
        b_new = tk.Button(brow, text="✖ Clear", bg=C_BTN_STD, fg=C_BTN_FG,
                          relief="flat", padx=10, pady=3, cursor="hand2",
                          command=_clear_form)
        b_new.pack(side="left", padx=(6, 0))
        add_tooltip(b_new, "Empty the fields and stop editing the contact you "
                           "clicked — the next Add makes a NEW one.")
        e_email.bind("<Return>", lambda e: _add())
        e_name.bind("<Return>", lambda e: _add())
        e_group.bind("<Return>", lambda e: _add())
        top.bind("<Escape>", lambda e: (_clear_form() if editing["idx"] is not None
                                        else top.destroy()))

        # ── Auto-save the people you write to (Issu 2026-08-01) ───────────────
        # These two used to be editable only in settings.json. This is where
        # they belong: right under the book they fill.
        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x", padx=16, pady=(8, 4))
        auto = tk.Frame(top, bg=C_BG3, padx=16)
        auto.pack(fill="x")
        tk.Label(auto, text="Remember people I write to, automatically:",
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 9, "bold"),
                 anchor="w").pack(fill="x")
        v_reply = tk.BooleanVar(
            value=bool(self.cfg.get("autosave_reply_contacts", True)))
        v_sent  = tk.BooleanVar(
            value=bool(self.cfg.get("autosave_sent_contacts", False)))

        def _auto_save_changed():
            self.cfg["autosave_reply_contacts"] = bool(v_reply.get())
            self.cfg["autosave_sent_contacts"]  = bool(v_sent.get())
            _save_settings(self.cfg)

        cb1 = tk.Checkbutton(auto, text="when I REPLY to someone  (recommended)",
                             variable=v_reply, command=_auto_save_changed,
                             bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                             activebackground=C_BG3, activeforeground=C_FG,
                             font=("Segoe UI", 9), highlightthickness=0,
                             anchor="w")
        cb1.pack(fill="x", padx=12)
        add_tooltip(cb1, "Someone you answered is someone you know — their "
                         "address is added here so it auto-completes next time.")
        cb2 = tk.Checkbutton(auto, text="when I send a NEW message to someone",
                             variable=v_sent, command=_auto_save_changed,
                             bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                             activebackground=C_BG3, activeforeground=C_FG,
                             font=("Segoe UI", 9), highlightthickness=0,
                             anchor="w")
        cb2.pack(fill="x", padx=12)
        add_tooltip(cb2, "Off by default: a one-off mail to a web shop does not "
                         "have to end up in your address book forever.")
        tk.Label(auto, text="Never duplicates: an address already here is "
                            "merged, not added twice.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 anchor="w").pack(fill="x", padx=12, pady=(0, 2))

        def _check_addresses():
            """Find contacts whose address cannot be right, and offer to mend
            them (Issu 2026-08-01).

            A corrupt address stored here is the reason the same mistake can
            come back months later: autocomplete and the 📖 picker hand it out
            again every time. Three kinds are reported — characters that cannot
            be in an address at all, a domain that merely LOOKS like gmail.com,
            and anything that is not an address in the first place."""
            people = store.get("people", [])
            fixable, odd = [], []
            for p in people:
                addr = (p.get("email") or "").strip()
                if not addr:
                    continue
                clean, changed = _clean_one_address(addr)
                bare = (parseaddr(clean)[1] or clean).strip()
                look = _gmail_lookalike(bare)
                if changed or look:
                    fixable.append((p, addr, look or bare))
                elif not _EMAIL_RE.match(bare):
                    odd.append((p, addr))
            if not fixable and not odd:
                messagebox.showinfo(
                    "Check addresses",
                    f"All {len(people)} address(es) look fine.",
                    parent=top)
                return
            lines = []
            if fixable:
                lines.append("These can be mended:")
                lines += [f"   {a}\n        →  {new}" for _p, a, new in fixable[:15]]
                if len(fixable) > 15:
                    lines.append(f"   … and {len(fixable) - 15} more")
            if odd:
                lines.append("")
                lines.append("These are not addresses at all — mend them by "
                             "hand, nothing is changed for them:")
                lines += [f"   {a}" for _p, a in odd[:10]]
            if not fixable:
                messagebox.showinfo("Check addresses", "\n".join(lines),
                                    parent=top)
                return
            if not messagebox.askyesno(
                    "Check addresses",
                    "\n".join(lines) + f"\n\nMend the {len(fixable)} "
                    f"address(es) above?", parent=top):
                return
            for p, old, new in fixable:
                log.warning("Address book mended: %r → %r    %s",
                            old, new, _addr_forensics(old))
                p["email"] = new
            _save_addressbook(store)
            _render_list()
            self._flash(f"{len(fixable)} address(es) mended")

        # ── Never save these (Issu 2026-08-25) ────────────────────────────────
        def _neversave_dialog():
            """Edit the list of addresses that must never reach the book.

            Four kinds, because that is how the junk actually looks: one exact
            robot address, a whole domain, everything that STARTS with
            "noreply", or everything that ENDS with "-bounce" / ".ru"."""
            rules = store.setdefault("never_save", [])
            t2 = tk.Toplevel(top)
            t2.title("Never save in Contacts — F(re)email")
            t2.configure(bg=C_BG3)
            _center_over(t2, top, 600, 600)
            t2.transient(top); t2.grab_set(); t2.focus_force()
            t2.bind("<Escape>", lambda e: t2.destroy())

            tk.Label(t2, text="🚫  Never save these in Contacts", bg=C_BG3,
                     fg=C_ACCENT, font=("Segoe UI", 13, "bold")).pack(pady=(14, 2))
            tk.Label(t2,
                     text="An address matching any rule below is never added "
                          "to the address book automatically — not when you "
                          "reply, not from an import. You can still add one by "
                          "hand; it just asks first.",
                     bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8),
                     wraplength=540, justify="center").pack(pady=(0, 8))

            rwrap = tk.Frame(t2, bg=C_BG2)
            rwrap.pack(fill="both", expand=True, padx=16, pady=(4, 6))
            rcanvas = tk.Canvas(rwrap, bg=C_BG2, highlightthickness=0, height=180)
            rsb = tk.Scrollbar(rwrap, orient="vertical", command=rcanvas.yview,
                               bg=C_BG3, troughcolor=C_BG1)
            rsb.pack(side="right", fill="y")
            rcanvas.configure(yscrollcommand=rsb.set)
            rcanvas.pack(fill="both", expand=True)
            rinner = tk.Frame(rcanvas, bg=C_BG2)
            rwin = rcanvas.create_window((0, 0), window=rinner, anchor="nw")
            rinner.bind("<Configure>",
                        lambda e: rcanvas.configure(scrollregion=rcanvas.bbox("all")))
            rcanvas.bind("<Configure>",
                         lambda e: rcanvas.itemconfig(rwin, width=e.width))
            _bind_mousewheel(rinner, rcanvas)

            def _render_rules():
                for w in rinner.winfo_children():
                    w.destroy()
                if not rules:
                    tk.Label(rinner, text="(no rules yet — everything is saved)",
                             bg=C_BG2, fg=C_FG_DIM,
                             font=("Segoe UI", 9, "italic"),
                             anchor="w", padx=8, pady=8).pack(fill="x")
                    return
                for i, r in enumerate(rules):
                    row = tk.Frame(rinner, bg=C_BG3 if i % 2 else C_BG2)
                    row.pack(fill="x", pady=1)
                    kind = (r.get("kind") or "address").lower()
                    tk.Label(row, text=_NEVER_KIND_LABEL.get(kind, kind),
                             bg=row["bg"], fg=C_FG_DIM, width=12, anchor="w",
                             font=("Segoe UI", 9)).pack(side="left", padx=(8, 0))
                    tk.Label(row, text=r.get("value", ""), bg=row["bg"], fg=C_FG,
                             font=("Segoe UI", 9), anchor="w").pack(
                                 side="left", fill="x", expand=True)
                    tk.Button(row, text="✕", bg=C_BTN_DEL, fg=C_BTN_FG,
                              relief="flat", font=("Segoe UI", 8, "bold"),
                              cursor="hand2",
                              command=lambda idx=i: (rules.pop(idx),
                                                     _save_addressbook(store),
                                                     _render_rules())).pack(
                                  side="right", padx=4, pady=2)
            _render_rules()

            # ── Add a rule ───────────────────────────────────────────────────
            tk.Frame(t2, bg=C_SEP, height=1).pack(fill="x", padx=16, pady=4)
            arow = tk.Frame(t2, bg=C_BG3, padx=16); arow.pack(fill="x", pady=(4, 0))
            v_kind = tk.StringVar(value=_NEVER_KIND_LABEL["prefix"])
            om = tk.OptionMenu(arow, v_kind,
                               *[_NEVER_KIND_LABEL[k] for k in _NEVER_KINDS])
            om.configure(bg=C_BTN_STD, fg=C_BTN_FG, relief="flat", width=12,
                         highlightthickness=0, activebackground=C_BG4,
                         font=("Segoe UI", 9), cursor="hand2")
            om["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                                 activeforeground=C_FG)
            om.pack(side="left")
            e_val = tk.Entry(arow, bg=C_BG2, fg=C_FG, relief="flat",
                             insertbackground=C_ACCENT, font=("Segoe UI", 9),
                             insertofftime=0, insertontime=9999999)
            no_blink(e_val)
            e_val.pack(side="left", fill="x", expand=True, ipady=2, padx=6)

            def _add_rule():
                val = e_val.get().strip().lstrip("@")
                if not val:
                    self._flash("Type something to never save"); return
                label = v_kind.get()
                kind = next((k for k in _NEVER_KINDS
                             if _NEVER_KIND_LABEL[k] == label), "address")
                if any((r.get("kind") == kind
                        and (r.get("value") or "").lower() == val.lower())
                       for r in rules):
                    self._flash("That rule is already in the list"); return
                rules.append({"kind": kind, "value": val})
                _save_addressbook(store)
                e_val.delete(0, "end")
                _render_rules()
            tk.Button(arow, text="➕ Add rule", bg=C_BTN_NEW, fg=C_BTN_FG,
                      relief="flat", padx=10, pady=3, cursor="hand2",
                      command=_add_rule).pack(side="left")
            e_val.bind("<Return>", lambda e: _add_rule())

            tk.Label(t2,
                     text="Address is  —  the exact address.        "
                          "Domain is  —  that domain and anything under it.\n"
                          "Starts with  —  noreply, no-reply, info…        "
                          "Ends with  —  -bounce, .ru, +shop…",
                     bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8),
                     justify="left", anchor="w").pack(fill="x", padx=16,
                                                      pady=(6, 2))

            def _add_suggested():
                new = [r for r in _NEVER_SAVE_SUGGESTED
                       if not any(x.get("kind") == r["kind"]
                                  and (x.get("value") or "").lower()
                                      == r["value"] for x in rules)]
                if not new:
                    self._flash("They are all in the list already"); return
                rules.extend({"kind": r["kind"], "value": r["value"]} for r in new)
                _save_addressbook(store)
                _render_rules()
                self._flash(f"{len(new)} rule(s) added")

            def _clean_book():
                """Apply the rules to what is ALREADY saved.

                Rules only guard the door; this is the broom for the contacts
                that came in before the door had a lock. Nothing goes without
                the list being shown first."""
                people = store.get("people", [])
                hits = [(p, _never_save_match(p.get("email", ""), rules))
                        for p in people]
                hits = [(p, r) for p, r in hits if r]
                if not hits:
                    messagebox.showinfo(
                        "Clean the address book",
                        "No saved contact matches your never-save rules.",
                        parent=t2)
                    return
                lines = [f"   {p.get('email','')}"
                         f"      ({_NEVER_KIND_LABEL.get(r.get('kind'), '')} "
                         f"“{r.get('value')}”)" for p, r in hits[:20]]
                if len(hits) > 20:
                    lines.append(f"   … and {len(hits) - 20} more")
                if not messagebox.askyesno(
                        "Clean the address book",
                        f"{len(hits)} saved contact(s) match your never-save "
                        "rules:\n\n" + "\n".join(lines) +
                        "\n\nRemove them from the address book?", parent=t2):
                    return
                drop = {id(p) for p, _r in hits}
                people[:] = [p for p in people if id(p) not in drop]
                _save_addressbook(store)
                _clear_form()
                self._flash(f"{len(hits)} contact(s) removed")

            b2 = tk.Frame(t2, bg=C_BG3); b2.pack(pady=10)
            b_sug = tk.Button(b2, text="✨ Add the usual robots", bg=C_BTN_STD,
                              fg=C_BTN_FG, relief="flat", padx=12, pady=4,
                              cursor="hand2", command=_add_suggested)
            b_sug.pack(side="left", padx=5)
            add_tooltip(b_sug, "Adds noreply, no-reply, donotreply, bounce, "
                               "mailer-daemon, postmaster and friends as "
                               "\"Starts with\" rules. Nothing is removed.")
            b_cln = tk.Button(b2, text="🧹 Clean the book now", bg=C_BTN_STD,
                              fg=C_BTN_FG, relief="flat", padx=12, pady=4,
                              cursor="hand2", command=_clean_book)
            b_cln.pack(side="left", padx=5)
            add_tooltip(b_cln, "Applies the rules to contacts you already have. "
                               "Shows the list first — nothing is removed "
                               "without your yes.")
            tk.Button(b2, text="Close", bg=C_BTN_NEW, fg=C_BTN_FG, relief="flat",
                      padx=16, pady=4, cursor="hand2",
                      command=t2.destroy).pack(side="left", padx=5)

        def _save_close():
            _auto_save_changed()
            _save_addressbook(store); top.destroy()
            self._flash("Address book saved")
        br = tk.Frame(top, bg=C_BG3); br.pack(pady=10)
        tk.Button(br, text="Save & Close", bg=C_BTN_NEW, fg=C_BTN_FG, relief="flat",
                  padx=16, pady=4, cursor="hand2", command=_save_close).pack(
                      side="left", padx=6)
        b_chk = tk.Button(br, text="🩺 Check addresses", bg=C_BTN_STD,
                          fg=C_BTN_FG, relief="flat", padx=16, pady=4,
                          cursor="hand2", command=_check_addresses)
        b_chk.pack(side="left", padx=6)
        add_tooltip(b_chk, "Looks for stored addresses that cannot be right — "
                           "stray characters, or a domain that only looks like "
                           "gmail.com — and offers to mend them. Nothing is "
                           "changed without asking.")
        b_nev = tk.Button(br, text="🚫 Never save…", bg=C_BTN_STD,
                          fg=C_BTN_FG, relief="flat", padx=14, pady=4,
                          cursor="hand2", command=_neversave_dialog)
        b_nev.pack(side="left", padx=6)
        add_tooltip(b_nev, "Addresses, domains, prefixes and suffixes that must "
                           "never be saved here automatically — noreply@, a "
                           "whole shop domain, anything ending in -bounce.")
        tk.Button(br, text="Cancel", bg=C_BTN_STD, fg=C_BTN_FG, relief="flat",
                  padx=16, pady=4, cursor="hand2", command=top.destroy).pack(
                      side="left", padx=6)
        if prefill_email:
            e_name.focus_set()

    # ── Contact colours editor ────────────────────────────────────────────────
    def _contacts_dialog(self):
        from tkinter import colorchooser
        store = self._contacts_store
        top = tk.Toplevel(self.root)
        top.title("Contact colours — F(re)email")
        top.configure(bg=C_BG3)
        _center_over(top, self.root, 600, 560)
        top.transient(self.root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())

        tk.Label(top, text="🎨  Contact colours", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 13, "bold")).pack(pady=(14, 2))
        tk.Label(top,
                 text="Give a sender a colour so their messages stand out in the "
                      "list. Give several senders the SAME colour to make a group.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8),
                 wraplength=560, justify="center").pack(pady=(0, 8))

        # ── Existing contacts (scrollable) ────────────────────────────────────
        list_wrap = tk.Frame(top, bg=C_BG2)
        list_wrap.pack(fill="both", expand=True, padx=16, pady=(2, 6))
        lcanvas = tk.Canvas(list_wrap, bg=C_BG2, highlightthickness=0, height=180)
        lsb = tk.Scrollbar(list_wrap, orient="vertical", command=lcanvas.yview,
                           bg=C_BG3, troughcolor=C_BG1)
        lsb.pack(side="right", fill="y")
        lcanvas.configure(yscrollcommand=lsb.set)
        lcanvas.pack(fill="both", expand=True)
        linner = tk.Frame(lcanvas, bg=C_BG2)
        lwin = lcanvas.create_window((0, 0), window=linner, anchor="nw")
        linner.bind("<Configure>",
                    lambda e: lcanvas.configure(scrollregion=lcanvas.bbox("all")))
        lcanvas.bind("<Configure>",
                     lambda e: lcanvas.itemconfig(lwin, width=e.width))
        _bind_mousewheel(linner, lcanvas)

        def _render_list():
            for w in linner.winfo_children():
                w.destroy()
            contacts = store.get("contacts", [])
            if not contacts:
                tk.Label(linner, text="(no contacts yet — add one below)",
                         bg=C_BG2, fg=C_FG_DIM, font=("Segoe UI", 9, "italic"),
                         anchor="w", padx=8, pady=8).pack(fill="x")
                return
            for i, c in enumerate(contacts):
                row = tk.Frame(linner, bg=C_BG3 if i % 2 else C_BG2)
                row.pack(fill="x", pady=1)
                tk.Label(row, text="  ●  ", bg=row["bg"], fg=c.get("color", "#ffffff"),
                         font=("Segoe UI", 12, "bold")).pack(side="left")
                lab = f"  {c.get('match','')}"
                if c.get("label"):
                    lab += f"   ·   {c['label']}"
                tk.Label(row, text=lab, bg=row["bg"], fg=C_FG,
                         font=("Segoe UI", 9), anchor="w").pack(
                             side="left", fill="x", expand=True)
                tk.Button(row, text="✕", bg=C_BTN_DEL, fg=C_BTN_FG, relief="flat",
                          font=("Segoe UI", 8, "bold"), cursor="hand2",
                          command=lambda idx=i: (store["contacts"].pop(idx),
                                                 _render_list())).pack(
                              side="right", padx=4, pady=2)
        _render_list()

        # ── Add form ──────────────────────────────────────────────────────────
        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x", padx=16, pady=4)
        form = tk.Frame(top, bg=C_BG3, padx=16)
        form.pack(fill="x")

        def _field(label):
            r = tk.Frame(form, bg=C_BG3); r.pack(fill="x", pady=2)
            tk.Label(r, text=label, bg=C_BG3, fg=C_FG_DIM, width=14, anchor="e",
                     font=("Segoe UI", 9)).pack(side="left")
            e = tk.Entry(r, bg=C_BG2, fg=C_FG, relief="flat",
                         insertbackground=C_ACCENT, font=("Segoe UI", 9),
                         insertofftime=0, insertontime=9999999)
            no_blink(e)
            e.pack(side="left", fill="x", expand=True, ipady=2)
            return e

        e_match = _field("Sender contains:")
        e_label = _field("Group label:")

        # Colour palette picker
        chosen = {"color": CONTACT_PALETTE[0]}
        pr = tk.Frame(form, bg=C_BG3); pr.pack(fill="x", pady=(4, 2))
        tk.Label(pr, text="Colour:", bg=C_BG3, fg=C_FG_DIM, width=14, anchor="e",
                 font=("Segoe UI", 9)).pack(side="left")
        swatches = {}
        def _select_color(col):
            chosen["color"] = col
            for cc, sw in swatches.items():
                sw.configure(relief="solid" if cc == col else "flat",
                             bd=2 if cc == col else 0)
        for col in CONTACT_PALETTE:
            sw = tk.Label(pr, bg=col, width=2, height=1, cursor="hand2",
                          relief="flat", bd=0)
            sw.pack(side="left", padx=2)
            sw.bind("<Button-1>", lambda e, c=col: _select_color(c))
            swatches[col] = sw
        def _custom():
            res = colorchooser.askcolor(parent=top, title="Pick a colour")
            if res and res[1]:
                chosen["color"] = res[1]
                for sw in swatches.values():
                    sw.configure(relief="flat", bd=0)
        tk.Button(pr, text="More…", bg=C_BTN_STD, fg=C_BTN_FG, relief="flat",
                  font=("Segoe UI", 8), cursor="hand2", command=_custom).pack(
                      side="left", padx=6)
        _select_color(CONTACT_PALETTE[0])

        def _add():
            mt = e_match.get().strip()
            if not mt:
                self._flash("Enter what the sender contains")
                return
            store.setdefault("contacts", []).append({
                "match": mt, "color": chosen["color"],
                "label": e_label.get().strip()})
            e_match.delete(0, "end"); e_label.delete(0, "end")
            _render_list()
        tk.Button(form, text="➕ Add contact", bg=C_BTN_NEW, fg=C_BTN_FG,
                  relief="flat", padx=10, pady=3, cursor="hand2",
                  command=_add).pack(anchor="w", padx=(118, 0), pady=(4, 2))

        def _save_close():
            _save_contacts(store)
            top.destroy()
            # Re-render the list so colours apply immediately.
            self._render_msg_list()
            self._flash("Contact colours saved")
        br = tk.Frame(top, bg=C_BG3); br.pack(pady=10)
        tk.Button(br, text="Save & Close", bg=C_BTN_NEW, fg=C_BTN_FG, relief="flat",
                  padx=16, pady=4, cursor="hand2", command=_save_close).pack(
                      side="left", padx=6)
        tk.Button(br, text="Cancel", bg=C_BTN_STD, fg=C_BTN_FG, relief="flat",
                  padx=16, pady=4, cursor="hand2", command=top.destroy).pack(
                      side="left", padx=6)

    # ── Account colours editor (DEL 09c) ──────────────────────────────────────
    def _account_colours_dialog(self):
        """Pick a colour for each account. The colour is what a folder wears in
        the sidebar and how a message is tinted in the All Accounts view."""
        from tkinter import colorchooser
        reals = [a for a in self._accounts if not a.get("virtual")]
        if not reals:
            messagebox.showinfo("Account colours",
                                "Add an account first — demo accounts already "
                                "have colours, but there is nothing to save.",
                                parent=self.root)
            return

        top = tk.Toplevel(self.root)
        top.title("Account colours — F(re)email")
        top.configure(bg=C_BG3)
        top.resizable(False, False)
        _center_over(top, self.root, 560, 160 + 46 * len(reals))
        top.transient(self.root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())

        tk.Label(top, text="🎨  Account colours", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 13, "bold")).pack(pady=(14, 2))
        tk.Label(top,
                 text="Each account has its own colour. Its folders wear it in "
                      "the sidebar, and in the All Accounts view every message "
                      "is tinted with the colour of the account it arrived on.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8),
                 wraplength=520, justify="center").pack(pady=(0, 10))

        # Working copy of the current colours, edited live in the dialog.
        working = {a["email"]: self._acct_colors.get(a["email"],
                                                      ACCOUNT_PALETTE[0])
                   for a in reals}
        swatch_lbls = {}

        rows = tk.Frame(top, bg=C_BG3, padx=20)
        rows.pack(fill="x")

        def _apply_swatch(email):
            swatch_lbls[email].configure(bg=working[email])

        def _pick_palette(email, col):
            working[email] = col
            _apply_swatch(email)

        def _pick_custom(email):
            res = colorchooser.askcolor(parent=top, color=working[email],
                                        title="Pick an account colour")
            if res and res[1]:
                working[email] = res[1]
                _apply_swatch(email)

        for a in reals:
            email = a["email"]
            r = tk.Frame(rows, bg=C_BG3)
            r.pack(fill="x", pady=5)
            sw = tk.Label(r, bg=working[email], width=3, height=1,
                          relief="solid", bd=1)
            sw.pack(side="left")
            swatch_lbls[email] = sw
            tk.Label(r, text=f"  {a.get('name') or email}",
                     bg=C_BG3, fg=C_FG, font=("Segoe UI", 9, "bold"),
                     anchor="w", width=22).pack(side="left")
            # A compact palette of quick swatches + a "More…" custom picker.
            pal = tk.Frame(r, bg=C_BG3)
            pal.pack(side="left")
            for col in ACCOUNT_PALETTE:
                q = tk.Label(pal, bg=col, width=2, height=1, cursor="hand2",
                             relief="flat", bd=0)
                q.pack(side="left", padx=1)
                q.bind("<Button-1>",
                       lambda e, em=email, c=col: _pick_palette(em, c))
            tk.Button(r, text="More…", bg=C_BTN_STD, fg=C_BTN_FG, relief="flat",
                      font=("Segoe UI", 8), cursor="hand2",
                      command=lambda em=email: _pick_custom(em)).pack(
                          side="left", padx=6)

        def _save_close():
            self._account_store.setdefault("colors", {})
            for email, col in working.items():
                self._account_store["colors"][email] = col
            _save_account_store(self._account_store)
            self._assign_account_colors()
            top.destroy()
            self._populate_sidebar(self.sidebar_inner)
            self._render_msg_list()
            self._flash("Account colours saved")

        def _reset():
            # Clear custom colours → fall back to the auto palette order.
            self._account_store.pop("colors", None)
            _save_account_store(self._account_store)
            self._assign_account_colors()
            top.destroy()
            self._populate_sidebar(self.sidebar_inner)
            self._render_msg_list()
            self._flash("Account colours reset")

        br = tk.Frame(top, bg=C_BG3)
        br.pack(pady=12)
        tk.Button(br, text="Save & Close", bg=C_BTN_NEW, fg=C_BTN_FG,
                  relief="flat", padx=16, pady=4, cursor="hand2",
                  command=_save_close).pack(side="left", padx=6)
        tk.Button(br, text="Reset to defaults", bg=C_BTN_STD, fg=C_BTN_FG,
                  relief="flat", padx=16, pady=4, cursor="hand2",
                  command=_reset).pack(side="left", padx=6)
        tk.Button(br, text="Cancel", bg=C_BTN_STD, fg=C_BTN_FG, relief="flat",
                  padx=16, pady=4, cursor="hand2", command=top.destroy).pack(
                      side="left", padx=6)

    # ── Attachment auto-save rules editor ─────────────────────────────────────
    def _autosave_rules_dialog(self):
        from tkinter import filedialog
        store = self._autosave_store
        top = tk.Toplevel(self.root)
        top.title("Attachment auto-save rules — F(re)email")
        top.configure(bg=C_BG3)
        _center_over(top, self.root, 640, 560)
        top.transient(self.root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())

        tk.Label(top, text="📎  Attachment auto-save rules", bg=C_BG3,
                 fg=C_ACCENT, font=("Segoe UI", 13, "bold")).pack(pady=(14, 2))
        tk.Label(top,
                 text="Attachments from matching senders are saved automatically "
                      "on every fetch (read-only — nothing on Gmail changes).",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8),
                 wraplength=600, justify="center").pack(pady=(0, 8))

        # ── Default folder ────────────────────────────────────────────────────
        dfrm = tk.Frame(top, bg=C_BG3, padx=16)
        dfrm.pack(fill="x")
        tk.Label(dfrm, text="Default folder:", bg=C_BG3, fg=C_FG_DIM,
                 width=14, anchor="e", font=("Segoe UI", 9)).pack(side="left")
        e_dir = tk.Entry(dfrm, bg=C_BG2, fg=C_FG, relief="flat",
                         insertbackground=C_ACCENT, font=("Segoe UI", 9),
                         insertofftime=0, insertontime=9999999)
        no_blink(e_dir)
        e_dir.pack(side="left", fill="x", expand=True, ipady=3)
        e_dir.insert(0, store.get("default_dir", ""))

        def _browse():
            d = filedialog.askdirectory(parent=top, title="Choose default folder")
            if d:
                e_dir.delete(0, "end"); e_dir.insert(0, d)
        tk.Button(dfrm, text="Browse…", bg=C_BTN_STD, fg=C_BTN_FG, relief="flat",
                  padx=8, cursor="hand2", command=_browse).pack(side="left", padx=4)

        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x", padx=16, pady=8)

        # ── Existing rules list (scrollable) ──────────────────────────────────
        tk.Label(top, text="Rules:", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 9, "bold"), anchor="w",
                 padx=16).pack(fill="x")

        list_wrap = tk.Frame(top, bg=C_BG2)
        list_wrap.pack(fill="both", expand=True, padx=16, pady=(2, 6))
        lcanvas = tk.Canvas(list_wrap, bg=C_BG2, highlightthickness=0, height=150)
        lsb = tk.Scrollbar(list_wrap, orient="vertical", command=lcanvas.yview,
                           bg=C_BG3, troughcolor=C_BG1)
        lsb.pack(side="right", fill="y")
        lcanvas.configure(yscrollcommand=lsb.set)
        lcanvas.pack(fill="both", expand=True)
        linner = tk.Frame(lcanvas, bg=C_BG2)
        lwin = lcanvas.create_window((0, 0), window=linner, anchor="nw")
        linner.bind("<Configure>",
                    lambda e: lcanvas.configure(scrollregion=lcanvas.bbox("all")))
        lcanvas.bind("<Configure>",
                     lambda e: lcanvas.itemconfig(lwin, width=e.width))
        _bind_mousewheel(linner, lcanvas)

        def _render_rules():
            for w in linner.winfo_children():
                w.destroy()
            rules = store.get("rules", [])
            if not rules:
                tk.Label(linner, text="(no rules yet — add one below)",
                         bg=C_BG2, fg=C_FG_DIM, font=("Segoe UI", 9, "italic"),
                         anchor="w", padx=8, pady=8).pack(fill="x")
                return
            for i, r in enumerate(rules):
                row = tk.Frame(linner, bg=C_BG3 if i % 2 else C_BG2)
                row.pack(fill="x", pady=1)
                where = r.get("subfolder", "common")
                where = {"common": "default folder",
                         "per_sender": "per-sender subfolder"}.get(where, f"/{where}")
                acct = r.get("account") or "any account"
                state = "" if r.get("enabled", True) else "  [disabled]"
                crit = []
                if r.get("match_from"):
                    crit.append(f"from “{r['match_from']}”")
                if r.get("match_subject"):
                    crit.append(f"subject “{r['match_subject']}”")
                if r.get("match_attachment"):
                    crit.append(f"file “{r['match_attachment']}”")
                txt = (f"{' + '.join(crit) or 'no criteria'}  ·  {acct}  →  {where}\n"
                       f"     prefix: {r.get('prefix','') or '(none)'}{state}")
                tk.Label(row, text=txt, bg=row["bg"], fg=C_FG,
                         font=("Segoe UI", 8), anchor="w", justify="left",
                         padx=8, pady=3).pack(side="left", fill="x", expand=True)
                tk.Button(row, text="✕", bg=C_BTN_DEL, fg=C_BTN_FG, relief="flat",
                          font=("Segoe UI", 8, "bold"), cursor="hand2",
                          command=lambda idx=i: _remove_rule(idx)).pack(
                              side="right", padx=4, pady=2)

        def _remove_rule(idx):
            try:
                store.get("rules", []).pop(idx)
            except Exception:
                pass
            _render_rules()

        _render_rules()

        # ── Add-rule form ─────────────────────────────────────────────────────
        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x", padx=16, pady=4)
        form = tk.Frame(top, bg=C_BG3, padx=16)
        form.pack(fill="x")

        def _field(label, width=18):
            r = tk.Frame(form, bg=C_BG3)
            r.pack(fill="x", pady=2)
            tk.Label(r, text=label, bg=C_BG3, fg=C_FG_DIM, width=14,
                     anchor="e", font=("Segoe UI", 9)).pack(side="left")
            e = tk.Entry(r, bg=C_BG2, fg=C_FG, relief="flat",
                         insertbackground=C_ACCENT, font=("Segoe UI", 9),
                         insertofftime=0, insertontime=9999999)
            no_blink(e)
            e.pack(side="left", fill="x", expand=True, ipady=2)
            return e

        e_match = _field("Sender contains:")
        # ── Content tests (DEL 04p) ──────────────────────────────────────────
        # A bill is still a bill when the supplier changes address, so a rule
        # can key on the SUBJECT or the attachment's FILENAME instead of (or
        # as well as) the sender.
        e_subject = _field("Subject has:")
        e_attach  = _field("File name has:")
        tk.Label(form,
                 text="Any field you fill in must match. Leave the sender "
                      "empty and put “faktura” here to catch bills from "
                      "anyone.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 7, "italic"),
                 anchor="w", justify="left",
                 wraplength=420).pack(fill="x", padx=(118, 0))
        # Account dropdown (any + each real account)
        r_acc = tk.Frame(form, bg=C_BG3); r_acc.pack(fill="x", pady=2)
        tk.Label(r_acc, text="Receiving acct:", bg=C_BG3, fg=C_FG_DIM, width=14,
                 anchor="e", font=("Segoe UI", 9)).pack(side="left")
        acc_opts = ["(any account)"] + [a["email"] for a in self._accounts
                                        if not a.get("virtual")]
        v_acc = tk.StringVar(value=acc_opts[0])
        om_acc = tk.OptionMenu(r_acc, v_acc, *acc_opts)
        om_acc.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                         activeforeground=C_FG, highlightthickness=0,
                         relief="flat", font=("Segoe UI", 9), anchor="w")
        om_acc["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                                 activeforeground=C_FG, font=("Segoe UI", 9))
        om_acc.pack(side="left", fill="x", expand=True)
        # Subfolder mode
        r_sub = tk.Frame(form, bg=C_BG3); r_sub.pack(fill="x", pady=2)
        tk.Label(r_sub, text="Save into:", bg=C_BG3, fg=C_FG_DIM, width=14,
                 anchor="e", font=("Segoe UI", 9)).pack(side="left")
        v_sub = tk.StringVar(value="common")
        for val, lab in [("common", "Default folder"),
                         ("per_sender", "Per-sender subfolder")]:
            tk.Radiobutton(r_sub, text=lab, variable=v_sub, value=val,
                           bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                           activebackground=C_BG3, activeforeground=C_FG,
                           font=("Segoe UI", 8), highlightthickness=0).pack(side="left")
        e_prefix = _field("Filename prefix:")
        # The date is CHOSEN, not typed (Issu 2026-09-01) — the dropdown
        # writes the token into the field above and the preview shows the
        # filename it produces. Typing tokens by hand still works.
        _dt_box = tk.Frame(form, bg=C_BG3)
        _dt_box.pack(fill="x", padx=(118, 0))
        self._date_token_row(_dt_box, e_prefix)
        tk.Label(form, text="Other tokens: {sender} {account} {subject}   "
                            "e.g.  GELF---Sandtorp 32---{YYYY-MM}---",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 7, "italic"),
                 anchor="w").pack(fill="x", padx=(118, 0))
        # "Save only" restricts WHICH files are written when a message matches —
        # e.g. *QR* to keep just the QR PNGs and skip the other attachments
        # (Issu 2026-08-01). Empty = save every attachment on a matching message.
        e_saveonly = _field("Save only files:")
        tk.Label(form, text="Only save attachments whose name matches, e.g. "
                            "*QR*  or  *.png  or  faktura   (empty = save all).",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 7, "italic"),
                 anchor="w", justify="left",
                 wraplength=420).pack(fill="x", padx=(118, 0))

        def _add_rule():
            mf   = e_match.get().strip()
            msub = e_subject.get().strip()
            matt = e_attach.get().strip()
            acct = v_acc.get()
            if not (mf or msub or matt):
                self._flash("Fill in a sender, a subject or a file name")
                return
            store.setdefault("rules", []).append({
                "match_from": mf,
                "match_subject": msub,
                "match_attachment": matt,
                "account": "" if acct.startswith("(") else acct,
                "subfolder": v_sub.get(),
                "prefix": e_prefix.get(),
                "save_only": e_saveonly.get().strip(),
                "enabled": True,
            })
            for e in (e_match, e_subject, e_attach, e_prefix, e_saveonly):
                e.delete(0, "end")
            _render_rules()

        tk.Button(form, text="➕ Add rule", bg=C_BTN_NEW, fg=C_BTN_FG,
                  relief="flat", padx=10, pady=3, cursor="hand2",
                  command=_add_rule).pack(anchor="w", padx=(118, 0), pady=(4, 2))

        # ── Save / Close ──────────────────────────────────────────────────────
        def _save_close():
            store["default_dir"] = e_dir.get().strip()
            _save_autosave_rules(store)
            top.destroy()
            self._flash("Auto-save rules saved")

        br = tk.Frame(top, bg=C_BG3); br.pack(pady=10)
        tk.Button(br, text="Save & Close", bg=C_BTN_NEW, fg=C_BTN_FG,
                  relief="flat", padx=16, pady=4, cursor="hand2",
                  command=_save_close).pack(side="left", padx=6)
        tk.Button(br, text="Cancel", bg=C_BTN_STD, fg=C_BTN_FG, relief="flat",
                  padx=16, pady=4, cursor="hand2",
                  command=top.destroy).pack(side="left", padx=6)

    # ── Export / import accounts (Issu 2026-08-01) ────────────────────────────
    def _accounts_io_dialog(self):
        """Export or import accounts, with a per-account checkbox so you can
        leave some out (default: all included).

        App passwords are stored encrypted with Windows DPAPI, which is tied to
        THIS Windows user on THIS machine — an exported password only works
        again on the same login. On another machine the account still imports,
        you just re-add its app password once. That is stated plainly here."""
        from tkinter import filedialog
        top = tk.Toplevel(self.root)
        top.title("Export / import accounts — F(re)email")
        top.configure(bg=C_BG3)
        _center_over(top, self.root, 560, 520)
        top.transient(top.master)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())

        tk.Label(top, text="👤  Export / import accounts", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 13, "bold")).pack(pady=(14, 2))
        tk.Label(top,
                 text="Tick the accounts to include (all by default). App "
                      "passwords are exported encrypted and only work again on "
                      "THIS Windows login — on another machine, re-add the "
                      "password once after importing.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8),
                 wraplength=520, justify="center").pack(pady=(0, 8))

        # ── The list of accounts (source depends on the mode) ────────────────
        state = {"mode": "export", "src": []}   # src = list of account dicts
        vars_by_email = {}

        list_wrap = tk.Frame(top, bg=C_BG2)
        list_wrap.pack(fill="both", expand=True, padx=16, pady=(0, 6))
        canvas = tk.Canvas(list_wrap, bg=C_BG2, highlightthickness=0, height=200)
        sb = tk.Scrollbar(list_wrap, orient="vertical", command=canvas.yview,
                          bg=C_BG3, troughcolor=C_BG1)
        sb.pack(side="right", fill="y")
        canvas.configure(yscrollcommand=sb.set)
        canvas.pack(fill="both", expand=True)
        inner = tk.Frame(canvas, bg=C_BG2)
        win = canvas.create_window((0, 0), window=inner, anchor="nw")
        inner.bind("<Configure>",
                   lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
        canvas.bind("<Configure>", lambda e: canvas.itemconfig(win, width=e.width))
        _bind_mousewheel(inner, canvas)

        hint = tk.Label(top, text="", bg=C_BG3, fg=C_FG_DIM,
                        font=("Segoe UI", 8, "italic"))
        hint.pack()

        def _render():
            for w in inner.winfo_children():
                w.destroy()
            vars_by_email.clear()
            if not state["src"]:
                tk.Label(inner,
                         text=("No accounts to export." if state["mode"] == "export"
                               else "Choose a file to import first."),
                         bg=C_BG2, fg=C_FG_DIM, font=("Segoe UI", 9, "italic"),
                         anchor="w", padx=8, pady=8).pack(fill="x")
                return
            for a in state["src"]:
                em = a.get("email", "")
                v = tk.BooleanVar(value=True)
                vars_by_email[em] = v
                has_pw = "✓ password" if a.get("secret") else "no password"
                tk.Checkbutton(
                    inner, text=f"  {a.get('name','') or em}   <{em}>   · {has_pw}",
                    variable=v, bg=C_BG2, fg=C_FG, selectcolor=C_BG1,
                    activebackground=C_BG2, activeforeground=C_FG,
                    font=("Segoe UI", 9), highlightthickness=0, anchor="w"
                    ).pack(fill="x", padx=4, pady=1)

        def _set_export():
            state["mode"] = "export"
            state["src"] = list(self._account_store.get("accounts", []))
            hint.configure(text="Exporting your current accounts.")
            _render()

        def _pick_import_file():
            path = filedialog.askopenfilename(
                parent=top, title="Accounts file to import",
                filetypes=[("Freemail accounts", "*.json"), ("All files", "*.*")])
            if not path:
                return
            try:
                with open(path, "r", encoding="utf-8") as f:
                    data = json.load(f)
                accts = data.get("accounts", []) if isinstance(data, dict) else []
                if not accts:
                    messagebox.showwarning("Import", "No accounts in that file.",
                                           parent=top)
                    return
                state["mode"] = "import"
                state["src"] = accts
                hint.configure(text=f"Importing from {os.path.basename(path)}")
                _render()
            except Exception as e:
                messagebox.showerror("Import", f"Could not read that file:\n{e}",
                                     parent=top)

        def _do_export():
            if state["mode"] != "export":
                _set_export()
                return
            chosen = [a for a in state["src"]
                      if vars_by_email.get(a.get("email", ""),
                                           tk.BooleanVar(value=False)).get()]
            if not chosen:
                messagebox.showinfo("Export", "Tick at least one account.",
                                    parent=top)
                return
            include_pw = bool(inc_pw.get())
            out = {"exported": _now_iso(),
                   "default_sender": self._account_store.get("default_sender", ""),
                   "note": "Freemail accounts export. Passwords are DPAPI-"
                           "encrypted and only work on the same Windows login.",
                   "accounts": []}
            for a in chosen:
                rec = {"email": a.get("email", ""), "name": a.get("name", "")}
                if include_pw and a.get("secret"):
                    rec["secret"] = a.get("secret", "")
                out["accounts"].append(rec)
            path = filedialog.asksaveasfilename(
                parent=top, title="Save accounts export",
                defaultextension=".json", initialfile="freemail_accounts.json",
                filetypes=[("Freemail accounts", "*.json")])
            if not path:
                return
            try:
                with open(path, "w", encoding="utf-8") as f:
                    json.dump(out, f, indent=2)
                self._flash(f"Exported {len(chosen)} account(s)")
                top.destroy()
            except Exception as e:
                messagebox.showerror("Export", f"Could not write the file:\n{e}",
                                     parent=top)

        def _do_import():
            if state["mode"] != "import":
                messagebox.showinfo("Import", "Choose a file to import first.",
                                    parent=top)
                return
            chosen = [a for a in state["src"]
                      if vars_by_email.get(a.get("email", ""),
                                           tk.BooleanVar(value=False)).get()]
            if not chosen:
                messagebox.showinfo("Import", "Tick at least one account.",
                                    parent=top)
                return
            accts = self._account_store.setdefault("accounts", [])
            existing = {a.get("email", ""): a for a in accts}
            added = updated = 0
            no_pw = []
            for a in chosen:
                em = a.get("email", "")
                if not em:
                    continue
                rec = {"email": em, "name": a.get("name", "") or em}
                if a.get("secret"):
                    rec["secret"] = a["secret"]
                elif em in existing and existing[em].get("secret"):
                    rec["secret"] = existing[em]["secret"]   # keep the one we have
                if not rec.get("secret"):
                    no_pw.append(em)
                if em in existing:
                    existing[em].update(rec); updated += 1
                else:
                    accts.append(rec); added += 1
            _save_account_store(self._account_store)
            self._rebuild_accounts()
            self._populate_sidebar(self.sidebar_inner)
            self._reschedule_autocheck()
            self._refresh_folder_tree()
            top.destroy()
            msg = f"Imported: {added} added, {updated} updated."
            if no_pw:
                msg += ("\n\nThese have no usable app password yet — add it via "
                        "Accounts → Add Gmail account (same address just updates "
                        "it):\n  • " + "\n  • ".join(no_pw[:8]))
                messagebox.showinfo("Import", msg, parent=self.root)
            else:
                self._flash(msg)

        # ── Controls ─────────────────────────────────────────────────────────
        inc_pw = tk.BooleanVar(value=True)
        tk.Checkbutton(top, text="Include app passwords (only usable on THIS "
                                 "Windows login)",
                       variable=inc_pw, bg=C_BG3, fg=C_FG_DIM, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 8), highlightthickness=0).pack(pady=(0, 4))

        br = tk.Frame(top, bg=C_BG3); br.pack(pady=10)
        tk.Button(br, text="📤 Export selected…", bg=C_BTN_NEW, fg=C_BTN_FG,
                  relief="flat", padx=12, pady=4, cursor="hand2",
                  command=_do_export).pack(side="left", padx=4)
        tk.Button(br, text="📥 Choose import file…", bg=C_BTN_STD, fg=C_BTN_FG,
                  relief="flat", padx=12, pady=4, cursor="hand2",
                  command=_pick_import_file).pack(side="left", padx=4)
        tk.Button(br, text="Import selected", bg=C_BTN_NEW, fg=C_BTN_FG,
                  relief="flat", padx=12, pady=4, cursor="hand2",
                  command=_do_import).pack(side="left", padx=4)
        tk.Button(br, text="Close", bg=C_BTN_STD, fg=C_BTN_FG, relief="flat",
                  padx=12, pady=4, cursor="hand2",
                  command=top.destroy).pack(side="left", padx=4)

        _set_export()   # start by showing the current accounts, ready to export

    # ── Add / manage accounts ─────────────────────────────────────────────────
    def _warn_unreadable_passwords(self):
        """After a Windows reinstall the DPAPI-encrypted app passwords cannot
        be read any more (they belong to the OLD Windows user).  Say so once,
        in plain words, and walk through entering them again - instead of the
        silent "Empty username or password" that left every account empty."""
        bad = [a for a in self._account_store.get("accounts", [])
               if str(a.get("secret", "")).startswith("dpapi:")
               and not _decrypt_secret(a.get("secret", ""))]
        if not bad:
            return
        names = "\n".join("    " + a.get("email", "?") for a in bad)
        if not messagebox.askyesno(
                "F(re)email - saved passwords unreadable",
                "Windows can no longer decrypt the saved app password for "
                "%d account(s):\n\n%s\n\n"
                "This is normal after Windows has been reinstalled: the "
                "passwords are encrypted for the old Windows user and cannot "
                "be recovered.  No mail can be fetched until each app "
                "password has been entered again.\n\n"
                "Enter them now, one account at a time?"
                % (len(bad), names), parent=self.root):
            return
        for a in bad:
            top = self._add_account_dialog(prefill=a)
            if top is not None:
                self.root.wait_window(top)

    def _add_account_dialog(self, prefill=None):
        import webbrowser
        APP_PW_URL = "https://myaccount.google.com/apppasswords"
        top = tk.Toplevel(self.root)
        top.title("Add Gmail account — F(re)email")
        top.configure(bg=C_BG3)
        top.resizable(False, False)
        _center_over(top, self.root, 540, 640)
        top.transient(self.root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())

        tk.Label(top, text="✉  Add a Gmail account", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 14, "bold")).pack(pady=(16, 2))
        tk.Label(top,
                 text="F(re)email signs in with an app password over IMAP/SMTP\n"
                      "(the same way Thunderbird can). Phase 1 is read-only.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9),
                 justify="center").pack(pady=(0, 6))

        # ── App-password explainer (Issu's request) ──────────────────────────
        # Make it impossible to miss: the "App password" is NOT the normal
        # Gmail login password. It is a 16-character code you generate once on
        # Google's own page, and it is stored encrypted in a local file.
        warn_box = tk.Frame(top, bg="#3a2d1a", padx=12, pady=8)
        warn_box.pack(fill="x", padx=24, pady=(0, 8))
        tk.Label(warn_box,
                 text="⚠  This is NOT your normal Gmail password.",
                 bg="#3a2d1a", fg="#ffd98a", font=("Segoe UI", 9, "bold"),
                 anchor="w", justify="left").pack(fill="x")
        tk.Label(warn_box,
                 text="You must create a 16-character \"app password\" on "
                      "Google's page (click the link below), then paste it "
                      "here. It is saved encrypted in a local file on this PC "
                      "— never sent anywhere else, and never your real password.",
                 bg="#3a2d1a", fg="#e8dcc0", font=("Segoe UI", 8),
                 anchor="w", justify="left", wraplength=460).pack(fill="x",
                                                                  pady=(2, 0))

        # How-to link
        link = tk.Label(top, text="🔗  Open Google's app-password page",
                        bg=C_BG3, fg=C_ACCENT, cursor="hand2",
                        font=("Segoe UI", 9, "underline"))
        link.pack(pady=(0, 10))
        link.bind("<Button-1>",
                  lambda e: open_url(APP_PW_URL))

        # ── The same address as copy-paste-able text (Issu's request) ────────
        # The link above usually lands on a Google SIGN-IN box first, and after
        # signing in you can end up on the account overview instead of the
        # app-password page.  So the address is ALSO shown as plain selectable
        # text: sign in, then paste this into the browser's address bar to get
        # straight there.  Read-only Entry = selectable + Ctrl+C, but the text
        # can never be edited away by mistake.
        url_box = tk.Frame(top, bg=C_BG3, padx=24)
        url_box.pack(fill="x", pady=(0, 10))
        tk.Label(url_box,
                 text="The link often opens a Google sign-in box first — sign "
                      "in, then paste this address into your browser:",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8),
                 anchor="w", justify="left", wraplength=460).pack(fill="x")

        url_row = tk.Frame(url_box, bg=C_BG3)
        url_row.pack(fill="x", pady=(3, 0))
        e_url = tk.Entry(url_row, bg=C_BG2, fg=C_FG, relief="flat",
                         font=("Consolas", 9), readonlybackground=C_BG2,
                         insertbackground=C_ACCENT,
                         insertofftime=0, insertontime=9999999)
        e_url.insert(0, APP_PW_URL)
        e_url.configure(state="readonly")
        no_blink(e_url)
        e_url.pack(side="left", fill="x", expand=True, ipady=3)

        copied_lbl = tk.Label(url_row, text="", bg=C_BG3, fg=C_ACCENT,
                              font=("Segoe UI", 8), width=8, anchor="w")

        def _copy_app_pw_url(_e=None):
            try:
                top.clipboard_clear()
                top.clipboard_append(APP_PW_URL)
                top.update_idletasks()          # make it stick on Windows
            except Exception:
                return
            try:                                # show WHAT was copied
                e_url.selection_range(0, "end")
            except Exception:
                pass
            copied_lbl.configure(text="Copied!")
            top.after(2000, lambda: copied_lbl.configure(text=""))

        tk.Button(url_row, text="📋 Copy", bg=C_BTN_STD, fg=C_BTN_FG,
                  relief="flat", padx=10, pady=2, cursor="hand2",
                  command=_copy_app_pw_url).pack(side="left", padx=(6, 0))
        copied_lbl.pack(side="left")

        frm = tk.Frame(top, bg=C_BG3, padx=24)
        frm.pack(fill="x")

        def _row(label):
            r = tk.Frame(frm, bg=C_BG3)
            r.pack(fill="x", pady=4)
            tk.Label(r, text=label, bg=C_BG3, fg=C_FG_DIM, width=14,
                     anchor="e", font=("Segoe UI", 9)).pack(side="left")
            e = tk.Entry(r, bg=C_BG2, fg=C_FG, relief="flat",
                         insertbackground=C_ACCENT, font=("Segoe UI", 10),
                         insertofftime=0, insertontime=9999999)
            no_blink(e)
            e.pack(side="left", fill="x", expand=True, ipady=3)
            return e

        e_name = _row("Display name:")
        e_mail = _row("Gmail address:")

        # ── Auto @gmail.com (Issu's request) ─────────────────────────────────
        # When ticked, you can type just "john" and it becomes
        # "john@gmail.com" on Add — no need to type the domain every time.
        auto_gmail = tk.BooleanVar(value=True)
        tk.Checkbutton(frm,
                       text="Add @gmail.com automatically (type just the name)",
                       variable=auto_gmail, bg=C_BG3, fg=C_FG_DIM,
                       selectcolor=C_BG2, activebackground=C_BG3,
                       activeforeground=C_FG, font=("Segoe UI", 8),
                       anchor="w", highlightthickness=0,
                       bd=0).pack(fill="x", padx=(118, 0))

        e_pass = _row("App password:")
        tk.Label(frm, text="(16 characters, spaces are ignored)",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 anchor="w").pack(fill="x", padx=(118, 0))

        status = tk.Label(top, text="", bg=C_BG3, fg="#e08a8a",
                          font=("Segoe UI", 9))
        status.pack(pady=(8, 0))

        btn_row = tk.Frame(top, bg=C_BG3)
        btn_row.pack(pady=14)

        def _do_add():
            name = e_name.get().strip()
            mail = e_mail.get().strip()
            pwd  = e_pass.get().replace(" ", "").strip()
            # Auto-complete a bare user name to a full Gmail address.
            if auto_gmail.get() and mail and "@" not in mail:
                mail = mail + "@gmail.com"
            if not mail or not pwd:
                status.configure(text="Email and app password are required.")
                return
            status.configure(fg=C_FG_DIM, text="Verifying with Gmail…")
            add_btn.configure(state="disabled")
            top.update_idletasks()

            def worker():
                try:
                    _verify_credentials(mail, pwd)
                    ok, err = True, ""
                except Exception as e:
                    ok, err = False, str(e)

                def done():
                    if not ok:
                        status.configure(
                            fg="#e08a8a",
                            text="Login failed — check address / app password.")
                        add_btn.configure(state="normal")
                        log.warning("Account verify failed for %s: %s", mail, err)
                        return
                    # Save (encrypted) and rebuild
                    accts = self._account_store.setdefault("accounts", [])
                    accts[:] = [a for a in accts if a.get("email") != mail]
                    accts.append({"email": mail,
                                  "name": name or mail,
                                  "secret": _encrypt_secret(pwd)})
                    if not self._account_store.get("default_sender"):
                        self._account_store["default_sender"] = mail
                    _save_account_store(self._account_store)
                    self._rebuild_accounts()
                    self._current_acct   = ALL_ACCOUNTS_ID
                    self._current_folder = "Inbox"
                    self._populate_sidebar(self.sidebar_inner)
                    top.destroy()
                    self._refresh_messages()
                    self._reschedule_autocheck()
                    self._refresh_folder_tree()   # list its custom folders too
                self.root.after(0, done)

            threading.Thread(target=worker, daemon=True).start()

        add_btn = tk.Button(btn_row, text="Add account", bg=C_BTN_NEW,
                            fg=C_BTN_FG, relief="flat", padx=16, pady=4,
                            cursor="hand2", command=_do_add)
        add_btn.pack(side="left", padx=6)
        tk.Button(btn_row, text="Cancel", bg=C_BTN_STD, fg=C_BTN_FG,
                  relief="flat", padx=16, pady=4, cursor="hand2",
                  command=top.destroy).pack(side="left", padx=6)

        e_pass.bind("<Return>", lambda e: _do_add())
        if prefill:
            # Re-entering the app password of a known account (see
            # _warn_unreadable_passwords): same address, same display name.
            e_name.insert(0, prefill.get("name", ""))
            e_mail.insert(0, prefill.get("email", ""))
            e_pass.focus_set()
        else:
            e_name.focus_set()
        return top

    def _remove_account_dialog(self):
        real = self._account_store.get("accounts", [])
        if not real:
            messagebox.showinfo("Remove account",
                                "No accounts are configured yet.",
                                parent=self.root)
            return
        top = tk.Toplevel(self.root)
        top.title("Remove account — F(re)email")
        top.configure(bg=C_BG3)
        top.resizable(False, False)
        _center_over(top, self.root, 420, 120 + 28 * len(real))
        top.transient(self.root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())

        tk.Label(top, text="Remove which account?", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 11, "bold")).pack(pady=(14, 4))
        tk.Label(top, text="(Only removes it from F(re)email — nothing on "
                           "Gmail is changed.)",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic")).pack()

        sel = tk.StringVar(value=real[0]["email"])
        for a in real:
            tk.Radiobutton(top, text=f"{a.get('name') or a['email']}  <{a['email']}>",
                           variable=sel, value=a["email"],
                           bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                           activebackground=C_BG3, activeforeground=C_FG,
                           font=("Segoe UI", 9), anchor="w",
                           highlightthickness=0).pack(fill="x", padx=24, pady=1)

        def _do_remove():
            email = sel.get()
            accts = self._account_store.get("accounts", [])
            accts[:] = [a for a in accts if a.get("email") != email]
            if self._account_store.get("default_sender") == email:
                self._account_store["default_sender"] = (
                    accts[0]["email"] if accts else "")
            _save_account_store(self._account_store)
            self._rebuild_accounts()
            self._current_acct   = (self._accounts[0]["email"]
                                    if self._accounts else ALL_ACCOUNTS_ID)
            self._current_folder = "Inbox"
            self._populate_sidebar(self.sidebar_inner)
            top.destroy()
            self._refresh_messages()
            self._reschedule_autocheck()

        br = tk.Frame(top, bg=C_BG3)
        br.pack(pady=14)
        tk.Button(br, text="Remove", bg=C_BTN_DEL, fg=C_BTN_FG, relief="flat",
                  padx=16, pady=4, cursor="hand2",
                  command=_do_remove).pack(side="left", padx=6)
        tk.Button(br, text="Cancel", bg=C_BTN_STD, fg=C_BTN_FG, relief="flat",
                  padx=16, pady=4, cursor="hand2",
                  command=top.destroy).pack(side="left", padx=6)

    # ── Toolbar actions ───────────────────────────────────────────────────────
    def _compose_new(self):
        # Default From: the current account, or first real account if All
        if self._current_acct == ALL_ACCOUNTS_ID:
            acct_obj = next(
                (a for a in self._accounts if not a.get("virtual")), None)
            default_from = (acct_obj["default_sender"]
                            if acct_obj and "default_sender" in acct_obj
                            else (acct_obj["email"] if acct_obj else ""))
        else:
            default_from = self._current_acct
        ComposeWindow(self.root, self.cfg, app=self,
                      accounts=self._accounts,
                      default_from=default_from)

    def _body_ready(self, msg, what):
        """Is this message's real text here yet?

        Since the folder list started arriving headers-first, the body of a
        message you have only just clicked can still be on its way. Replying to
        it at that instant quoted an EMPTY original — the message went out with
        none of their text in it, and nothing said why (Issu 2026-08-08).

        So: wait for it. One short beat is almost always enough (the fetch is
        already running); if it genuinely is not there, say so and let the user
        decide rather than sending a hollow reply."""
        if msg.get("_body_loaded", True):
            return True
        self._ensure_full_body(msg)
        # Give the fetch that is already in flight a moment to land. Two
        # seconds in 100 ms steps — long enough for a normal message, short
        # enough never to feel like a freeze.
        for _ in range(20):
            self.root.update()
            if msg.get("_body_loaded", True):
                return True
            if msg.get("_body_error"):
                break
            self.root.after(100)
        if msg.get("_body_loaded", True):
            return True
        return messagebox.askyesno(
            what,
            "The text of this message has not finished downloading"
            + (f":\n\n{msg.get('_body_error','')}"
               if msg.get("_body_error") else " yet.")
            + "\n\nGo ahead anyway? Their original text would NOT be included "
              "in what you send.\n\nSaying no lets you try again in a moment.",
            parent=self.root, default="no")

    def _reply(self):
        self._resync_selected_msg()
        if not self._selected_msg:
            messagebox.showinfo("Reply", "Select a message first.", parent=self.root)
            return
        if not self._body_ready(self._selected_msg, "Reply"):
            return
        # Reply From: the account that received the message
        default_from = self._selected_msg.get("account_email", self._current_acct)
        ComposeWindow(self.root, self.cfg, app=self,
                      accounts=self._accounts,
                      default_from=default_from,
                      reply_to=self._selected_msg,
                      reply_all=self._reply_all_var.get())

    def _smart_reply(self):
        self._resync_selected_msg()
        if not self._selected_msg:
            messagebox.showinfo("Smart Reply", "Select a message first.", parent=self.root)
            return
        # Smart Reply cuts the original into paragraphs the moment it opens,
        # so an unloaded body would give it exactly one empty paragraph to
        # answer — even worse here than in a normal reply.
        if not self._body_ready(self._selected_msg, "Smart Reply"):
            return
        default_from = self._selected_msg.get("account_email", self._current_acct)
        SmartReplyWindow(self.root, self.cfg, app=self,
                         accounts=self._accounts,
                         default_from=default_from,
                         reply_to=self._selected_msg,
                         reply_all=self._reply_all_var.get())

    def _forward(self):
        self._resync_selected_msg()
        if not self._selected_msg:
            messagebox.showinfo("Forward", "Select a message first.", parent=self.root)
            return
        if not self._body_ready(self._selected_msg, "Forward"):
            return
        default_from = self._selected_msg.get("account_email", self._current_acct)
        ComposeWindow(self.root, self.cfg, app=self,
                      accounts=self._accounts,
                      default_from=default_from,
                      forward_msg=self._selected_msg)

    def _retry_bounce(self, msg):
        """Rebuild a bounced message so it can be fixed and resent (Issu
        2026-08-01). Opens a fresh compose addressed to ONLY the address that
        failed (the ones that went through are left out, so nobody is mailed
        twice), with the original subject and body recovered from the bounce —
        no copy-paste, ready to correct the recipient and send again."""
        rec    = _bounce_recover(msg)
        failed = _bounce_details(msg).get("recipient", "") or rec.get("to", "")
        prefill = {"to": failed, "subject": rec.get("subject", ""),
                   "body": rec.get("body", "")}
        default_from = msg.get("account_email", self._current_acct)
        ComposeWindow(self.root, self.cfg, app=self,
                      accounts=self._accounts,
                      default_from=default_from,
                      prefill=prefill)

    def _collapsed_thread_members(self, msg):
        """If `msg` is displayed as a COLLAPSED conversation row (threaded view,
        >1 messages, not expanded), return all its member messages; else None.
        A collapsed row shows only the newest message, so acting on 'the row'
        should offer to act on the whole conversation (Issu: deleting the row
        only removed one, and the sibling took its place)."""
        # No thread_view guard: a MANUAL merge group collapses even when
        # auto-merge is off. _effective_tid handles both — an un-merged message
        # is its own id, so `members` is just itself (len 1) and we return None.
        if self._current_folder in _VIRTUAL_FOLDERS:
            return None
        tid = self._effective_tid(msg)
        if tid in getattr(self, "_expanded_rows", set()):
            return None
        members = [m for m in self._messages
                   if self._effective_tid(m) == tid]
        return members if len(members) > 1 else None

    # ── ✉ Address mails (manual marking) — Issu 2026-09-23 ────────────────────
    def _addr_toggle_mark(self, msg):
        """List/reading-pane right-click: flag or unflag a mail as an address
        mail. The whole-mail variant — no snippet — so the ✉ says only "there
        is an address in here"."""
        store = self._address_store
        if _addr_is_marked(store, msg):
            _addr_clear(store, msg)
            self._flash("Address mark removed")
        else:
            _addr_set(store, msg, "")          # whole-mail mark, no snippet
            self._flash("Marked as address mail")
        self._render_msg_list()

    def _addr_save_selection(self, msg, text):
        """Reading-pane right-click: save the SELECTED text as this mail's
        address part. Also marks the mail, so the ✉ turns green and a click
        pops the text straight up."""
        text = (text or "").strip()
        if not text:
            self._flash("Nothing selected")
            return
        _addr_set(self._address_store, msg, text)
        self._render_msg_list()
        self._flash("Saved this mail's address")

    def _row_widgets_for(self, msg):
        """The list-row cell widgets for `msg`, or [] — used to select a row
        from the envelope handler without rebuilding the list."""
        for ent in getattr(self, "_row_frames", []):
            if ent and ent[0] is msg:
                return ent[1]
        return []

    def _address_cell_click(self, event, msg):
        """Click the ✉ cell. Marked → pop the saved address up (or say there is
        no saved part yet). A grey ✉ (address only deeper in the conversation)
        pops that message's part. An empty cell falls back to a normal row
        select, so the column is not a dead strip down the side of the list."""
        store = self._address_store
        if _addr_is_marked(store, msg):
            self._show_address_popup(event, msg)
            return "break"
        members = self._collapsed_thread_members(msg)
        if members:
            deeper = [m for m in members
                      if m is not msg and _addr_is_marked(store, m)]
            if deeper:
                self._show_address_popup(event, deeper[0], in_thread=True)
                return "break"
        # Empty cell → behave like clicking the row.
        ctrl  = bool(getattr(event, "state", 0) & 0x0004)
        shift = bool(getattr(event, "state", 0) & 0x0001)
        self._select_msg(msg, self._row_widgets_for(msg), ctrl=ctrl, shift=shift)
        return "break"

    def _show_address_popup(self, event, msg, in_thread=False):
        """A small popup at the cursor showing this mail's saved address part,
        with Copy and Open. If the mail was only marked (no part saved) it says
        so and offers to open the mail so he can add or fix one."""
        snippet = _addr_snippet(self._address_store, msg)
        top = tk.Toplevel(self.root)
        top.withdraw()
        top.overrideredirect(True)
        top.configure(bg=C_SEP)
        frame = tk.Frame(top, bg=C_BG3, bd=0)
        frame.pack(padx=1, pady=1, fill="both", expand=True)

        title = "✉  Address in this mail"
        if in_thread:
            title = "✉  Address (from another mail in this conversation)"
        tk.Label(frame, text=title, bg=C_BG3, fg=C_ADDR,
                 font=("Segoe UI", 9, "bold"), anchor="w",
                 padx=10, pady=(8, 4)).pack(fill="x")

        if snippet:
            box = tk.Text(frame, bg=C_BG2, fg=C_FG, bd=0, wrap="word",
                          font=("Segoe UI", 10), padx=8, pady=6,
                          height=min(12, max(2, snippet.count("\n") + 2)),
                          width=42)
            box.insert("1.0", snippet)
            box.configure(state="disabled")
            box.pack(fill="both", expand=True, padx=10, pady=(0, 6))
        else:
            tk.Label(frame,
                     text="Marked as an address mail, but no text part saved.\n"
                          "Open it and right-click the address to save one.",
                     bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9),
                     justify="left", anchor="w", padx=10,
                     pady=(0, 6)).pack(fill="x")

        btns = tk.Frame(frame, bg=C_BG3)
        btns.pack(fill="x", padx=10, pady=(0, 8))

        def _close():
            try:
                top.destroy()
            except Exception:
                pass

        if snippet:
            tk.Button(btns, text="📋  Copy", bg=C_BTN_STD, fg=C_BTN_FG,
                      relief="flat", padx=8, pady=2,
                      command=lambda: (self._copy_to_clipboard(snippet,
                                       "Address copied"), _close())
                      ).pack(side="left")
        tk.Button(btns, text="Open mail", bg=C_BTN_STD, fg=C_BTN_FG,
                  relief="flat", padx=8, pady=2,
                  command=lambda: (_close(), self._focus_message(msg))
                  ).pack(side="left", padx=(6, 0))
        tk.Button(btns, text="Close", bg=C_BTN_STD, fg=C_BTN_FG,
                  relief="flat", padx=8, pady=2,
                  command=_close).pack(side="right")

        # Position at the cursor, then show. Close on click-away or Esc.
        try:
            x = int(getattr(event, "x_root", self.root.winfo_pointerx()))
            y = int(getattr(event, "y_root", self.root.winfo_pointery()))
        except Exception:
            x, y = 200, 200
        top.geometry(f"+{x + 6}+{y + 6}")
        top.deiconify()
        top.lift()
        # Escape and the buttons close it. No <FocusOut> auto-close: a borderless
        # Toplevel can fail to hold focus on Windows and would then vanish the
        # instant it appeared.
        try:
            top.bind("<Escape>", lambda e: _close())
            top.focus_set()
        except Exception:
            pass

    # ── Run the filters on EVERY account, not only the open inbox ─────────────
    # Issu 2026-09-23: "reglerna borde köras när mailen kommer… och när jag kör
    # Refresh-knappen." Refresh only fetches the account/folder on screen, so
    # rules fired per-inbox. This sweeps every account's Inbox in the background
    # and runs the SAME local/server rule pass the visible list uses, on Refresh
    # and at start-up. (Truly "the moment mail arrives", unattended, still needs
    # the per-account auto-check turned on in Tools → Auto-check.)
    def _sweep_all_accounts(self, reason="refresh"):
        if self._demo_mode:
            return
        cur = self._current_acct
        skip = set()
        # Whatever the foreground refresh already covered is not fetched twice.
        if self._current_folder == "Inbox":
            if cur == ALL_ACCOUNTS_ID:
                # It already fetched every Inbox — but not the Trash, where
                # the "rescue from Trash" rules look (Issu 2026-10-12).
                for a in self._accounts:
                    if not a.get("virtual") and a.get("email"):
                        self._rescue_trash_only(a["email"])
                return
            skip.add(cur)
            self._rescue_trash_only(cur)
        for a in self._accounts:
            if a.get("virtual"):
                continue
            email = a.get("email")
            if not email or email in skip:
                continue
            self._filter_sweep_account(email, reason)

    # ── Rescue from Trash, in the background (Issu 2026-10-12) ───────────────
    def _rescue_trash_wanted(self, email):
        """Only worth a network round-trip when Server changes is on (a rescue
        IS a server change) and a rescue rule covers this account."""
        if self._demo_mode or not self.cfg.get("allow_server_changes", False):
            return False
        return _rescue_rules_for(self._filter_store, email)

    def _fetch_rescue_trash(self, email, pwd):
        """Worker-thread fetch of the Trash for the rescue rules: the newest
        FETCH_LIMIT plus everything from the last RESCUE_TRASH_HOURS hours.
        Never raises; returns None when there is nothing to do."""
        try:
            if not self._rescue_trash_wanted(email):
                return None
            use_cache = self.cfg.get("cache_enabled", True)
            msgs = _fetch_folder_smart(email, pwd, "Trash",
                                       limit=FETCH_LIMIT, use_cache=use_cache)
            if msgs and len(msgs) >= FETCH_LIMIT:
                # Is the oldest of the newest 40 still inside the window? Then
                # there may be more recent mail behind it — fetch deeper.
                oldest = min((d for d in (_parse_msg_dt(m.get("_dt", "") or "")
                                          for m in msgs) if d), default=None)
                if oldest and oldest >= (datetime.now()
                                         - timedelta(hours=RESCUE_TRASH_HOURS)):
                    msgs = _fetch_folder_smart(
                        email, pwd, "Trash", limit=RESCUE_TRASH_MAX_FETCH,
                        use_cache=use_cache)
            return _rescue_trash_window(msgs or [])
        except Exception as e:
            log.warning("Rescue-from-Trash fetch for %s failed: %s", email, e)
            return None

    def _run_rescue_trash(self, email, trash_msgs):
        """Main thread: run ONLY the rescue rules over what the fetch brought.
        No toast and no redraw — the Trash is not on screen."""
        if not trash_msgs:
            return
        try:
            self._run_filters_on(trash_msgs, "fetch", rescue_only=True)
        except Exception as e:
            log.error("Rescue-from-Trash pass for %s failed: %s", email, e)

    def _rescue_trash_only(self, email):
        """Trash pass for an account whose Inbox the foreground refresh is
        already fetching (so the sweep skips it)."""
        a = next((x for x in self._accounts
                  if x.get("email") == email and not x.get("virtual")), None)
        if a is None or not self._rescue_trash_wanted(email):
            return
        busy = getattr(self, "_rescue_inflight", None)
        if busy is None:
            busy = self._rescue_inflight = set()
        if email in busy:
            return
        busy.add(email)

        def worker():
            trash_msgs = None
            try:
                pwd = _decrypt_secret(a.get("secret", ""))
                trash_msgs = self._fetch_rescue_trash(email, pwd)
            except Exception as e:
                log.warning("Rescue-from-Trash pass for %s failed: %s", email, e)

            def done():
                busy.discard(email)
                self._run_rescue_trash(email, trash_msgs)
            try:
                self.root.after(0, done)
            except Exception:
                busy.discard(email)

        threading.Thread(target=worker, daemon=True).start()

    def _filter_sweep_account(self, email, reason="refresh"):
        """One account: a background, read-only fetch of its Inbox followed by
        the local/server rule pass. Reuses the auto-check in-flight guard so a
        sweep and a scheduled poll of the same account never run at once."""
        a = next((x for x in self._accounts
                  if x.get("email") == email and not x.get("virtual")), None)
        if a is None:
            return
        if self._poll_inflight.get(email) is not None:
            return                           # a poll/sweep is already on the wire
        self._poll_inflight[email] = time.monotonic()

        def worker():
            msgs = None
            trash_msgs = None
            try:
                pwd  = _decrypt_secret(a.get("secret", ""))
                msgs = _fetch_folder_smart(
                    email, pwd, "Inbox", limit=self._fetch_limit,
                    use_cache=self.cfg.get("cache_enabled", True))
            except Exception as e:
                log.error("Filter sweep (%s) for %s failed: %s", reason, email, e)
            if msgs is not None:
                trash_msgs = self._fetch_rescue_trash(email, pwd)

            def done():
                try:
                    if msgs is not None:
                        self._bg_check = True
                        shown = msgs
                        try:
                            shown = self._apply_local_state(msgs)
                        except Exception as e:
                            log.error("Sweep rule run for %s failed: %s",
                                      email, e)
                        # Same as a background poll: only the toast uses the
                        # returned list; the on-screen list is left untouched.
                        self._notify_new(shown)
                    self._run_rescue_trash(email, trash_msgs)
                finally:
                    self._poll_inflight.pop(email, None)
            try:
                self.root.after(0, done)
            except Exception:
                self._poll_inflight.pop(email, None)

        threading.Thread(target=worker, daemon=True).start()

    def _expand_collapsed_threads(self, targets):
        """Grow a manual MOVE so a COLLAPSED conversation row moves whole.

        Issu 2026-09-01: "Move message-alternativen… flyttar de inte en hel
        tråd, om de är i collapsed? Det vore bättre om det skedde automatiskt
        så att man måste expand om man vill move enstaka."

        He is right about the old behaviour: a collapsed row draws the NEWEST
        message of the conversation (that is what `lead` is in
        _render_msg_list), so a move took that one message and left the rest
        behind — and an older sibling then slid up into the row, which looks
        exactly like "the move did nothing".

        The rule now: a closed row IS the conversation, so moving it takes
        every member — no question asked, because a move is reversible and
        the count is on the row (5) for anyone to read. Open the twisty and
        every member gets its own row; move one of THOSE and only that one
        goes. That is the "expand if you want to move a single message" half.

        Delete deliberately keeps ASKING instead (_delete_selected) — that one
        is the destructive direction.

        Works for hand-made merge groups too, which collapse even with
        auto-merge off: _collapsed_thread_members answers for both.

        Returns (messages, extra) — `extra` is how many were pulled in beyond
        the rows actually picked, so the caller can say so out loud.
        """
        pending = getattr(self, "_pending_delete_keys", set())
        base, seen = [], set()
        for t in targets:                       # de-dupe what was handed in
            if id(t) not in seen:
                seen.add(id(t))
                base.append(t)
        out, seen = [], set()
        for t in base:
            members = self._collapsed_thread_members(t) or [t]
            if not any(m is t for m in members):
                members = [t] + list(members)   # never lose the row itself
            for m in members:
                # A message waiting out its delete-undo is not on screen and
                # must not be dragged along by its conversation (DEL 09k).
                if pending and _msg_key(m) in pending:
                    continue
                if id(m) in seen:
                    continue
                seen.add(id(m))
                out.append(m)
        # How many are HIDDEN behind a closed row — counted from the RESULT,
        # not from what came in, so the answer is the same whether the caller
        # handed over the row or a set that is already expanded (the context
        # menu does the latter, and the move paths then expand a second time).
        # That keeps this idempotent: running it twice must not make the
        # warning disappear.
        rows, counted = 0, set()
        for m in out:
            if self._collapsed_thread_members(m):
                tid = self._effective_tid(m)
                if tid in counted:
                    continue                # same closed row, already counted
                counted.add(tid)
            rows += 1
        return out, max(0, len(out) - rows)

    def _conversation_member_count(self, msg):
        """How many loaded messages currently group under the same row as
        `msg` (>=1). Used to decide whether to offer "Separate" (Issu
        2026-08-02) — works for both manual merges and auto Gmail threads,
        and returns 1 for a conversation already split apart."""
        if self._current_folder in _VIRTUAL_FOLDERS:
            return 1
        tid = self._effective_tid(msg)
        return sum(1 for m in self._messages
                   if self._effective_tid(m) == tid)

    def _resync_selected_msg(self):
        """Rows are ticked (and painted as selected) but `_selected_msg` is None
        -> make the first ticked row the selected message again.

        Issu 2026-10-12: "jag markerar mail … vill radera det och det säger att
        jag inte har markerat någon fil". A refresh you ask for (↻, F5, opening
        the folder) replaces every row object and sets `_selected_msg` to None
        on purpose — the reading pane closes — but the TICKS are carried over to
        the new rows. So the row stayed highlighted while Delete / Reply /
        Forward / Snooze, which all test `_selected_msg`, said "Select a
        message first". The reading pane is left exactly as it is."""
        if self._selected_msg is not None or not self._selected_ids:
            return
        for m in self._messages or []:
            if m.get("id") in self._selected_ids:
                self._selected_msg = m
                return

    def _delete_selected(self):
        self._resync_selected_msg()
        if not self._selected_msg:
            messagebox.showinfo("Delete", "Select a message first.", parent=self.root)
            return
        # ── Several rows ticked → delete ALL of them (Issu bug 2026-08-01) ────
        # The toolbar Delete button and the Delete key used to act on the single
        # last-clicked row only, so ticking four messages and pressing Delete
        # removed just the top one and left the other three behind. Route a real
        # multi-selection straight to the bulk path, which asks once and takes
        # the whole set.
        if len(self._selected_ids) > 1:
            self._bulk_delete()
            return
        # A collapsed conversation row stands for several messages, and it now
        # DELETES as the whole conversation — no question (Issu 2026-09-01:
        # "allt som är collapsed ska behandlas med samma regel. Vill jag
        #  särskilja så får jag expanda"). It used to ask "Delete all 5 /
        # Only the newest", but "only the newest" is exactly the singling-out
        # that expanding the row is for, so the question had no answer left
        # worth offering. Taking only the newest was the old default and the
        # bug behind it: the next-oldest slid up into the row and it looked as
        # though nothing had gone. The 60-second Undo bar covers a mis-click,
        # the same way it already does for a bulk delete (Issu 2026-08-01).
        members = self._collapsed_thread_members(self._selected_msg)
        if members:
            self._selected_ids = {m.get("id") for m in members}
            self._flash(f"Deleting the whole conversation — {len(members)} "
                        f"messages, not just the row")
            self._bulk_delete()
            return
        # A NOTE is a local file, so Delete must actually delete it. Hiding it
        # from the view would be a lie: the file would still be on disk and
        # the note would reappear the moment you left the folder and came
        # back. Notes are the one thing here that Delete really removes —
        # and never anything on a server, because notes were never there.
        if self._selected_msg.get("_note_path"):
            self._delete_note(self._selected_msg)
            return
        # In the Deleted archive, "delete" removes the saved LOCAL copy.
        if self._current_folder == "Deleted":
            self._remove_deleted(self._selected_msg)
            return
        # Deleting from the TRASH means "for good" — permanent server delete,
        # after a hidden local copy is kept (DEL 04s).
        if (self._current_folder == "Trash" and not self._demo_mode
                and self._selected_msg.get("uid")):
            self._permanent_delete([self._selected_msg])
            return
        # ── Server delete already switched on → do it ────────────────────────
        if (self.cfg.get("allow_server_changes", False)
                and not self._demo_mode
                and self._selected_msg.get("uid")):
            self._delete_on_server(self._selected_msg)
            return

        # ── Real account, server delete still OFF → offer to turn it on here ─
        # A dead-end "want me to hide it?" is exactly what confused Issu, so
        # Delete now asks the real question and can enable server delete inline.
        if not self._demo_mode and self._selected_msg.get("uid"):
            choice = self._prompt_server_delete(1)
            if choice is None:
                return
            if choice == "server":
                self._delete_on_server(self._selected_msg)
                return
            # chose "just hide" → instant hide with an Undo button, no server
            self._soft_delete([self._selected_msg], permanent=False, server=False)
            return

        # ── Demo mode → there is no server to delete from ────────────────────
        if self._demo_mode:
            messagebox.showinfo(
                "Delete",
                "This is DEMO mail — there is no Gmail account to delete it "
                "from.\n\nAdd your account (Accounts → Add Gmail account), then "
                "Delete can move real messages to the Gmail Trash.",
                parent=self.root)
            return

        # ── A real message with no server id → local hide only ───────────────
        # No popup — instant hide with an Undo button (Issu 2026-08-01).
        self._soft_delete([self._selected_msg], permanent=False, server=False)

    def _hide_message_locally(self, msg):
        """Remove a message from the current view only — never from the server."""
        if msg in self._messages:
            self._messages.remove(msg)
        if msg in self._all_messages:
            self._all_messages.remove(msg)
        self._selected_msg = None
        self._render_msg_list()
        self._show_reading_pane_empty()

    def _prompt_server_delete(self, count):
        """Server delete is OFF but a real account exists: ask whether to turn
        it on and delete for real. Returns "server" (enabled now — caller
        should delete on the server), "hide" (local hide this time), or None
        (cancel). Enabling here is a deliberate Yes and is remembered, exactly
        like the Tools → Server changes toggle."""
        it   = "this message" if count == 1 else f"these {count} messages"
        itp  = "it" if count == 1 else "them"
        ans = ask_yes_no_cancel(
            self.root, "Delete on Gmail?",
            f"Server delete is currently OFF, so Delete would only hide {it} "
            f"from the view — {itp} would stay on Gmail and come back on "
            f"Refresh.\n\n"
            f"Move to Trash  —  Gmail keeps it 30 days and you can restore it, "
            f"and this program deletes on Gmail from now on.\n"
            f"Just hide  —  {itp} stays on Gmail, hidden here only.",
            yes="Move to Trash", no="Just hide", cancel="Do nothing",
            icon="🗑")
        if ans is None:
            return None
        if ans:
            self.cfg["allow_server_changes"] = True
            _save_settings(self.cfg)
            log.info("allow_server_changes enabled from the Delete dialog")
            self._flash("Server delete turned on")
            return "server"
        return "hide"

    def _permanent_delete(self, msgs):
        """Delete for good from Gmail (used when deleting FROM the Trash). A
        hidden local copy is saved first (DEL 04s), and there is ONE
        confirmation for the whole batch — never one popup per message."""
        msgs = [m for m in msgs if m.get("uid")]
        if not msgs:
            return
        # The one irreversible delete in the program, so the protection gate
        # comes BEFORE the count and the confirmation — the number in the
        # dialog must be the number that actually goes (DEL 09p).
        msgs = self._guard_protected(msgs, verb="Erasing")
        if not msgs:
            return
        n    = len(msgs)
        days = int(self.cfg.get("deleted_keep_days", 30) or 0)
        keep = (f"Freemail keeps a hidden local copy for {days} days "
                f"(the Deleted folder) that you can read, forward or restore."
                if days > 0 else
                "Freemail keeps a hidden local copy (the Deleted folder) that "
                "you can read, forward or restore.")
        if not messagebox.askyesno(
                "Delete permanently from Gmail",
                f"Permanently delete {n} message(s) from Gmail?\n\n"
                f"They are removed from the Gmail Trash for good. {keep}",
                parent=self.root, default="no"):
            return
        # Permanent delete needs server changes on. Offer to enable inline.
        if not self.cfg.get("allow_server_changes", False):
            choice = self._prompt_server_delete(n)
            if choice != "server":
                if choice == "hide":
                    messagebox.showinfo(
                        "Delete permanently",
                        "Permanent delete needs Gmail changes on. Nothing was "
                        "removed.", parent=self.root)
                return
        # Remove from the view now; expunge (after saving a local copy) in the
        # background so you can move on.
        self._delete_msgs_background(msgs, permanent=True)

    # ── Empty the Trash (Issu 2026-08-03: "Trash har ingen Empty all") ────────
    def _empty_trash(self):
        """Erase EVERYTHING in the Gmail Trash — not just the messages loaded
        here, the whole thing.

        The one irreversible action in the program, so it is built to be hard
        to do by accident and impossible to do by surprise: it needs Server
        changes on, it counts the real total on the server FIRST and shows it,
        it asks twice, and the second question is per account with the number
        in front of you. Gmail does not put this back."""
        if self._demo_mode:
            messagebox.showinfo(
                "Empty Trash",
                "This clears the Trash on Gmail, so it needs an account.\n\n"
                "Accounts → Add Gmail account…", parent=self.root)
            return
        reals = [a for a in self._accounts if not a.get("virtual")]
        if not reals:
            return
        # Which accounts? ONLY the one you are looking at — unless you are in
        # the All Accounts view, where "all of them" is what the view means.
        #
        # There used to be a fallback that widened to EVERY account when the
        # current one could not be resolved, and that is how "empty the Trash
        # of account 2" turned into "empty every Trash" (Issu 2026-08-03).
        # A destructive action must never widen its own scope: if we cannot
        # tell which account is meant, we stop and say so.
        all_accounts = (self._current_acct == ALL_ACCOUNTS_ID)
        if all_accounts:
            targets = list(reals)
        else:
            targets = [a for a in reals if a["email"] == self._current_acct]
        if not targets:
            messagebox.showinfo(
                "Empty Trash",
                "Pick the account whose Trash you want to empty in the left "
                "sidebar first (or the All Accounts view to empty every one).",
                parent=self.root)
            return
        scope = ("EVERY account" if all_accounts
                 else f"the account {targets[0]['email']}")
        if not self.cfg.get("allow_server_changes", False):
            if not messagebox.askyesno(
                    "Server changes are off",
                    "Emptying the Trash changes your Gmail account, and that "
                    "switch is currently OFF.\n\nTurn it on and continue?",
                    parent=self.root, default="no"):
                return
            self.cfg["allow_server_changes"] = True
            _save_settings(self.cfg)
            log.info("allow_server_changes enabled from Empty Trash")

        self._flash("Counting the Trash…")

        def counter():
            counts = []
            for a in targets:
                pwd = self._secret_for(a["email"])
                if not pwd:
                    continue
                counts.append((a["email"], pwd,
                               _imap_trash_count(a["email"], pwd)))

            def ask():
                total = sum(c for _e, _p, c in counts)
                if not total:
                    messagebox.showinfo("Empty Trash",
                                        "The Trash is already empty.",
                                        parent=self.root)
                    return
                where = "\n".join(f"  • {n} in {e}" for e, _p, n in counts if n)
                keep = int(self.cfg.get("deleted_keep_days", 30) or 0)
                if not messagebox.askyesno(
                        "Empty Trash",
                        f"ERASE {total} message(s) from the Gmail Trash of "
                        f"{scope}, for good?\n\n{where}\n\n"
                        f"This cannot be undone — not by Freemail, not by "
                        f"Gmail, not from your phone.\n\n"
                        f"(Messages you deleted THROUGH Freemail also have a "
                        f"hidden local copy in the Deleted folder for "
                        f"{keep} days. Mail that reached the Trash any other "
                        f"way has no copy at all.)",
                        parent=self.root, default="no"):
                    return
                if not messagebox.askyesno(
                        "Empty Trash — last chance",
                        f"Really erase {total} message(s) from {scope}?\n\n"
                        f"Press No if you are not certain.",
                        parent=self.root, default="no"):
                    return
                self._flash(f"Erasing {total} message(s)…")

                def worker():
                    erased, problems = 0, []
                    for email, pwd, n in counts:
                        if not n:
                            continue
                        try:
                            k, probs = _imap_empty_trash(email, pwd)
                            erased += k
                            problems.extend(probs)
                        except Exception as e:
                            problems.append(f"{email}: {e}")
                            log.error("Empty Trash failed for %s: %s", email, e)

                    def finish():
                        log.info("Empty Trash: erased %d message(s)", erased)
                        if problems:
                            messagebox.showwarning(
                                "Empty Trash",
                                f"{erased} message(s) were erased, but there "
                                f"were problems:\n\n"
                                + "\n".join(f"• {p}" for p in problems[:6]),
                                parent=self.root)
                        else:
                            self._flash(f"Trash emptied — {erased} message(s) "
                                        f"erased")
                        if self._current_folder == "Trash":
                            self._refresh_messages()
                        self._maybe_refresh_counts(force=True)
                    try:
                        self.root.after(0, finish)
                    except Exception:
                        pass
                threading.Thread(target=worker, daemon=True).start()
            try:
                self.root.after(0, ask)
            except Exception:
                pass
        threading.Thread(target=counter, daemon=True).start()

    def _remove_deleted_batch(self, msgs):
        """Remove several saved local copies from the Deleted archive at once."""
        metas = [m.get("_deleted_meta") for m in msgs if m.get("_deleted_meta")]
        if not metas:
            return
        if not messagebox.askyesno(
                "Remove copies",
                f"Delete {len(metas)} saved local copies for good?\n\nThey are "
                f"already gone from Gmail; this only removes Freemail's safety "
                f"copies.", parent=self.root, default="no"):
            return
        for meta in metas:
            _deleted_remove(meta)
        self._select_all(False)
        self._flash(f"Removed {len(metas)} local copies")
        if self._current_folder == "Deleted":
            self._render_deleted()

    def _delete_on_server(self, msg, confirm=True):
        """Move one message to the Gmail Trash (DEL 04i).

        No Yes/No popup any more (Issu 2026-08-01): the message leaves the view
        at once and an Undo button holds the real Gmail move for a minute. The
        `confirm` parameter is kept for callers but is now a no-op — the Undo
        window is the safety net that replaced the dialog. Nothing is erased:
        this is a move to Trash, still recoverable in Gmail for 30 days."""
        self._soft_delete([msg], permanent=False, server=True)

    def _delete_msgs_background(self, msgs, permanent):
        """Take messages out of the view IMMEDIATELY, then do the Gmail delete
        on a background thread so you can carry on. On failure the view is
        reloaded so it always ends up matching the server.

        permanent=False → move to Trash (recoverable). permanent=True → real
        expunge, after a hidden local copy is saved (DEL 04s)."""
        msgs = [m for m in msgs if m.get("uid")]
        if not msgs:
            return
        # 1) Instant local removal + badge update.
        for m in msgs:
            if m.get("unread") and not m.get("_always_unread"):
                self._badge_adjust(m, -1)
            if m in self._messages:
                self._messages.remove(m)
            if m in self._all_messages:
                self._all_messages.remove(m)
        self._selected_ids = set()
        self._selected_msg = None
        self._render_msg_list()
        self._show_reading_pane_empty()
        self._repaint_badges()
        self._flash(f"Deleting {len(msgs)}…  (updating Gmail in the background)")

        # 2) Server work off the main thread.
        self._start_server_delete(list(msgs), permanent)

    def _server_delete_batch(self, targets, permanent) -> list:
        """Do the actual Gmail delete for a batch, synchronously, and return a
        list of problem strings. Shared by the background delete, the delete-
        limbo commit, and the flush-on-close path."""
        archive_on = self.cfg.get("archive_auto", False)
        problems = []
        for m in targets:
            acct   = m.get("account_email", "")
            pwd    = self._secret_for(acct)
            folder = m.get("_folder", self._current_folder)
            uid    = m.get("uid")
            if not uid:
                continue
            if not pwd:
                problems.append(f"No stored password for {acct}.")
                continue
            try:
                if permanent:
                    try:
                        _deleted_save(m)          # safety copy first
                    except Exception as e:
                        log.error("deleted-save failed: %s", e)
                    prob = _imap_expunge_message(acct, pwd, folder, uid)
                else:
                    if archive_on:
                        try:
                            _archive_message(self.cfg, m)
                        except Exception as e:
                            log.warning("archive before delete failed: %s", e)
                    prob = _imap_trash_message(acct, pwd, folder, uid)
                if prob:
                    problems.append(prob)
            except Exception as e:
                problems.append(str(e))
                log.error("background delete failed: %s", e)
        return problems

    def _start_server_delete(self, targets, permanent):
        """Run _server_delete_batch on a worker thread; reload the list if any
        message could not be removed, so the view always ends up matching the
        server."""
        def worker():
            problems = self._server_delete_batch(targets, permanent)

            def done():
                if problems:
                    messagebox.showwarning(
                        "Delete permanently" if permanent else "Delete on Gmail",
                        "Some messages could not be removed:\n\n"
                        + "\n".join(f"• {p}" for p in problems[:6])
                        + "\n\nReloading to show what is really on Gmail.",
                        parent=self.root)
                    self._refresh_messages()
                else:
                    self._maybe_refresh_counts(force=True)
            try:
                self.root.after(0, done)
            except Exception:
                pass
        threading.Thread(target=worker, daemon=True).start()

    # ── Delete limbo: act now, commit to Gmail after an Undo window ────────────
    # ── DEL 09p — protected messages ("✉🔒 Send and save") ────────────────────
    def _is_protected_message(self, msg) -> bool:
        """Is this one message protected against a bulk delete?"""
        return _is_protected_msg(self._protected_store, msg)

    def _guard_protected(self, msgs, verb="Deleting"):
        """The gate every delete passes through. Returns the messages that may
        go — possibly none, possibly all of them.

        Two behaviours, and which one you get depends only on HOW MANY
        messages the delete is taking:

          several → the protected ones are quietly dropped from the batch and
                    the status bar says how many were left behind. No dialog:
                    a popup per protected mail is exactly the interruption
                    that makes people stop reading popups.
          one     → that is you singling it out by hand, so the question is
                    worth asking, and the dialog can also take the lock off.

        Issu 2026-09-15: "Det ignoreras då. Jag måste markera sådana mail 'ett
        i taget' och får en popup om jag verkligen vill radera det."
        """
        msgs = list(msgs)
        locked = [m for m in msgs if self._is_protected_message(m)]
        if not locked:
            return msgs
        if len(msgs) > 1:
            # Identity, not value: two messages can compare equal as dicts
            # (same sender, same subject, same minute — his Tradera receipts
            # do exactly that), and `m not in locked` would then drop the
            # wrong ones. `id()` asks the question actually meant here.
            locked_ids = {id(m) for m in locked}
            rest = [m for m in msgs if id(m) not in locked_ids]
            self._flash(f"🔒 {len(locked)} protected message(s) left alone — "
                        f"open one on its own to delete it"
                        + (f"; {len(rest)} deleted" if rest else ""))
            return rest

        msg = msgs[0]
        subj = (msg.get("subject") or "(no subject)")[:70]
        # Only TWO real answers here, and the safe one is what Return and
        # Escape both give: ask_yes_no_cancel returns None for Escape as well
        # as for the third button, so nothing that changes state may hang off
        # it. Taking the lock off lives on the right-click menu instead, where
        # it cannot be reached by a stray key press.
        ans = ask_yes_no_cancel(
            self.root, "Protected message",
            f"“{subj}”\n\n"
            f"This message is protected, so a bulk delete skips it — "
            f"{verb.lower()} it has to be said one message at a time. This "
            f"is that question.\n\n"
            f"Keep it  —  nothing happens\n"
            f"Delete it anyway  —  it goes the ordinary way, with the usual "
            f"Undo button\n\n"
            f"To take the lock off without deleting anything: right-click the "
            f"message → 🔓 Unprotect.",
            yes="Keep it", no="Delete it anyway", cancel="Cancel", icon="🔒")
        if ans is not False:
            self._flash("🔒 Left alone — it is protected")
            return []
        # "Delete it anyway" — the lock has no message left to protect.
        _protect_remove(self._protected_store, _protect_id(msg))
        return [msg]

    def _protect_messages(self, msgs, quiet=False):
        """Lock messages by hand (right-click → 🔒 Protect)."""
        n = 0
        for m in msgs:
            if self._is_protected_message(m):
                continue
            _protect_add(self._protected_store, _protect_id(m),
                         subject=m.get("subject", ""),
                         to=m.get("_to_hdr", "") or m.get("from", ""))
            n += 1
        self._render_msg_list()
        self._repaint_selection()
        if not quiet:
            self._flash(f"🔒 {n} message(s) protected — bulk delete will skip "
                        f"them" if n else "Already protected")
        return n

    def _unprotect_messages(self, msgs, quiet=False):
        """Take the lock off again.

        A mail sent with "Send and save" carries the mark in its own headers,
        and we cannot rewrite a message sitting on Gmail — so the ledger
        remembers the exception instead. That is what "unprotected" has to
        mean for those, and it is said out loud rather than quietly failing."""
        n = 0
        for m in msgs:
            key = _protect_id(m)
            was = self._is_protected_message(m)
            _protect_remove(self._protected_store, key)
            if str(m.get("_protected_hdr") or "").strip():
                # Header-protected: record the exception, and clear the flag on
                # the copy in memory so the list stops showing the padlock now
                # instead of only after the next fetch.
                self._protect_exempt_add(key)
                m["_protected_hdr"] = ""
            if was:
                n += 1
        self._render_msg_list()
        self._repaint_selection()
        if not quiet:
            self._flash(f"🔓 Protection removed from {n} message(s)"
                        if n else "Those were not protected")
        return n

    def _protect_exempt_add(self, key):
        """Remember that a header-protected message was deliberately released.

        Kept in the same file, under its own key, so the answer survives a
        restart — otherwise the padlock would come straight back on the next
        fetch and "unprotect" would be a lie."""
        if not key:
            return
        ex = self._protected_store.setdefault("exempt", {})
        ex[key] = _now_iso()
        _save_protected(self._protected_store)

    def _soft_delete(self, msgs, permanent=False, server=True):
        """Remove messages from the view AT ONCE (no Yes/No popup) and hold the
        real change for delete_undo_seconds behind an Undo button (Issu
        2026-08-01). One batch at a time — a new delete commits any previous
        one first. server=False is a local hide (nothing to commit on Gmail),
        still with the same Undo affordance.

        With delete_undo_seconds == 0 the change is made immediately, matching
        the old behaviour but without the confirmation dialog."""
        if server:
            msgs = [m for m in msgs if m.get("uid")]
        msgs = list(msgs)
        if not msgs:
            return
        # THE choke point for every delete in the program — single, bulk,
        # context menu, spam-internal, the unsubscribe clean-up. Protected mail
        # is filtered out here so no caller can forget to ask (DEL 09p).
        msgs = self._guard_protected(msgs, verb="Deleting")
        if not msgs:
            return
        # A new delete supersedes any pending one — commit it before starting.
        if self._pending_delete is not None:
            self._commit_delete()

        secs = int(self.cfg.get("delete_undo_seconds", 60) or 0)

        # Instant local removal + badge update (identical to the old path).
        for m in msgs:
            if m.get("unread") and not m.get("_always_unread"):
                self._badge_adjust(m, -1)
            if m in self._messages:
                self._messages.remove(m)
            if m in self._all_messages:
                self._all_messages.remove(m)
        # …and remember them as "gone, pending", so a reload that happens
        # during the undo window cannot hand them back (DEL 09k).
        if secs > 0:
            self._pending_delete_keys |= {_msg_key(m) for m in msgs}
        self._selected_ids = set()
        self._selected_msg = None
        self._render_msg_list()
        self._show_reading_pane_empty()
        self._repaint_badges()

        # No undo window → commit straight away, but still no popup.
        if secs <= 0:
            if server:
                self._start_server_delete(msgs, permanent)
            self._flash(f"Deleted {len(msgs)}")
            return

        entry = {"msgs": msgs, "permanent": permanent, "server": server,
                 "after_id": None}
        entry["after_id"] = self.root.after(
            secs * 1000, lambda e=entry: self._commit_delete(e))
        # In-window Undo bar (Issu 2026-08-02) — no floating topmost popup.
        self._show_inwindow_undo(
            secs, len(msgs), on_undo=lambda e=entry: self._undo_delete(e))
        self._pending_delete = entry

    def _commit_delete(self, entry=None):
        """Actually perform the pending Gmail delete and clear the limbo."""
        entry = entry or self._pending_delete
        if entry is None:
            return
        # Only act on the current pending batch (guards a stale timer).
        if self._pending_delete is entry:
            self._pending_delete = None
        if entry.get("after_id") is not None:
            try:
                self.root.after_cancel(entry["after_id"])
            except Exception:
                pass
            entry["after_id"] = None
        self._forget_pending_keys(entry)
        self._hide_inwindow_undo()
        if entry.get("server"):
            self._start_server_delete(entry["msgs"], entry["permanent"])

    def _forget_pending_keys(self, entry):
        """Drop one batch's "gone, pending" keys (DEL 09k). Called on commit,
        on undo and on shutdown — after this the list may show them again if
        the server still has them, which is the correct answer in every one of
        those three cases."""
        try:
            self._pending_delete_keys -= {_msg_key(m)
                                          for m in (entry.get("msgs") or [])}
        except Exception:
            self._pending_delete_keys = set()

    def _undo_delete(self, entry):
        """Bring a just-deleted batch back — nothing reached Gmail yet.

        DEL 09k: the batch may have been re-fetched behind the undo window
        (a Move that failed and reloaded, ↻ Refresh, the auto-check), in which
        case the list already holds a FRESH copy of each message and pushing
        the old dict in as well would show it twice. Keys, not object
        identity, decide — `m not in self._messages` compares dicts by value
        and a single flag change is enough to make the same message look like
        a different one. And a batch deleted in another folder is restored
        WITHOUT being forced into the folder now on screen."""
        if entry.get("after_id") is not None:
            try:
                self.root.after_cancel(entry["after_id"])
            except Exception:
                pass
            entry["after_id"] = None
        if self._pending_delete is entry:
            self._pending_delete = None
        self._forget_pending_keys(entry)
        here = {_msg_key(m) for m in self._all_messages}
        elsewhere = 0
        for m in entry["msgs"]:
            key = _msg_key(m)
            if key in here:
                continue                     # a re-fetch already brought it
            if not self._msg_belongs_here(m):
                elsewhere += 1               # deleted from a folder we left
                continue
            self._all_messages.append(m)
            self._messages.append(m)
            here.add(key)
            if m.get("unread") and not m.get("_always_unread"):
                self._badge_adjust(m, +1)
        self._apply_sort()
        self._render_msg_list()
        self._repaint_badges()
        self._hide_inwindow_undo()
        n = len(entry["msgs"])
        self._flash(f"Restored {n} message(s)" +
                    ("  —  they are back where they were, not in this folder"
                     if elsewhere else ""))

    def _msg_belongs_here(self, msg) -> bool:
        """Would this message be listed in the view currently on screen?

        Used by Undo so a message deleted in one folder is not dropped into
        another one just because you walked away during the undo window."""
        if self._current_folder in _VIRTUAL_FOLDERS:
            return False
        if (self._current_acct != ALL_ACCOUNTS_ID
                and msg.get("account_email", "") != self._current_acct):
            return False
        return _folder_norm(msg.get("_folder", "")) == _folder_norm(
            self._current_folder or "")

    def _flush_pending_deletes(self):
        """Commit any message still in the delete-limbo — called when the
        window closes. Closing the program IS the confirmation that the delete
        should happen, so it goes through — but it must NEVER block shutdown
        (Issu 2026-08-02: "stänger jag ned programmet så stängs det ned, även
        om det väntar på delete-tiden"). The Gmail delete therefore runs on a
        NON-daemon background thread that keeps the process alive just long
        enough to finish, while the window closes instantly. _server_delete_
        batch opens its own IMAP connections, so it is safe to run after the
        connection pool is torn down."""
        entry = self._pending_delete
        self._pending_delete = None
        if entry is None:
            return
        self._forget_pending_keys(entry)
        if entry.get("after_id") is not None:
            try:
                self.root.after_cancel(entry["after_id"])
            except Exception:
                pass
        self._hide_inwindow_undo()
        if entry.get("server"):
            msgs = list(entry.get("msgs") or [])
            perm = entry.get("permanent", False)

            def _finish():
                try:
                    self._server_delete_batch(msgs, perm)
                except Exception as e:
                    log.error("flush pending delete failed: %s", e)
            # daemon=False so the interpreter waits for the delete to finish
            # after the GUI is gone — the user still sees an instant close.
            try:
                threading.Thread(target=_finish, daemon=False).start()
            except Exception as e:
                log.error("could not start flush-delete thread: %s", e)

    # ── In-window Undo bar (Issu 2026-08-02) ────────────────────────────────
    # The Undo control now lives inside the main window (right of the Follow-up
    # quick filter) instead of a floating popup. It shows THREE steady states
    # only — "60 seconds to undo" → "30 sec" → "10 sec" (red) — so there is no
    # per-second flicker to distract.
    def _show_inwindow_undo(self, seconds, count, on_undo):
        self._cancel_undo_after()
        self._undo_bar_cb = on_undo
        try:
            self._undo_btn.configure(
                text=(f"↺ Undo delete ({count})" if count > 1
                      else "↺ Undo delete"))
            # Re-show cleanly at the far right of the quick-filter row.
            self._undo_bar.pack_forget()
            self._undo_bar.pack(side="right", padx=4)
        except Exception:
            pass
        self._set_undo_label(seconds, red=(seconds <= 10))
        # Only schedule a threshold that is still ahead of us.
        for thresh in (30, 10):
            if seconds > thresh:
                aid = self.root.after(
                    (seconds - thresh) * 1000,
                    lambda t=thresh: self._set_undo_label(t, red=(t <= 10)))
                self._undo_after_ids.append(aid)

    def _set_undo_label(self, secs, red=False):
        try:
            txt = f"{secs} seconds to undo" if secs >= 60 else f"{secs} sec"
            self._undo_lbl.configure(text=txt,
                                     fg=("#e74c3c" if red else C_ACCENT))
        except Exception:
            pass

    def _cancel_undo_after(self):
        for aid in self._undo_after_ids:
            try:
                self.root.after_cancel(aid)
            except Exception:
                pass
        self._undo_after_ids = []

    def _hide_inwindow_undo(self):
        self._cancel_undo_after()
        self._undo_bar_cb = None
        try:
            self._undo_bar.pack_forget()
        except Exception:
            pass

    def _inwindow_undo_click(self):
        cb = self._undo_bar_cb
        self._hide_inwindow_undo()
        if cb:
            try:
                cb()
            except Exception as e:
                log.error("in-window undo handler failed: %s", e)

    def _inwindow_do_click(self):
        """"⚡ Do it" — commit the pending delete now instead of waiting out
        the undo window (DEL 09j). _commit_delete already cancels the timer,
        takes the bar down and starts the Gmail delete, so this is only the
        button that says "yes, now"."""
        entry = self._pending_delete
        if entry is None:
            self._hide_inwindow_undo()
            return
        n = len(entry.get("msgs") or [])
        log.info("do-it pressed: committing %d pending delete(s) early", n)
        self._commit_delete(entry)
        self._flash(f"Deleting {n} message(s) now")

    # ── In-window SEND bar (Issu 2026-08-08) ────────────────────────────────
    # The counterpart of the delete bar above, for the undo-send window. Same
    # rules: inside the main window, no floating popup over other programs,
    # and only a few steady states instead of a per-second countdown.
    def _show_inwindow_send(self, item_id, seconds, subject=""):
        self._cancel_send_after()
        self._send_bar_id = item_id
        subj = (subject or "(no subject)").strip()
        if len(subj) > 30:
            subj = subj[:29] + "…"
        try:
            self._send_btn.configure(text="✖ Cancel send")
            self._send_bar.pack_forget()
            self._send_bar.pack(side="right", padx=4)
        except Exception:
            pass
        self._set_send_label(f"Sending “{subj}”", red=False)
        # Steady steps, not a ticking clock: halfway, then the last few
        # seconds in red. With the default 10-second window that is one
        # change, which is exactly enough warning without any flicker.
        for frac, red in ((0.5, False), (0.8, True)):
            wait = int(seconds * frac * 1000)
            if 0 < wait < seconds * 1000:
                try:
                    aid = self.root.after(
                        wait,
                        lambda s=subj, r=red: self._set_send_label(
                            f"Sending “{s}” — last chance" if r
                            else f"Sending “{s}”", red=r))
                    self._send_after_ids.append(aid)
                except Exception:
                    pass
        # Whatever happens, the bar goes away when the window is over — the
        # outbox removes it again on success, this is the safety net.
        try:
            aid = self.root.after(max(500, int(seconds * 1000) + 1500),
                                  lambda i=item_id: self._hide_inwindow_send(i))
            self._send_after_ids.append(aid)
        except Exception:
            pass

    def _set_send_label(self, text, red=False):
        try:
            self._send_lbl.configure(text=text,
                                     fg=("#e74c3c" if red else C_ACCENT))
        except Exception:
            pass

    def _cancel_send_after(self):
        for aid in getattr(self, "_send_after_ids", []):
            try:
                self.root.after_cancel(aid)
            except Exception:
                pass
        self._send_after_ids = []

    def _hide_inwindow_send(self, item_id=None):
        """Take the bar down. With an item_id it only hides the bar if it is
        still about THAT message — otherwise a slow timer from a previous send
        would wipe the bar of the one you just pressed Send on."""
        if item_id is not None and self._send_bar_id != item_id:
            return
        self._cancel_send_after()
        self._send_bar_id = None
        try:
            self._send_bar.pack_forget()
        except Exception:
            pass

    def _inwindow_send_cancel_click(self):
        item_id = self._send_bar_id
        self._hide_inwindow_send()
        if item_id:
            self._cancel_outbox(item_id, reopen=True)

    def _inwindow_send_now_click(self):
        """"⚡ Send now" — stop waiting out the undo-send window (DEL 09j).

        Brings the queued item's send_at forward to this instant and kicks the
        scheduler, so it goes on the very next tick instead of when the timer
        would have expired. _send_outbox_item takes the bar down itself."""
        item_id = self._send_bar_id
        if not item_id:
            self._hide_inwindow_send()
            return
        self._cancel_send_after()
        hit = None
        for m in self._outbox_store.get("messages", []):
            if m.get("id") == item_id and m.get("state") != "sending":
                hit = m
                break
        if hit is None:
            self._hide_inwindow_send()
            return
        hit["send_at"] = _now_iso()
        hit["state"]   = "queued"
        _save_outbox(self._outbox_store)
        self._set_send_label("Sending now…", red=False)
        log.info("send-now pressed for outbox item %s", item_id)
        self._outbox_tick()

    # ── The search WINDOW (Issu 2026-08-08) ─────────────────────────────────
    def open_search_window(self, prefill=""):
        """Open (or raise) the standalone search window.

        Only ever ONE of them — a second would search the same mail again for
        no reason, and two windows both claiming to be "the search" is exactly
        the kind of muddle this program tries not to make."""
        win = getattr(self, "_search_win", None)
        if win is not None:
            try:
                if win.top.winfo_exists():
                    win.top.deiconify()
                    win.top.lift()
                    win.top.focus_force()
                    if prefill:
                        win.e_query.delete(0, "end")
                        win.e_query.insert(0, prefill)
                        win.e_query.focus_set()
                    return win
            except Exception:
                pass
        win = SearchWindow(self)
        self._search_win = win
        if prefill:
            win.e_query.insert(0, prefill)
        return win

    def open_message_from_search(self, msg):
        """Jump the MAIN window to a message the search window found.

        Goes to the account and folder it really lives in — which is the whole
        point of showing results as a tree — and opens it there, so everything
        you can normally do to a message works on it."""
        acct   = msg.get("account_email", "")
        folder = msg.get("_folder", "")
        try:
            self.root.deiconify()
            self.root.lift()
            self.root.focus_force()
        except Exception:
            pass
        if not acct or not folder:
            return
        same = (self._current_acct == acct and self._current_folder == folder)
        if not same:
            try:
                self._reveal_folder(acct, folder)
            except Exception:
                pass
            self._select_folder(acct, folder)
        # The list may still be arriving; look for it now and again shortly.
        def _find(tries=12):
            want = _reply_key(msg)
            hit = next((m for m in self._messages
                        if _reply_key(m) == want), None)
            if hit is None:
                hit = next((m for m in self._messages
                            if m.get("uid") == msg.get("uid")
                            and m.get("_folder") == folder), None)
            if hit is not None:
                self._focus_message(hit)
                return
            if tries > 0:
                self.root.after(250, lambda: _find(tries - 1))
            else:
                self._flash("Opened the folder — the message is further down "
                            "than the loaded window; press “Load older”")
        self.root.after(150 if not same else 0, _find)

    def _do_search(self):
        """Search. The scope selector next to the box decides whether this is
        the instant local filter or a real IMAP search across every folder."""
        query = self.e_search.get().strip()
        if query == "Search mail…":
            query = ""
        scope = self._scope_labels.get(self._scope_var.get(), "folder")
        self.cfg["search_scope"] = scope
        if query and scope != "folder":
            self._search_wide(query, scope)
            return
        q = query.lower()
        self._search_active = bool(q)
        if not q:
            self._messages = list(self._all_messages)
        else:
            self._messages = [
                m for m in self._all_messages
                if q in m.get("subject", "").lower()
                or q in m.get("from", "").lower()
                or q in m.get("from_name", "").lower()
                or q in m.get("body", "").lower()
            ]
        self._selected_msg = None
        self._expanded_rows = set()
        self._apply_sort()
        suffix = f"  ({len(self._messages)})" if not q else \
                 f"  ({len(self._messages)} match)"
        self.lbl_folder.configure(text=f"  {self._current_folder}{suffix}")
        self._sync_trash_button()
        self._render_msg_list()
        self._show_reading_pane_empty()

    def _sync_trash_button(self):
        """Show "🔥 Empty Trash" only while the Trash is the open folder — it
        is the one irreversible button in the program and has no business
        sitting next to the Inbox. "✓ Read all" hides on the local views where
        there is no server folder to mark."""
        try:
            btn = getattr(self, "_empty_trash_btn", None)
            if btn is not None:
                if self._current_folder == "Trash" and not self._demo_mode:
                    btn.pack(side="left", padx=(10, 2))
                else:
                    btn.pack_forget()
            rbtn = getattr(self, "_read_all_btn", None)
            if rbtn is not None:
                if self._current_folder in _VIRTUAL_FOLDERS:
                    rbtn.pack_forget()
                elif not rbtn.winfo_manager():
                    rbtn.pack(side="left", padx=2)
        except Exception:
            pass

    def _all_search_folders(self, email, skip_excluded=True):
        """Every folder ONE account can be searched in: the standard set plus
        that account's own labels, minus whatever the exclusion lists name.

        Your own labels are in here on purpose. The other wide scopes only ever
        walked the six standard folders, so "leave 0---Frakt & kvitto out"
        would have changed nothing at all — the folder was never searched to
        begin with. "All except…" is the scope that goes everywhere, which is
        what makes taking one folder out of it worth doing (Issu 2026-08-17)."""
        folders = list(_SEARCH_FOLDERS)
        for uf in (self._user_folders or {}).get(email, []):
            mailbox = uf.get("mailbox")
            if mailbox and mailbox not in folders:
                folders.append(mailbox)
        if skip_excluded:
            folders = _search_keep_folders(self.cfg, email, folders)
        return folders

    def _search_wide(self, query, scope):
        """Read-only IMAP SEARCH across every folder — and, in the wider
        scopes, across every account — merged into one folder-labelled list.

        Runs on a worker thread like every other network call here, so a slow
        mailbox never freezes the window. Exactly as read-only as the normal
        fetch: select(readonly=True) + BODY.PEEK[].

        "all_except" is the same search over a bigger set of folders (standard
        + your own labels) and a smaller set of accounts. Because that set can
        be large it asks for HEADERS only, through the same per-field search
        the search window uses; the body of anything you open is fetched then,
        exactly as it is for every other header-first list in the program."""
        # Local notes are searched in every wide scope — they are on disk, so
        # no IMAP SEARCH can ever reach them, and silently skipping the one
        # folder you are surest about would be the worst kind of wrong.
        note_hits = _notes_search(self.cfg, query)
        except_mode = (scope == "all_except")

        if self._demo_mode:
            # Demo data has no server to search — fall back to a local sweep
            # of every mock folder so the feature can still be tried out.
            hits, q = [], query.lower()
            for folder in _FOLDERS:
                if folder in _VIRTUAL_FOLDERS:
                    continue
                if except_mode and _search_folder_skipped(
                        self.cfg, self._current_acct, folder):
                    continue
                for m in _mock_messages(folder, self._current_acct):
                    if (q in m.get("subject", "").lower()
                            or q in m.get("from", "").lower()
                            or q in m.get("body", "").lower()):
                        m = dict(m); m["_folder"] = folder
                        hits.append(m)
            self._show_search_results(note_hits + hits, query, demo=True)
            return

        if scope in ("all_accounts", "all_except"):
            targets = [a for a in self._accounts if not a.get("virtual")]
        else:
            acct = self._current_acct
            targets = ([a for a in self._accounts if not a.get("virtual")]
                       if acct == ALL_ACCOUNTS_ID else
                       [a for a in self._accounts if a.get("email") == acct])

        # Which folders each account contributes, worked out HERE on the main
        # thread — the workers get plain lists and never read settings or
        # sidebar state from a background thread.
        left_out = 0
        folders_by_acct = {}
        if except_mode:
            skipped_accounts = [a for a in targets
                                if _search_account_skipped(self.cfg,
                                                           a.get("email", ""))]
            targets = [a for a in targets
                       if not _search_account_skipped(self.cfg,
                                                      a.get("email", ""))]
            for a in targets:
                email = a["email"]
                everything = self._all_search_folders(email,
                                                      skip_excluded=False)
                kept = _search_keep_folders(self.cfg, email, everything)
                left_out += len(everything) - len(kept)
                folders_by_acct[email] = kept
            left_out += sum(
                len(self._all_search_folders(a["email"], skip_excluded=False))
                for a in skipped_accounts)
            if not targets or not any(folders_by_acct.values()):
                messagebox.showinfo(
                    "Search",
                    "“All except…” has nothing left to search — every account "
                    "or folder is on the leave-out list.\n\n"
                    "Tools → “Search: what to leave out…” is where that list "
                    "lives.", parent=self.root)
                return
        if not targets:
            return

        where = ("everything except what you left out" if except_mode
                 else "all folders")
        self.lbl_folder.configure(text=f"  Searching {where} for “{query}”…")
        token = object()
        self._fetch_token = token

        def worker():
            collected, errors = [], []
            for a in targets:
                try:
                    pwd = _decrypt_secret(a.get("secret", ""))
                    if except_mode:
                        collected.extend(_search_account_by_field(
                            a["email"], pwd, query, _SEARCH_FIELDS,
                            folders_by_acct.get(a["email"], [])))
                    else:
                        collected.extend(
                            _imap_search_folders(a["email"], pwd, query))
                except Exception as e:
                    errors.append((a["email"], str(e)))
                    log.error("Wide search failed for %s: %s", a["email"], e)
            collected.sort(key=lambda m: m.get("_sortkey", 0.0), reverse=True)

            def done():
                if self._fetch_token is not token:
                    return
                note = (f" — {left_out} folder{'s' if left_out != 1 else ''} "
                        f"left out" if except_mode and left_out else "")
                self._show_search_results(note_hits + collected, query,
                                          note=note)
                if errors:
                    messagebox.showwarning(
                        "Search problem",
                        "Could not search:\n\n" +
                        "\n".join(f"• {e[0]}: {e[1]}" for e in errors),
                        parent=self.root)
            try:
                self.root.after(0, done)
            except Exception:
                pass

        threading.Thread(target=worker, daemon=True).start()

    def _show_search_results(self, hits, query, demo=False, note=""):
        """Render a wide-search result set as if it were a folder. The rows
        keep their own _folder, so the reading pane still says where each hit
        actually lives."""
        hits = self._apply_local_state(hits)
        self._all_messages  = hits
        self._messages      = hits
        self._selected_msg  = None
        self._expanded_rows = set()
        self._search_active = True
        self._apply_sort()
        self.lbl_folder.configure(
            text=f"  Search “{query}”  ({len(hits)} match"
                 f"{'es' if len(hits) != 1 else ''}"
                 f"{' — demo data' if demo else ''}{note})")
        self._render_msg_list()
        self._show_reading_pane_empty()

    # ==========================================================================
    # DEL 09b — OUTBOX (send later + undo send), DRAFTS, NOTIFICATIONS
    # ==========================================================================

    def queue_send(self, payload: dict, when=None, kind="normal",
                   protect=False):
        """Put one message in the outbox. This is the ONLY way anything leaves
        this program — plain Send, Send later, Smart Reply and the unsubscribe
        mails all end up here.

        when=None  → send after the undo window (or immediately if undo is off)
        when=<dt>  → scheduled; no undo toast, it is visible in File → Outbox
        protect=True → "✉🔒 Send and save" (DEL 09p): the message goes out with
                     the X-Freemail-Protected header, so the copy Gmail files
                     in Sent is skipped by every bulk delete from then on.
        """
        # ── Last line of defence for the address corruption (Issu 2026-08-01) ──
        # Because this is the ONE path everything leaves by, cleaning here covers
        # callers that never learned to: the unsubscribe mailer, a bounce retry,
        # a draft restored from an older version, and anything added later. Any
        # character that gets stripped is written to the log with its Unicode
        # code point and this `kind`, which is how the source will finally be
        # identified — see _sanitize_payload_addresses / _addr_forensics.
        payload = _sanitize_payload_addresses(dict(payload), f"queue_send/{kind}")
        # Same choke point, same treatment for the SUBJECT and BODY (Issu
        # 2026-08-01): strip invisible/control junk and log any � so the "ä→?"
        # corruption finally leaves a trace even for callers that never asked.
        payload = _sanitize_payload_text(payload, f"queue_send/{kind}")
        item = {
            "id":      _new_id(),
            "state":   "queued",
            "kind":    kind,
            "created": _now_iso(),
            "from":    payload.get("from", ""),
            "to":      payload.get("to", ""),
            "cc":      payload.get("cc", ""),
            "subject": payload.get("subject", ""),
            "body":    payload.get("body", ""),
            # Optional rich alternative (Smart Reply's two-part HTML). Empty for
            # every plain message, so nothing else changes.
            "body_html": payload.get("body_html", "") or "",
            "bcc":     list(payload.get("bcc") or []),
            "attachments": [],      # filled in just below
            "draft_id":    payload.get("draft_id", ""),
            # Threading (Issu 2026-08-05): the original message's Message-ID,
            # so the recipient's client links this reply into the same thread
            # instead of showing a brand-new, unrelated message.
            "in_reply_to": payload.get("in_reply_to", "") or "",
            "references":  payload.get("references", "") or "",
            # DEL 09p — "Send and save". Carried on the outbox item rather than
            # applied at the button, so it survives the undo window, a restart
            # with mail still queued, a scheduled send and a failed retry.
            "protect": bool(protect),
            "error":   "", "tries": 0,
        }
        if protect:
            # Our own Message-ID, decided ONCE and written down now, so a retry
            # cannot send the same mail under two different ids. Gmail may well
            # replace it with one of its own — that is why the header above is
            # what protection actually rests on, and this is the spare key.
            try:
                item["message_id"] = make_msgid(
                    domain=(parseaddr(item["from"])[1] or "").split("@")[-1]
                           or None)
            except Exception:
                item["message_id"] = make_msgid()
        # Take our own copy of every attachment, so the message still has its
        # files when it goes out tomorrow morning (see _outbox_store_attachments).
        item["attachments"] = _outbox_store_attachments(
            item["id"], list(payload.get("attachments") or []))

        if when is not None:
            held = _send_window_next(when, self.cfg)
            item["send_at"] = held.isoformat(timespec="seconds")
            self._outbox_store.setdefault("messages", []).append(item)
            _save_outbox(self._outbox_store)
            if held != when:
                self._flash(f"Held to your sending window: "
                            f"{held.strftime('%Y-%m-%d %H:%M')}")
            else:
                self._flash(f"Scheduled for {when.strftime('%Y-%m-%d %H:%M')}")
            self._outbox_tick()
            return item["id"]

        delay = int(self.cfg.get("undo_send_seconds", 10)) \
            if self.cfg.get("undo_send_on", True) else 0
        delay = max(0, min(delay, 600))          # hard ceiling: 10 minutes
        due = datetime.now() + timedelta(seconds=delay)
        held = _send_window_next(due, self.cfg)
        item["send_at"] = held.isoformat(timespec="seconds")
        self._outbox_store.setdefault("messages", []).append(item)
        _save_outbox(self._outbox_store)

        if held != due:
            # Deliberately said out loud: pressing Send and having nothing
            # happen for nine hours would otherwise look like a fault.
            self._flash(f"Held until {held.strftime('%a %H:%M')} "
                        f"(your sending window)")
            self._set_status(extra=f"1 message waiting for "
                                   f"{held.strftime('%a %H:%M')} — "
                                   f"File → Outbox to send it now")
            self._outbox_tick()
            return item["id"]

        if delay > 0 and kind != "unsubscribe":
            # The bar IS the confirmation — no "message queued" popup on top of
            # it, that would defeat the point of a quiet undo window.
            #
            # IN the main window, not floating over every other program
            # (Issu 2026-08-08). Same treatment the delete undo already got.
            self._show_inwindow_send(item["id"], delay, item["subject"])
        self._outbox_tick()
        return item["id"]

    def _outbox_find(self, item_id):
        for m in self._outbox_store.get("messages", []):
            if m.get("id") == item_id:
                return m
        return None

    def _cancel_outbox(self, item_id, reopen=False):
        """Take a message back out of the queue. With reopen=True the compose
        window comes back with everything exactly as it was — that is what the
        Cancel button on the undo toast does."""
        item = self._outbox_find(item_id)
        if item is None or item_id in self._sending_ids:
            # Already gone out — be honest about it rather than pretending.
            self._flash("Too late — that message has already been sent")
            return
        self._outbox_store["messages"] = [
            m for m in self._outbox_store.get("messages", [])
            if m.get("id") != item_id]
        _save_outbox(self._outbox_store)
        toast = self._undo_toasts.pop(item_id, None)
        if toast is not None:
            toast.close()
        self._hide_inwindow_send(item_id)

        # The outbox no longer owns this message, so the draft must stop
        # claiming to be queued — otherwise a crash right now would lose it
        # from the start-up restore as well.
        if item.get("draft_id"):
            for d in _list_drafts():
                if d.get("id") == item["draft_id"]:
                    d.pop("queued", None)
                    _save_draft(d)
                    break

        if reopen:
            draft = {
                "id": item.get("draft_id") or _new_id(),
                "kind": "compose", "from": item.get("from", ""),
                "to": item.get("to", ""), "cc": item.get("cc", ""),
                "subject": item.get("subject", ""), "body": item.get("body", ""),
                "attachments": item.get("attachments", []),
            }
            ComposeWindow(self.root, self.cfg, app=self,
                          accounts=self._accounts, draft=draft)
        else:
            # Really cancelled, not reopened — the copied attachments have
            # nothing left to belong to.
            _outbox_clear_attachments(item)
            self._flash("Removed from the outbox")

    def _outbox_tick(self):
        """Scheduler. Runs every few seconds, sends whatever is due, and
        reschedules itself. Kept deliberately dumb: state lives on disk, so a
        crash or a restart simply resumes where it left off."""
        if self._outbox_after_id is not None:
            try:
                self.root.after_cancel(self._outbox_after_id)
            except Exception:
                pass
            self._outbox_after_id = None
        try:
            for item in _outbox_due(self._outbox_store):
                if item["id"] in self._sending_ids:
                    continue
                self._send_outbox_item(item)
        except Exception as e:
            log.error("Outbox tick failed: %s", e)
        finally:
            try:
                self._outbox_after_id = self.root.after(3000, self._outbox_tick)
            except Exception:
                pass   # window is closing

    def _send_outbox_item(self, item):
        """Actually hand one queued message to SMTP, on a worker thread."""
        item_id = item["id"]
        self._sending_ids.add(item_id)
        item["state"] = "sending"
        toast = self._undo_toasts.pop(item_id, None)
        if toast is not None:
            toast.close()
        # Past the point of no return — the Cancel bar must go, immediately.
        self._hide_inwindow_send(item_id)

        if self._demo_mode:
            self._sending_ids.discard(item_id)
            self._outbox_store["messages"] = [
                m for m in self._outbox_store.get("messages", [])
                if m.get("id") != item_id]
            _save_outbox(self._outbox_store)
            _outbox_clear_attachments(item)
            self._flash("Message sent! (demo)")
            return

        from_email = parseaddr(item.get("from", ""))[1] or item.get("from", "")
        pwd = self._secret_for(from_email)
        if not pwd:
            self._outbox_fail(item, "No stored password for this sender account.")
            return

        # Clean each address one last time before SMTP — belt and braces against
        # the stray-character corruption (Issu 2026-08-01), covering queued and
        # retried items that never passed back through the compose window.
        to_addrs = [_clean_one_address(x)[0]
                    for x in _re.split(r"[;,]", item.get("to", "") or "")
                    if x.strip()]
        bcc_addrs = [_clean_one_address(x)[0]
                     for x in (item.get("bcc") or []) if x.strip()]
        cc_addrs = [_clean_one_address(x)[0]
                    for x in _re.split(r"[;,]", item.get("cc", "") or "")
                    if x.strip()]
        subject   = item.get("subject", "")
        body      = item.get("body", "")
        html_body = item.get("body_html", "") or ""
        paths     = item.get("attachments") or []
        in_reply_to = item.get("in_reply_to", "") or ""
        references  = item.get("references", "") or ""
        protect     = bool(item.get("protect"))
        msg_id      = item.get("message_id", "") or ""

        def worker():
            ok, err = True, ""
            try:
                _smtp_send(from_email, pwd, to_addrs, cc_addrs, subject, body,
                           paths, bcc_addrs=bcc_addrs, html_body=html_body,
                           in_reply_to=in_reply_to, references=references,
                           message_id=msg_id, protected=protect)
            except Exception as e:
                ok, err = False, str(e)
                log.error("SMTP send failed (outbox %s): %s", item_id, e)

            def done():
                self._sending_ids.discard(item_id)
                if ok:
                    self._outbox_store["messages"] = [
                        m for m in self._outbox_store.get("messages", [])
                        if m.get("id") != item_id]
                    _save_outbox(self._outbox_store)
                    if item.get("draft_id"):
                        # NOW it is really sent. Keep the draft a few minutes
                        # as a safety net, then let the sweeper remove it
                        # (Tools → Sending).
                        for d in _list_drafts():
                            if d.get("id") == item["draft_id"]:
                                d.pop("queued", None)
                                d["sent"] = _now_iso()
                                _save_draft(d)
                                break
                    _outbox_clear_attachments(item)
                    if protect:
                        # The header in the message is what really protects it;
                        # this second record only matters if Gmail kept OUR
                        # Message-ID, in which case the mail is protected here
                        # even should the header ever be stripped in transit.
                        if msg_id:
                            _protect_add(self._protected_store, msg_id,
                                         subject=subject,
                                         to=item.get("to", ""))
                        self._flash("🔒 Sent and protected — bulk delete will "
                                    "leave it alone")
                    else:
                        self._flash("Message sent!")
                    self._activity_log(
                        "sent", account=from_email,
                        sender=from_email, subject=subject,
                        detail=f"to {item.get('to','')}"
                               + (f", cc {item.get('cc','')}"
                                  if item.get("cc") else "")
                               + ("  🔒 protected" if protect else ""))
                    # Filters that opted into the "after a message is sent"
                    # trigger (DEL 04z2) run over the sent message now. It has
                    # no server UID, so server-side actions safely no-op; local
                    # actions (tag / notify / snooze) and the log still apply.
                    try:
                        self._run_filters_on([{
                            "from": from_email, "from_name": from_email,
                            "account_email": from_email,
                            "subject": subject, "body": body,
                            "to": item.get("to", ""),
                            "_folder": "Sent", "attachments": paths,
                            "id": "sent-" + item_id, "uid": None,
                        }], "sent")
                    except Exception as e:
                        log.warning("after-send filter run failed: %s", e)
                else:
                    self._outbox_fail(item, err)
            try:
                self.root.after(0, done)
            except Exception:
                pass

        threading.Thread(target=worker, daemon=True).start()

    def _outbox_fail(self, item, error):
        """A failed send stays in the outbox — never silently dropped."""
        self._sending_ids.discard(item.get("id", ""))
        item["state"] = "failed"
        item["error"] = error
        item["tries"] = int(item.get("tries", 0)) + 1
        _save_outbox(self._outbox_store)
        self._activity_log("sent", account=item.get("from", ""),
                           sender=item.get("from", ""),
                           subject=item.get("subject", ""),
                           detail=f"FAILED — {error}  (still in the Outbox)")
        # The menu path is FILE → Outbox. It used to say "Tools → Outbox",
        # which sent Issu hunting for a folder called tools\outbox on disk
        # (2026-08-07). It is a window in this program, not a directory.
        messagebox.showerror(
            "Send failed",
            f"{error}\n\nThe message is still waiting in the Outbox — nothing "
            f"was lost. Open it with  File → Outbox…  (a window in this "
            f"program, not a folder on disk), fix the problem and press "
            f"\"Send now\" there.", parent=self.root)

    # ── Draft restore on start-up ─────────────────────────────────────────────
    def _nag_stuck_outbox(self):
        """Say so, at start-up, if mail has been stuck in the outbox.

        Issu's three failed replies sat there from 2026-08-07 and he only
        found out by trying to send something else. A failed send already
        shows an error at the moment it happens — but if the program was
        closed, or the error was dismissed while busy, nothing ever mentioned
        it again. The queue is exactly where a message can wait for ever
        without anybody noticing, so it gets one quiet notice.

        Deliberately not a modal box: a toast that tells you and lets you get
        on with it, and it only speaks when something has genuinely been
        waiting more than an hour."""
        try:
            items = self._outbox_store.get("messages", []) or []
            now = datetime.now()
            stuck = []
            for m in items:
                if m.get("state") not in ("queued", "failed"):
                    continue
                when = _parse_iso(m.get("send_at", "")) or _parse_iso(
                    m.get("created", ""))
                if when is None or (now - when).total_seconds() < 3600:
                    continue          # scheduled for later, or just queued
                stuck.append((m, when))
            if not stuck:
                return
            failed = [m for m, _w in stuck if m.get("state") == "failed"]
            oldest = min(w for _m, w in stuck)
            days = max(0, (now - oldest).days)
            when_txt = (f"{days} day(s)" if days
                        else f"{int((now - oldest).total_seconds() // 3600)} hour(s)")
            lines = [f"{(m.get('subject') or '(no subject)')[:44]}"
                     for m, _w in stuck[:3]]
            log.warning("Outbox: %d message(s) waiting, oldest %s "
                        "(%d failed)", len(stuck), oldest.isoformat(timespec="minutes"),
                        len(failed))
            self._activity_log(
                "sent", detail=f"{len(stuck)} message(s) still waiting in the "
                               f"Outbox, oldest for {when_txt}"
                               + (f", {len(failed)} failed" if failed else ""))
            NotifyToast(
                self.root,
                f"📤  {len(stuck)} message(s) still in the Outbox",
                lines + [f"waiting {when_txt}"
                         + (f" · {len(failed)} failed" if failed else "")
                         + "  —  click to open it"],
                on_click=self._outbox_dialog, seconds=14)
        except Exception as e:
            log.debug("outbox nag failed: %s", e)

    def _offer_draft_restore(self):
        """After a crash (or a "keep as draft" close) offer the drafts back.

        Drafts that are queued or already sent are skipped — the outbox owns
        those, and reopening one would risk sending the same message twice."""
        drafts = [d for d in _list_drafts()
                  if not d.get("sent") and not d.get("queued")]
        if not drafts:
            return
        n = len(drafts)
        if not messagebox.askyesno(
                "Unsent messages",
                f"{n} unsent message{'s' if n > 1 else ''} "
                f"{'were' if n > 1 else 'was'} found from an earlier session.\n\n"
                f"Open {'them' if n > 1 else 'it'} now?", parent=self.root):
            return
        for d in drafts[:6]:      # a sane limit — the rest stay on disk
            ComposeWindow(self.root, self.cfg, app=self,
                          accounts=self._accounts, draft=d)

    # ── New-mail notification ─────────────────────────────────────────────────
    def _notify_new(self, messages):
        """Toast for messages we have not shown before. The very first fetch
        of a session only fills the "seen" set — nobody wants 40 popups
        because they started the program."""
        fresh = [m for m in messages
                 if _msg_key(m) not in self._seen_keys
                 and m.get("_filter_notify", "default") != "never"
                 # An auto-read folder is silent by definition. Belt and braces
                 # on top of the "never" above: a rule's action_notify="always"
                 # must not be able to shout over a folder you deliberately
                 # asked to keep quiet (Issu 2026-08-17).
                 and not m.get("_auto_read")
                 and (m.get("unread") or m.get("_filter_notify") == "always")]
        for m in messages:
            self._seen_keys.add(_msg_key(m))
        background = self._bg_check
        self._bg_check = False
        if self._first_fetch:
            self._first_fetch = False
            return
        if not background or not fresh or not self.cfg.get("notify_on", True):
            return
        lines = [f"{(m.get('from_name') or m.get('from'))}: "
                 f"{(m.get('subject') or '(no subject)')[:44]}"
                 for m in fresh[:3]]
        if len(fresh) > 3:
            lines.append(f"…and {len(fresh) - 3} more")
        first = fresh[0]
        title = (f"📬  {len(fresh)} new message"
                 f"{'s' if len(fresh) > 1 else ''}")
        # Prefer a real Windows toast; fall back to the in-app one if the OS
        # notification could not be shown (or was turned off).
        shown_native = False
        if self.cfg.get("notify_windows", True):
            shown_native = self._windows_toast(title, "\n".join(lines))
        if not shown_native:
            NotifyToast(self.root, title, lines,
                        on_click=lambda m=first: self._jump_to(m))
        # The toast disappears after a few seconds; the flashing taskbar
        # button is what is still there when you come back to the computer.
        self._flash_taskbar()
        if self.cfg.get("notify_sound", False):
            try:
                import winsound
                winsound.MessageBeep(winsound.MB_ICONASTERISK)
            except Exception:
                try:
                    self.root.bell()
                except Exception:
                    pass

    # ── Taskbar: unread count in the title, and a flash on new mail ───────────
    #
    # This is the "OS notification" item, done with the two mechanisms Windows
    # actually respects for a plain desktop program. A tray icon was the other
    # candidate and was deliberately not built: Shell_NotifyIcon through
    # ctypes needs a message loop of its own to receive clicks, and a
    # half-working tray icon that swallows your window is worse than none.

    def _get_hwnd(self):
        """The real Win32 handle of the main window, found once and cached.

        winfo_id() is tkinter's inner content frame, not the top-level window
        the taskbar knows about — the same reason _set_window_icon uses
        FindWindowW."""
        if getattr(self, "_hwnd", None):
            return self._hwnd
        if platform.system() != "Windows":
            return None
        try:
            self._hwnd = ctypes.windll.user32.FindWindowW(None,
                                                          self.root.title())
        except Exception:
            self._hwnd = None
        return self._hwnd

    def _update_title(self):
        """Show the unread count in the title, so the taskbar and Alt-Tab
        carry it.

        Counts what is LOADED in the current view — Phase 1 does not poke the
        server for counts it was not asked to fetch, and an honest "what you
        can see" number beats a wrong global one."""
        try:
            unread = self._total_unread()
            base = "F(re)email"
            title = f"{base}  ({unread})" if unread else base
            if self.root.title() != title:
                self.root.title(title)
                # Title change can invalidate the cached HWND (FindWindowW keys
                # on the title) — drop it so the next taskbar call re-finds it.
                self._hwnd = None
        except Exception:
            pass

    def _flash_taskbar(self):
        """Nudge the taskbar button a few times when new mail arrives and the
        window is NOT in front.

        DISCREET ON PURPOSE (Issu is sensitive to blinking): the TASKBAR BUTTON
        only — never the title bar — and a FINITE handful of flashes that then
        stop, instead of blinking non-stop until the window is clicked. Can be
        switched off entirely with the "flash the taskbar" setting."""
        if platform.system() != "Windows":
            return
        if not self.cfg.get("notify_flash", True):
            return
        hwnd = self._get_hwnd()
        if not hwnd:
            return
        try:
            user32 = ctypes.windll.user32
            if user32.GetForegroundWindow() == hwnd:
                return
            from ctypes import wintypes

            class FLASHWINFO(ctypes.Structure):
                _fields_ = [("cbSize",    wintypes.UINT),
                            ("hwnd",      wintypes.HWND),
                            ("dwFlags",   wintypes.DWORD),
                            ("uCount",    wintypes.UINT),
                            ("dwTimeout", wintypes.DWORD)]

            FLASHW_TRAY = 0x00000002   # taskbar button only (no title-bar blink)
            # uCount=2, no TIMERNOFG → two gentle flashes, then it settles.
            info = FLASHWINFO(ctypes.sizeof(FLASHWINFO), hwnd,
                              FLASHW_TRAY, 2, 0)
            user32.FlashWindowEx(ctypes.byref(info))
        except Exception as e:
            log.debug("FlashWindowEx failed: %s", e)

    def _jump_to(self, msg):
        """Bring the window forward and open a specific message."""
        try:
            self.root.deiconify()
            self.root.lift()
            self.root.focus_force()
        except Exception:
            pass
        if msg in self._messages:
            self._show_message_in_reading_pane(msg)
            self._selected_msg = msg

    # ── Local state: filters, block list, snooze ──────────────────────────────
    def _apply_local_state(self, messages: list, manual: bool = False) -> list:
        """Run every LOCAL rule over a freshly fetched list and return what
        should actually be shown. Phase-1 safe by construction: this only ever
        decides what THIS program displays — Gmail is never told anything.

        manual=True also runs the "only when I run them" filters (DEL 04x)."""
        # Diagnose every MANUAL run always (that is the moment you are asking
        # "why didn't it move?"), and automatic runs only while the setting is
        # on — a full explanation of forty messages × ten rules on every
        # new-mail check would bury the log.
        want_diag = bool(manual or self.cfg.get("filter_diagnostics", True))
        try:
            stats = _apply_filters(
                messages, self._filter_store, self._tag_store, manual=manual,
                allow_server=(self.cfg.get("allow_server_changes", False)
                              and not self._demo_mode),
                diagnose=want_diag)
        except Exception as e:
            log.error("Filter run failed: %s", e)
            stats = {"snoozed": []}
        if stats.get("diag"):
            self._record_filter_diag(stats["diag"], verbose=bool(manual))
        # Rules that matched but are still counting down (DEL 04z3). Kept so
        # "Run filters now" can say "3 are waiting" instead of the flatly
        # untrue "nothing matched" — a waiting rule sets no _filter_names.
        self._filter_waiting = list(stats.get("waiting") or [])
        if self._filter_waiting and manual:
            for w in self._filter_waiting[:10]:
                log.info("filter '%s' is waiting on “%.60s” — %s to go (acts %s)",
                         w["fname"], w["subject"], _human_minutes(w["left"]),
                         w["at"] or "when it can be dated")

        # Server-side actions the filters asked for (move / trash / mark-read /
        # star on Gmail) run on a background thread — off the GUI, deduped, and
        # only when Server changes is on (already gated above).
        if stats.get("server_actions"):
            self._dispatch_filter_server_actions(stats["server_actions"])

        # Rules that read the BODY could not be judged on messages whose body
        # is not downloaded yet. Get those bodies and judge them properly —
        # see _filter_needs_body for why guessing was never acceptable.
        if stats.get("need_body"):
            self._finish_deferred_rules(stats["need_body"])

        # ── Folders that read themselves (Issu 2026-08-17) ───────────────────
        # AFTER the rules, deliberately: a rule may have just filed this
        # message into the auto-read folder, and the point is that it is read
        # by the time you would otherwise have seen a badge for it. Runs on
        # every fetch of every folder, so a receipt is silenced whether it
        # arrived here, was moved here, or was already sitting here.
        try:
            self._dispatch_auto_read(self._apply_auto_read(messages))
        except Exception as e:
            log.error("Auto-read pass failed: %s", e)

        # Record new filter activity (deduped) for the Filter-log viewer, and
        # mirror it to Freemail.log so there is a lasting record of what rules
        # did — the "log when mail follows rules" Issu asked for (DEL 04x).
        for ev in stats.get("events", []):
            token = (ev["fid"], ev["key"], ev["actions"])
            if token in self._filter_log_seen:
                continue
            self._filter_log_seen.add(token)
            ev = dict(ev, when=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
            self._filter_log.append(ev)
            log.info("filter '%s' → %s : %s  [%s] from %s",
                     ev["fname"], ev["actions"], ev["subject"][:60],
                     ev["folder"], ev["sender"])
            # …and to the on-disk activity log, which survives a restart.
            self._log_filter_events([ev])
            self._bump_rule_stats([ev])
        if len(self._filter_log) > 500:            # keep the viewer bounded
            self._filter_log = self._filter_log[-500:]

        # A filter may ask for automatic snoozing of what it matched.
        for msg, mins in stats.get("snoozed", []):
            self._snooze_message(msg, datetime.now() + timedelta(minutes=mins),
                                 quiet=True)
        self._handle_filter_unsubs(stats)

        visible = []
        for m in messages:
            # A NOTE is never hidden by a rule. Colour it, star it, fine — but
            # something you deliberately saved to your own disk must not be
            # able to vanish behind a filter or a block list you set up for
            # incoming mail. Notes are the one place with no surprises.
            is_note = bool(m.get("_note_path"))
            if not is_note:
                if m.get("_filter_hide"):
                    continue
                if _is_blocked(self._blocklist_store, m):
                    continue
                if _is_local_spam(self._blocklist_store, m):
                    m["spam"] = True
                # Keep flagged senders unread while their mail is in an Inbox.
                # The marker is honoured again at render time so it cannot be
                # lost during the session (see _render_one_row).
                if (m.get("_folder") == "Inbox"
                        and _is_always_unread(self._blocklist_store, m)):
                    m["unread"] = True
                    m["_always_unread"] = True
                else:
                    m["_always_unread"] = False
                self._apply_float_flags([m])     # floating follow-ups (04j)
                # (A snoozed mail used to be skipped here. Snooze is a plain
                # reminder now - nothing is ever hidden by it.)
            visible.append(m)
        return visible

    def _finish_deferred_rules(self, msgs):
        """Download the bodies of messages a BODY-reading rule could not be
        judged against, then judge them (Issu 2026-08-16).

        Only the messages that actually need it, and each one only once per
        session — a rule testing the body must not turn every new-mail check
        into a full download of the folder. Once the body is in place the
        message is no longer deferrable, so this cannot loop."""
        if self._demo_mode or not msgs:
            return
        todo = []
        for m in msgs:
            key = _msg_key(m)
            if key in self._body_for_rules_done:
                continue
            if not (m.get("uid") and m.get("account_email")
                    and m.get("_folder")):
                continue
            self._body_for_rules_done.add(key)
            todo.append(m)
        if not todo:
            return
        # Bounded: a folder of two thousand messages and one body rule must not
        # become two thousand fetches in one go. The rest are picked up on the
        # following checks.
        todo = todo[:25]
        log.info("Fetching %d message body(ies) so body-based rules can be "
                 "judged properly", len(todo))

        def worker():
            filled = []
            for m in todo:
                pwd = self._secret_for(m.get("account_email", ""))
                if not pwd:
                    continue
                try:
                    built = _fetch_single_full_body(
                        m["account_email"], pwd, m["_folder"], m["uid"],
                        interactive=False)
                except Exception as e:
                    log.debug("Deferred-rule body fetch failed for %s: %s",
                              _msg_key(m), e)
                    continue
                if built:
                    m.update(built)        # in place — other windows share it
                    filled.append(m)

            def done():
                if not filled:
                    return
                # _run_filters_on is the existing path for "messages that are
                # not the on-screen list": local actions, server actions,
                # logging, snooze — and no redraw. Exactly right here.
                self._run_filters_on(filled, "fetch")
            try:
                self.root.after(0, done)
            except Exception:
                pass

        threading.Thread(target=worker, daemon=True).start()

    # ── Filter diagnostics: "why didn't my rule fire?" (Issu 2026-08-03) ───────
    def _record_filter_diag(self, diag, verbose=True):
        """Keep the last filter run's full explanation, and mirror it to
        Freemail.log.

        Two levels on purpose. A MANUAL run writes everything, message by
        message — that is the run you did because something is wrong. A
        BACKGROUND run writes only the per-rule summary, so a mailbox check
        every five minutes does not fill the log with the same forty messages
        over and over (Issu is not to be given a log he cannot read).

        That was not enough. Measured on his machine on 2026-08-08: even the
        summary is ~30 lines, written EVERY MINUTE whether or not a single
        rule matched, and it had become 80% of a 24 MB log. So a background
        run that matched NOTHING now writes one line instead of thirty. The
        moment anything actually happens the full summary is back — which is
        the only time it was ever worth reading.

        The diagnosis is still kept in memory in full, so "Why didn't my rule
        fire?" shows everything regardless."""
        self._filter_diag = diag
        try:
            lines = _diag_render(diag, verbose=verbose)
            if not verbose:
                try:
                    rules = diag.get("rules") or []
                    matched = sum(int(r.get("hits", 0) or 0) for r in rules)
                    # Standing warnings — "Server changes is off", "this rule
                    # has no action" — are worth saying, but they are the SAME
                    # every minute. Repeating them is the noise itself. So they
                    # are written when they CHANGE, and then not again.
                    sig = (diag.get("server_note", ""),
                           tuple(sorted(r.get("name", "") for r in rules
                                        if not r.get("ran")
                                        or not r.get("actions"))))
                except Exception:
                    matched, sig = 1, None      # unsure → say it all, as before
                changed = (sig is not None
                           and sig != getattr(self, "_diag_sig", None))
                if sig is not None:
                    self._diag_sig = sig
                if not matched and not changed:
                    log.info("Filter run (%s): %d message(s), %d rule(s), "
                             "nothing matched.",
                             diag.get("trigger", "?"),
                             diag.get("n_messages", 0),
                             diag.get("n_rules", 0))
                    return
            for line in lines:
                log.info("%s", line)
        except Exception as e:
            log.warning("Could not write the filter diagnosis: %s", e)

    def _filter_diag_dialog(self):
        """Show the last filter run in full: which rules exist, which ran,
        which matched completely, and which came CLOSE and on what."""
        top = self._dialog_shell("Why didn't my rule fire?", 900, 640)
        tk.Label(top,
                 text="The last filter run, rule by rule and message by "
                      "message. ✔ = matched in full · ~ = near miss (some "
                      "conditions matched, not enough for this match mode) · "
                      "✖ = no match · – = the rule did not even run. The same "
                      "text is written to Freemail.log.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 wraplength=860, justify="left", pady=4).pack(fill="x", padx=12)

        frame = tk.Frame(top, bg=C_BG3)
        frame.pack(fill="both", expand=True, padx=12, pady=6)
        sb = tk.Scrollbar(frame, bg=C_BG3, troughcolor=C_BG1)
        sb.pack(side="right", fill="y")
        sbx = tk.Scrollbar(frame, orient="horizontal", bg=C_BG3,
                           troughcolor=C_BG1)
        sbx.pack(side="bottom", fill="x")
        txt = tk.Text(frame, bg=C_BG2, fg=C_FG, relief="flat", wrap="none",
                      font=("Consolas", 9), padx=8, pady=6,
                      yscrollcommand=sb.set, xscrollcommand=sbx.set,
                      insertofftime=0, insertontime=9999999)
        no_blink(txt)
        sb.configure(command=txt.yview)
        sbx.configure(command=txt.xview)
        txt.pack(fill="both", expand=True)
        # Deliberately NOT _attach_nav'd: this is a long report you scroll with
        # the arrow keys. Passing them to the main window's navigator would
        # move the message selection behind your back while you read.

        diag = getattr(self, "_filter_diag", None)
        if not diag:
            txt.insert("end",
                       "  No filter run has been diagnosed yet.\n\n"
                       "  Open Tools → Mail filters… and press "
                       "“▶ Run now (loaded mail)”, then come back here.\n")
        else:
            for line in _diag_render(diag, verbose=True):
                txt.insert("end", line + "\n")
            if diag.get("truncated"):
                txt.insert("end", f"\n  … {diag['truncated']} more message(s) "
                                  f"were filtered but not explained here.\n")
        txt.configure(state="disabled")

        def _copy():
            body = "\n".join(_diag_render(diag, verbose=True)) if diag else ""
            self._copy_to_clipboard(body, "Diagnosis copied")

        br = tk.Frame(top, bg=C_BG3)
        br.pack(fill="x", padx=12, pady=(0, 10))
        for text, colour, cmd in (
                ("▶ Run the filters again now", C_BTN_NEW,
                 lambda: (top.destroy(), self._run_filters_now())),
                ("📋 Copy all", C_BTN_STD, _copy),
                ("Open Freemail.log…", C_BTN_STD, self._open_log_file),
                ("Close", C_BTN_STD, top.destroy)):
            tk.Button(br, text=text, bg=colour, fg=C_BTN_FG,
                      font=("Segoe UI", 9), relief="flat", cursor="hand2",
                      padx=12, pady=4, command=cmd).pack(side="left", padx=4)

    def _open_log_file(self):
        """Open Freemail.log in whatever the system uses for .log files."""
        try:
            path = _log_file
            if os.path.isfile(path):
                open_path(path)          # noqa: attribute exists on Windows
            else:
                messagebox.showinfo("Log", f"No log file at:\n{path}",
                                    parent=self.root)
        except Exception as e:
            log.warning("Could not open the log: %s", e)
            # _LOG_PATH never existed — this fall-back raised NameError inside
            # the handler for the ORIGINAL error, so "Open Freemail.log" on a
            # machine without a file association failed twice and told you
            # nothing (found by a static pass, 2026-08-08).
            messagebox.showinfo("Log", f"The log file is at:\n{_log_file}",
                                parent=self.root)

    # ==========================================================================
    # DEL 04y2 — CROSS-ACCOUNT DELIVERY  (the whole message, exactly once)
    # ==========================================================================
    #
    # Issu 2026-08-16, and the reason this is now one function instead of two
    # copies of nearly-the-same code inside the dispatcher:
    #
    #   "Filter verkar inte fungera… de skickas runt… blir kopior och en del
    #    av dem verkar tappa sitt body-innehåll."
    #
    # All three complaints are the same journey going wrong at three points, so
    # all three are answered here, in the ONE place a message can leave one
    # account for another:
    #
    #   1. THE BODY.  Never upload what has not been checked. A message that
    #      has only been listed carries its header block in _raw and nothing
    #      more; uploading that produced the 4 KB, zero-body receipts sitting in
    #      0---Frakt & Kvitto right now. The body is fetched if it is missing,
    #      and if it still cannot be had the delivery is REFUSED — the caller
    #      then leaves the original where it is instead of trashing it.
    #   2. THE COPIES.  Asked and answered once, in a ledger that survives a
    #      restart, and backed up by an account-wide (not folder-wide) look on
    #      the server. A receipt filed on into .../2026-08 is still "already
    #      delivered".
    #   3. THE MESS.  The copy keeps the original's DATE and read state, so it
    #      lands where it belongs in a sorted list instead of pretending to be
    #      new mail that arrived today.
    #
    # Returns (problem, delivered_now): problem is "" on success; delivered_now
    # is False when the message was already there, so nothing is counted or
    # announced twice.

    def _full_raw_for(self, msg) -> bytes:
        """The COMPLETE raw bytes of a message — headers and body — or b"".

        Three places are tried, cheapest first: what the message already
        carries, the on-disk cache, and finally the server. Each is checked
        with _raw_is_headers_only rather than trusted, because the whole class
        of bug this exists to stop came from believing a header-only stub was
        a message."""
        raw = msg.get("_raw")
        if isinstance(raw, str):
            raw = raw.encode("utf-8", "replace")
        if raw and not _raw_is_headers_only(raw):
            return raw

        cached = _cached_raw_for(msg)
        if cached and not _raw_is_headers_only(cached):
            msg["_raw"] = cached                 # keep it for the next caller
            return cached

        acct   = msg.get("account_email", "")
        folder = msg.get("_folder", "")
        uid    = msg.get("uid")
        pwd    = self._secret_for(acct)
        if not (acct and folder and uid and pwd):
            return b""
        try:
            # interactive=False: this runs on the filter dispatcher's own
            # background thread, and must not elbow the UI lane aside.
            built = _fetch_single_full_body(acct, pwd, folder, uid,
                                            interactive=False)
        except Exception as e:
            log.warning("Cross-account delivery: could not fetch the body of "
                        "%s/%s uid %s: %s", acct, folder, uid, e)
            return b""
        if not built:
            return b""
        got = built.get("_raw") or b""
        if isinstance(got, str):
            got = got.encode("utf-8", "replace")
        if not got or _raw_is_headers_only(got):
            return b""
        msg.update(built)          # in place: other windows hold this same dict
        return got

    def _deliver_cross_account(self, msg, target_account, target_folder,
                               flt_id=""):
        """Put ONE message into another account's folder, exactly once, whole.

        See the section header above.

        Returns (problem, delivered_now, verified). `verified` is the one the
        caller must not ignore: it means "an intact copy of this message is in
        the target account right now". Only then may the source be trashed.

        Issu 2026-08-18 — the two-value version made "I skipped this" and "it
        is safely there" indistinguishable, and the cross-account move read
        the empty problem string as success and trashed the source anyway. So
        every receipt he pulled back out of the Trash by hand was thrown
        straight back in, dozens of times, while nothing was ever copied."""
        target_account = (target_account or "").strip()
        target_folder  = (target_folder or "").strip()
        if not (target_account and target_folder):
            return ("a cross-account rule needs both a target account and a "
                    "target folder", False, False)
        tpwd = self._secret_for(target_account)
        if not tpwd:
            return (f"no stored password for {target_account}", False, False)

        mid  = msg.get("_message_id", "")
        subj = msg.get("subject", "") or ""
        src  = msg.get("account_email", "")

        # ── 1. Have we already delivered this one? (free, and it remembers) ──
        # _delivered_heal has already thrown out the rows that pointed at a
        # body-less Trash copy, so anything still here is a real delivery.
        seen = _delivered_already(self._delivered, mid, target_account)
        if seen:
            log.info("cross-account delivery skipped — %r was already "
                     "delivered to %s/%s on %s",
                     subj[:60], target_account, seen.get("folder", ""),
                     seen.get("when", ""))
            return "", False, True

        # ── 2. Ask the target account itself, anywhere in it ─────────────────
        where, intact = _imap_message_id_in_account(
            target_account, tpwd, mid) if mid else ("", True)
        if where and intact:
            # Really there, with contents. Write it down so this question is
            # never asked over the network again — that IS the 144-times-a-week
            # churn. A copy in the target's own Trash counts here on purpose:
            # a whole message you threw away must stay thrown away.
            _delivered_record(self._delivered, mid, target_account, where,
                              subj, src, intact=True)
            log.info("cross-account delivery skipped — %r is already in "
                     "%s (%s)", subj[:60], target_account, where)
            return "", False, True
        if where and not intact:
            # It is "there" and it is EMPTY — one of the hollow copies the old
            # move left behind. That is not a delivery and must never be
            # written down as one, or the real message is locked out for good.
            if _is_discard_folder(where):
                # In the Trash/Spam it is rubbish twice over, and it is also
                # the thing that would make Gmail relabel the shell instead of
                # accepting the real message. Remove it, then carry on and
                # deliver properly. Nothing of value is lost: the envelope is
                # empty and the contents are in this account, whole.
                n, certain = _imap_purge_hollow_copy(target_account, tpwd,
                                                     where, mid)
                if not certain:
                    # We could not find out whether the shell is still there.
                    # Delivering now could make Gmail hang the folder label on
                    # the EMPTY copy instead of accepting this one, and then
                    # the ledger would call the job done. Leave everything
                    # untouched and try again on the next check.
                    log.warning("cross-account delivery POSTPONED for %r: the "
                                "empty copy in %s/%s could not be cleared "
                                "(the account could not be asked). Nothing "
                                "was copied, nothing was removed — the next "
                                "check tries again.",
                                subj[:60], target_account, where)
                    return ("the empty copy already there could not be "
                            "cleared — nothing was changed"), False, False
                log.warning("cross-account delivery: %r had %d empty copy/"
                            "copies in %s/%s — cleared, delivering the real "
                            "message now", subj[:60], n, target_account, where)
            else:
                # An empty copy sitting in a folder he actually files into is
                # not ours to delete on a filter run. Leave it, deliver
                # nothing, and do NOT let the caller trash the source: that
                # source is the only intact copy left.
                log.warning("cross-account delivery REFUSED for %r: the copy "
                            "in %s/%s has NO BODY. The original is being kept "
                            "where it is — repair it with Tools → “Mail with "
                            "no body…”", subj[:60], target_account, where)
                self._activity_log(
                    "filtered", account=src, sender=msg.get("from", ""),
                    subject=subj,
                    detail=f"already in {target_account}/{where}, but that "
                           f"copy has NO BODY (made by an older version). "
                           f"Nothing was copied and the original was LEFT "
                           f"WHERE IT IS — repair it with Tools → “Mail with "
                           f"no body…”, which puts the real message back from "
                           f"this account.")
                return ("the copy already there has no body — the original "
                        "was left alone"), False, False

        # ── 3. The body, or nothing at all ───────────────────────────────────
        raw = self._full_raw_for(msg)
        if not raw:
            log.warning("cross-account delivery REFUSED for %r: only the "
                        "headers could be got, and delivering those would "
                        "leave an empty copy and lose the real message",
                        subj[:60])
            self._activity_log(
                "filtered", account=src, sender=msg.get("from", ""),
                subject=subj,
                detail=f"NOT delivered to {target_account}/{target_folder} — "
                       f"the message body could not be downloaded, so nothing "
                       f"was copied and the original was left where it is. "
                       f"It will be tried again on the next check.")
            return ("the message body could not be downloaded — nothing was "
                    "copied and the original was left alone"), False, False

        # ── 4. Deliver it, keeping its own date and read state ───────────────
        # _imap_append_full, not _imap_append_message: without INTERNALDATE
        # every delivered receipt is stamped "now", so a folder sorted by date
        # shows a year of shipping mail all landing today — and without \Seen
        # a rule that says "mark read" delivers unread mail anyway.
        flags = []
        if not msg.get("unread", False):
            flags.append("\\Seen")
        if msg.get("starred"):
            flags.append("\\Flagged")
        prob = _imap_append_full(target_account, tpwd, target_folder, raw,
                                 flags=flags,
                                 internaldate=msg.get("_dt") or None)
        if prob:
            return prob, False, False
        _delivered_record(self._delivered, mid, target_account, target_folder,
                          subj, src, intact=True)
        log.info("cross-account delivery [rule %s]: %r  %s → %s/%s  "
                 "(%d bytes, body verified)", flt_id or "?", subj[:60],
                 src or "?", target_account, target_folder, len(raw))
        return "", True, True

    def _dispatch_filter_server_actions(self, actions):
        """Carry out the SERVER-side filter actions on a background thread
        (DEL 04y). Each is done at most once per message (deduped optimistically
        so a re-fetch mid-flight can't double it; a failure frees it to retry).
        A trashed message gets a hidden local copy first, so it stays in the
        Deleted folder and can be restored to Gmail even after Gmail's own
        30-day window."""
        todo = []
        blocked = 0

        # ── Protected folders (Issu 2026-08-08) ──────────────────────────────
        # A folder you protected refuses to let anything AUTOMATIC take mail
        # out of it — no move, no trash. This is the one place every
        # server-side filter action passes through, so refusing here covers
        # every rule that exists and every rule added later.
        #
        # It does not stop mail arriving, and it does not stop YOU: a move you
        # make by hand, or a delete you press, both still work. What it stops
        # is exactly what Issu described — mail hopping about on its own
        # after it had already been filed where it belonged.
        #
        # Routed through _split_protected — the SAME function the
        # whole-mailbox sweep uses — instead of a second, separate
        # self._is_protected() check living here. _split_protected's own
        # docstring already claimed this promise was kept in "the filter
        # dispatcher and the whole-mailbox sweep"; until now only the sweep
        # actually called it, so the promise of one implementation was being
        # kept in exactly one of the two places it named (found by a static
        # pass, 2026-08-08).
        mt_groups = {}
        for a in actions:
            if a.get("kind") in ("move", "trash"):
                msg = a.get("msg") or {}
                mt_groups.setdefault(
                    (msg.get("account_email", ""), msg.get("_folder", "")),
                    []).append(msg)
        _, _blocked_groups = _split_protected(mt_groups, self._is_protected)
        blocked_keys = set(_blocked_groups)

        for a in actions:
            msg = a.get("msg") or {}
            if (a.get("kind") in ("move", "trash")
                    and (msg.get("account_email", ""),
                         msg.get("_folder", "")) in blocked_keys):
                blocked += 1
                log.info("Protected folder %r: refused a filter %s of %r",
                         msg.get("_folder", ""), a.get("kind"),
                         msg.get("subject", "")[:60])
                self._activity_log(
                    "protected", account=msg.get("account_email", ""),
                    sender=msg.get("from", ""), subject=msg.get("subject", ""),
                    detail=f"a rule wanted to {a.get('kind')} this out of "
                           f"{msg.get('_folder','')}, but that folder is "
                           f"protected — left where it was")
                continue
            key = (a["fid"], _msg_key(a["msg"]), a["kind"])
            if key in self._filter_action_done:
                continue
            self._filter_action_done.add(key)     # optimistic — freed on failure
            todo.append((key, a))
        if blocked:
            self._flash(f"🔒 {blocked} message(s) stayed put — their folder is "
                        f"protected")
        if not todo:
            return
        # Remember every move destination so it floats to the top of the
        # "Move to folder" picker as a frequent/favourite path (Issu 2026-08-02).
        for _k, a in todo:
            if a.get("kind") == "move" and (a.get("param") or "").strip():
                self._record_move_folder(a["param"])

        # ── Group the work before doing any of it (Issu 2026-08-03) ───────────
        #
        # This used to run one message at a time, and every message meant a new
        # TLS handshake, a new LOGIN, a LIST and a SELECT: his log shows 1–5
        # seconds per message and about ninety seconds to file twenty of them.
        # Actions that go to the same place are now done in ONE batch over ONE
        # connection: (account, source folder, kind, target) is the key, so a
        # rule moving eleven Vinted mails to one label is a single UID MOVE.
        #
        # A CROSS-account move is deliberately left per message: it uploads the
        # raw bytes of that one message to the other account and only then
        # trashes the original, and that pairing must not be batched apart.
        batches, singles = {}, []
        for key, a in todo:
            msg    = a["msg"]
            acct   = msg.get("account_email", "")
            folder = msg.get("_folder", "Inbox")
            kind   = a["kind"]
            tacct  = (a.get("account") or "").strip()
            if kind == "move" and tacct and tacct != acct:
                singles.append((key, a))            # cross-account: one by one
            elif kind in ("move", "trash", "seen", "flag"):
                batches.setdefault(
                    (acct, folder, kind, a.get("param", "") or ""),
                    []).append((key, a))
            else:
                singles.append((key, a))

        def worker():
            removed_ids = []      # moved/trashed → drop from the current view
            seen_flag   = []      # (msg, kind) to reflect locally on success
            moved_where = {}      # destination → how many actually went there

            def _fail(items, why, kind):
                """A whole batch failed: free every key so it can be retried."""
                for key, a in items:
                    self._filter_action_done.discard(key)
                log.warning("filter server action %s failed for %d message(s): "
                            "%s", kind, len(items), why)

            # ── Batched actions ──────────────────────────────────────────────
            #
            # ORDER MATTERS (Issu 2026-08-03: "4 mail olästa trots Mark as read
            # + on Gmail"). A rule that BOTH moves a message AND marks it read
            # queued the move first, so UID MOVE took the message out of the
            # Inbox and the following STORE \Seen hit a UID that was no longer
            # there — the mail landed in the target folder still unread.
            #
            # On Gmail \Seen is a per-MESSAGE flag shared by every label, so
            # setting it while the message is still in the Inbox and THEN moving
            # keeps it read. So: do "seen"/"flag" first, then "move", then
            # "trash".
            _KIND_ORDER = {"seen": 0, "flag": 1, "move": 2, "trash": 3}
            for (acct, folder, kind, param), items in sorted(
                    batches.items(),
                    key=lambda kv: _KIND_ORDER.get(kv[0][2], 9)):
                pwd  = self._secret_for(acct)
                # TWO rules can ask for the very same thing — Issu's log has
                # "Rule for hamta@dhl.com" stored twice, and uid 53846 was
                # moved, then moved again. One uid, one action.
                pairs, seen_uids = [], set()
                for k, a in items:
                    u = a["msg"].get("uid")
                    if not u or u in seen_uids:
                        continue
                    seen_uids.add(u)
                    pairs.append((k, a))
                uids = [a["msg"].get("uid") for _k, a in pairs]
                if not (pwd and uids):
                    for k, _a in items:
                        self._filter_action_done.discard(k)
                    continue
                fname = pairs[0][1].get("fname", "")
                try:
                    if kind == "move":
                        n, probs = _imap_move_uids(acct, pwd, folder, uids,
                                                   param)
                    elif kind == "trash":
                        for _k, a in pairs:
                            try:
                                _deleted_save(a["msg"])   # local copy first
                            except Exception as e:
                                log.warning("filter-trash local copy failed: %s",
                                            e)
                        n, probs = _imap_trash_uids(acct, pwd, folder, uids)
                    elif kind == "seen":
                        prob = _imap_mark_seen(acct, pwd, folder, uids)
                        n, probs = (0, [prob]) if prob else (len(uids), [])
                    else:                                  # "flag"
                        prob = _imap_star_message(acct, pwd, folder, uids)
                        n, probs = (0, [prob]) if prob else (len(uids), [])
                except Exception as e:
                    _fail(items, e, kind)
                    log.error("filter server action %s crashed: %s", kind, e)
                    continue
                if probs and not n:
                    _fail(items, "; ".join(str(p) for p in probs), kind)
                    continue
                for _k, a in pairs:
                    if kind in ("move", "trash"):
                        removed_ids.append(a["msg"].get("id"))
                    else:
                        seen_flag.append((a["msg"], kind))
                if kind in ("move", "trash"):
                    moved_where[param if kind == "move" else ""] = (
                        moved_where.get(param if kind == "move" else "", 0)
                        + len(pairs))
                log.info("filter '%s' %s %d message(s) on Gmail [%s]%s",
                         fname, kind, n, folder,
                         f" → {param}" if param else "")
                for p in probs:
                    log.warning("filter %s: %s", kind, p)

            # ── The ones that really are per message ─────────────────────────
            for key, a in singles:
                msg    = a["msg"]
                acct   = msg.get("account_email", "")
                pwd    = self._secret_for(acct)
                folder = msg.get("_folder", "Inbox")
                uid    = msg.get("uid")
                kind   = a["kind"]
                if not (pwd and uid):
                    self._filter_action_done.discard(key)
                    continue
                try:
                    if kind == "move":
                        # ── CROSS-account move (rewritten Issu 2026-08-16) ────
                        #
                        # Deliver the WHOLE message to the target account, then
                        # — and only then — trash the source. Two things went
                        # wrong here before and both are fixed by _deliver_x:
                        #
                        #   • it uploaded msg["_raw"], which for mail that has
                        #     only ever been LISTED is the header block and
                        #     nothing else. That is where Issu's body-less
                        #     receipts came from, and the source was trashed
                        #     afterwards regardless, so the real message was
                        #     gone.
                        #   • it asked one folder whether the message was
                        #     already there, so a copy filed on into a month
                        #     folder was invisible and a second one was sent.
                        #
                        # If the body cannot be got, nothing is uploaded and
                        # NOTHING IS TRASHED — the mail stays where it is and
                        # the next check tries again. Never trade a real
                        # message for an empty envelope.
                        tacct = (a.get("account") or "").strip()
                        prob, delivered, verified = \
                            self._deliver_cross_account(
                                msg, tacct, a["param"],
                                flt_id=a.get("fid", ""))
                        # `verified`, not "no problem" (Issu 2026-08-18). A
                        # skip returns no problem at all, and reading that as
                        # success is what trashed the source of every receipt
                        # whose ledger row was poisoned — over and over, each
                        # time he restored one by hand.
                        if not prob and verified:
                            tprob = _imap_trash_message(acct, pwd,
                                                        folder, uid)
                            if tprob:
                                log.warning("filter x-acct move: copied "
                                            "but source not removed: %s",
                                            tprob)
                            removed_ids.append(msg.get("id"))
                            if delivered:
                                moved_where[a["param"]] = (
                                    moved_where.get(a["param"], 0) + 1)
                        elif not prob:
                            log.warning("filter x-acct move: %r was NOT "
                                        "confirmed in %s, so the original "
                                        "stays in %s/%s",
                                        (msg.get("subject", "") or "")[:60],
                                        tacct, acct, folder)
                    elif kind == "rescue_copy":
                        # Cross-account rescue straight from Trash (see
                        # action_rescue_trash). Same delivery path, same
                        # once-only promise — and the Trash original is
                        # deliberately left alone: it is already out of the
                        # source account's normal mailbox view, and no filter
                        # action here ever permanently deletes mail.
                        tacct = (a.get("account") or "").strip()
                        prob, delivered, _verified = \
                            self._deliver_cross_account(
                                msg, tacct, a["param"],
                                flt_id=a.get("fid", ""))
                        if not prob and delivered:
                            moved_where[a["param"]] = (
                                moved_where.get(a["param"], 0) + 1)
                    else:
                        prob = "unknown action"
                    if prob:
                        self._filter_action_done.discard(key)   # allow retry
                        log.warning("filter server action %s failed: %s",
                                    kind, prob)
                    else:
                        log.info("filter '%s' %s on Gmail: %s [%s]",
                                 a["fname"], kind,
                                 (msg.get("subject", "") or "")[:60], folder)
                except Exception as e:
                    self._filter_action_done.discard(key)
                    log.error("filter server action %s crashed: %s", kind, e)

            def done():
                for msg, k in seen_flag:
                    if k == "seen" and not msg.get("_always_unread"):
                        msg["unread"] = False
                    elif k == "flag":
                        msg["starred"] = True
                # SAY what happened. A filter move used to be completely
                # silent: the mail left Gmail, the list refilled with older
                # mail (the window is the newest ~40 per folder), and the inbox
                # looked untouched — which is exactly why Issu asked whether it
                # had worked at all (2026-08-03).
                if moved_where:
                    bits = ", ".join(
                        f"{n} → {t}" if t else f"{n} → Trash"
                        for t, n in sorted(moved_where.items(),
                                           key=lambda kv: -kv[1]))
                    self._flash(f"Filters moved {sum(moved_where.values())} "
                                f"message(s) on Gmail: {bits}")
                    # …and it has to be VISIBLE. A destination two levels down
                    # sits inside a folded parent, so the mail left the Inbox
                    # and appeared nowhere you could see. Unfold the path to
                    # every place mail was just filed.
                    # Wrapped: this is cosmetic, and it runs BEFORE the list is
                    # updated below. A sidebar problem must never be the reason
                    # moved mail stays on screen.
                    try:
                        opened = False
                        for t in moved_where:
                            if not t:
                                continue
                            for a in self._accounts:
                                if a.get("virtual"):
                                    continue
                                opened |= self._reveal_folder(a["email"], t,
                                                              redraw=False)
                        if opened:
                            self._populate_sidebar(self.sidebar_inner)
                        # A brand-new label has to appear in the sidebar at
                        # all, or the mail looks like it went nowhere.
                        known = set(self._known_folder_names())
                        if any(t and t not in known for t in moved_where):
                            self._refresh_folder_tree()
                    except Exception as e:
                        log.warning("Could not reveal a move destination: %s", e)
                if removed_ids:
                    # Only touch the SCREEN if the screen actually changed.
                    # Since the scheduled per-account check began running the
                    # rules for accounts that are not on display (Issu
                    # 2026-08-16), most moves happen to mail that was never in
                    # this list — and redrawing then would blank the reading
                    # pane, and the text you had selected in it, while you were
                    # reading something else entirely. Blink-free by default:
                    # no visible change, no redraw.
                    rid = set(removed_ids)
                    before = len(self._messages)
                    self._messages = [m for m in self._messages
                                      if m.get("id") not in rid]
                    self._all_messages = [m for m in self._all_messages
                                          if m.get("id") not in rid]
                    if len(self._messages) != before:
                        self._render_msg_list()
                        # Keep the pane if what you are reading is still here.
                        sel = self._selected_msg
                        if sel is None or sel.get("id") in rid:
                            self._show_reading_pane_empty()
                elif seen_flag:
                    self._render_msg_list()
                self._maybe_refresh_counts(force=True)
            try:
                self.root.after(0, done)
            except Exception:
                pass
        threading.Thread(target=worker, daemon=True).start()

    def _run_filters_now(self):
        """Run every enabled filter over the messages currently loaded —
        including the "only when I run them" rules — apply the results, redraw,
        and report what happened (Issu 2026-08-01: clearing out junk in bulk)."""
        if self._demo_mode:
            self._all_messages = _mock_messages(self._current_folder,
                                                self._current_acct)
        base = list(self._all_messages)
        if not base:
            self._flash("Open a folder first — nothing loaded to filter")
            return
        # Re-evaluate cleanly: drop annotations left by a previous run so a
        # rule that no longer matches doesn't keep a message hidden.
        for m in base:
            for k in ("_filter_hide", "_filter_color", "_filter_notify",
                      "_filter_names"):
                m.pop(k, None)
        self._messages = self._apply_local_state(base, manual=True)
        self._selected_msg = None
        self._search_active = False
        self._apply_sort()
        self._render_msg_list()
        self._show_reading_pane_empty()
        self._repaint_badges()

        # ── Tell the user what actually happened ─────────────────────────────
        matched = sum(1 for m in base if m.get("_filter_names"))
        hidden  = sum(1 for m in base if m.get("_filter_hide"))
        # A waiting rule matched but deliberately did nothing yet (DEL 04z3).
        # Saying "nothing matched" here would be false, and would send him
        # hunting for a broken rule that is working exactly as asked.
        waiting = list(getattr(self, "_filter_waiting", []) or [])
        if matched == 0 and waiting:
            soon = min(waiting, key=lambda w: w.get("left", 0))
            messagebox.showinfo(
                "Nothing to do yet — some rules are waiting",
                f"{len(waiting)} message(s) matched a rule that WAITS before "
                f"acting, so nothing was done to them.\n\n"
                f"The next one is “{(soon['subject'] or '(no subject)')[:60]}” "
                f"— {_human_minutes(soon['left'])} to go"
                + (f", at {soon['at']}." if soon["at"] else ".")
                + "\n\nThey are filed by themselves on a later check; you do "
                  "not have to be looking at the folder.",
                parent=self.root)
            return
        if matched == 0:
            # "Nothing matched" used to be the end of the conversation. Now the
            # run has already been explained rule by rule, so offer to SHOW
            # that instead of leaving Issu to guess (2026-08-03).
            diag = getattr(self, "_filter_diag", None)
            near = sum(r.get("near", 0) for r in (diag or {}).get("rules", []))
            if diag and messagebox.askyesno(
                    "Filters ran — nothing matched",
                    f"{len(base)} message(s) were checked against "
                    f"{diag.get('n_rules', 0)} rule(s) and not one matched"
                    + (f", though {near} came close.\n\n"
                       if near else ".\n\n")
                    + "Show what each rule compared, and where it stopped?",
                    parent=self.root, default="yes"):
                self._filter_diag_dialog()
            else:
                self._flash("Filters ran — nothing matched")
            return
        # Would any enabled rule move/delete on Gmail while Server changes is
        # off? Then those only hid locally — say so, since "get rid of junk"
        # usually means actually removing it on Gmail.
        server_wanted = any(
            _filter_has_server_action(f)
            for f in self._filter_store.get("filters", [])
            if f.get("enabled", True))
        server_off = (server_wanted
                      and not self.cfg.get("allow_server_changes", False)
                      and not self._demo_mode)
        bits = [f"{matched} matched"]
        if hidden:
            bits.append(f"{hidden} hidden from the list")
        if waiting:
            bits.append(f"{len(waiting)} still waiting")
        # Short enough for the 1-second toast; the dialog below can be wordier.
        summary = "Filters ran: " + ", ".join(bits)
        if server_off:
            # Offer to turn Server changes ON right here and re-run, instead of
            # sending Issu off to a menu — this is exactly why "inget flyttas
            # NÅGONSIN" (a move rule with Server changes off does nothing at
            # all: move is not a local action, so the mail neither moves nor
            # hides). Issu 2026-08-02.
            if messagebox.askyesno(
                    "Rules want to move/delete on Gmail — but that's OFF",
                    summary + ", of the mail loaded here.\n\n"
                    "Your rules ask to MOVE or DELETE mail on Gmail, but "
                    "“Server changes” is OFF — so those rules did nothing at "
                    "all (a move is not a local action, so the mail neither "
                    "moved nor hid).\n\n"
                    "Turn Server changes ON now and run the filters again for "
                    "real?", parent=self.root, default="yes"):
                self.cfg["allow_server_changes"] = True
                _save_settings(self.cfg)
                log.info("allow_server_changes enabled from Run filters")
                self._flash("Server changes ON — moving on Gmail…")
                self._run_filters_now()
            return
        else:
            self._flash(summary + (" · moving/deleting on Gmail in the "
                                   "background" if server_wanted else ""))

    # ── Whole-mailbox sweep (Issu 2026-08-01) ─────────────────────────────────
    # ══ DEL 51 — the Mail Relocator ═══════════════════════════════════════
    #
    # Manual only. Nothing in this block is ever called by a fetch, a timer
    # or the filter dispatcher — that separation IS the feature (Issu
    # 2026-08-23: "Detta ska vara separat sak… körs enbart manuellt").

    def open_relocator(self):
        win = getattr(self, "_reloc_win", None)
        if win is not None and win.winfo_exists():
            win.lift()
            win.focus_force()
            return
        self._reloc_win = RelocatorWindow(self)

    def _reloc_accounts_for(self, rule) -> list:
        real = [a for a in self._accounts if not a.get("virtual")]
        want = {w.lower() for w in _reloc_norm(rule)["accounts"]}
        if not want:
            return real
        return [a for a in real if (a.get("email") or "").lower() in want]

    def _reloc_find(self, rule, progress=None) -> tuple:
        """Everything one rule would move. READ-ONLY, and safe to call from a
        worker thread. Returns (messages, notes, problems)."""
        r = _reloc_norm(rule)
        plan = _reloc_plan(r)
        if not plan["ok"]:
            return [], [], [plan["why"]]
        extra = _reloc_extra_terms(r)
        found, notes, problems = [], [], []
        for a in self._reloc_accounts_for(r):
            acct = a.get("email", "")
            pwd = self._secret_for(acct)
            if not pwd:
                problems.append(f"no stored password for {acct}")
                continue
            try:
                msgs, nts = _imap_sweep_search(
                    acct, pwd, plan, r["folders"],
                    per_folder=r["per_folder"] or SWEEP_MAX_PER_FOLDER,
                    progress=progress, extra_terms=extra)
            except Exception as e:
                problems.append(f"{acct}: {e}")
                log.error("Relocator search failed for %s: %s", acct, e)
                continue
            found.extend(msgs)
            notes.extend(f"{acct} · {n}" for n in nts)
        # Gmail keeps ONE message and hangs labels on it, so the same mail
        # comes back from Inbox AND All Mail. Keep the copy from the folder
        # listed first, or the second move would fail on something already
        # gone (the same reasoning as the sweep's).
        order = {n: i for i, n in enumerate(r["folders"])}
        found.sort(key=lambda m: order.get(m.get("_folder", ""), 99))
        keep, seen = [], set()
        for m in found:
            if not _reloc_keep(r, m):
                continue
            # De-dup PER ACCOUNT, never across them: inside one account the
            # same Gmail message really does come back from Inbox and All
            # Mail, but two accounts that both received the same mail hold
            # two separate messages — collapsing those would move one and
            # quietly leave the other behind.
            mid = (m.get("_message_id") or "").strip()
            if mid:
                key = (m.get("account_email", ""), mid)
                if key in seen:
                    continue
                seen.add(key)
            keep.append(m)
        keep.sort(key=lambda m: m.get("_sortkey", 0.0), reverse=True)
        log.info("Relocator '%s': server returned %d, %d to move → %s",
                 r["name"], len(found), len(keep), _reloc_dest_label(r))
        return keep, notes, problems

    def _reloc_confirm_and_move(self, jobs, parent=None, on_done=None,
                                notes=None, problems=None, ask=True):
        """Show what would go, ask once, then move it.

        `jobs` is [(rule, [messages])]. One confirmation for the whole lot,
        with the real numbers and the real destinations in front of him —
        the same shape of promise the whole-mailbox sweep makes."""
        parent = parent or self.root
        jobs = [(r, m) for r, m in jobs if m]
        if not jobs:
            if on_done:
                on_done(0, list(problems or []))
            return
        total = sum(len(m) for _r, m in jobs)

        # Group per rule, and take protected folders out BEFORE asking, so
        # the number he confirms is the number that will really move.
        plans, blocked_total = [], 0
        for rule, msgs in jobs:
            r = _reloc_norm(rule)
            groups = {}
            for m in msgs:
                groups.setdefault((m.get("account_email", ""),
                                   m.get("_folder", "")), []).append(m)
            groups, blocked = _split_protected(groups, self._is_protected)
            blocked_total += sum(len(v) for v in blocked.values())
            if groups:
                plans.append((r, groups))
        movable = sum(len(v) for _r, g in plans for v in g.values())
        if not movable:
            messagebox.showinfo(
                "Mail Relocator",
                f"All {total} match(es) are in folders you have protected, "
                f"so nothing was moved.\n\n🔒 Protection means “nothing "
                f"automatic may move mail out of here”, and the Relocator "
                f"keeps that promise too.", parent=parent)
            if on_done:
                on_done(0, list(problems or []))
            return

        # A rule that DELETES is a different question and must look like one
        # (Issu 2026-08-23: "det kan bli en Relocate som jag kan döpa till
        # Delete"). The count in front of him is the same promise either way.
        trashing = sum(len(v) for r, g in plans for v in g.values()
                       if r["action"] == "trash")
        if ask:
            lines = []
            for r, groups in plans:
                n = sum(len(v) for v in groups.values())
                icon = "🗑" if r["action"] == "trash" else "⤴"
                lines.append(f"  {icon}  {r['name'] or '(unnamed rule)'}"
                             f"\n       {n} message(s)  →  "
                             f"{_reloc_dest_label(r)}")
                for (acct, folder), items in sorted(groups.items()):
                    lines.append(f"          · {len(items)} from {folder} "
                                 f"({acct})")
            head = (f"Delete {movable} message(s)?" if trashing == movable
                    else f"Move or delete {movable} message(s)?" if trashing
                    else f"Move {movable} message(s)?")
            tail = ("\n\nDeleted mail goes to the Gmail Trash, where it stays "
                    "for 30 days and can be put back from any mail program. "
                    "Nothing is erased."
                    if trashing else
                    "\n\nThis is a real move on Gmail. Nothing is deleted.")
            q = (head + "\n\n" + "\n".join(lines[:40])
                 + ("\n  …" if len(lines) > 40 else "")
                 + (f"\n\n🔒 {blocked_total} more are in protected folders "
                    f"and will be left alone." if blocked_total else "")
                 + tail)
            if not messagebox.askyesno("Mail Relocator", q, parent=parent,
                                       default="no"):
                if on_done:
                    on_done(0, list(problems or []))
                return

        if not self.cfg.get("allow_server_changes", False):
            if not messagebox.askyesno(
                    "Server changes are off",
                    "This changes your Gmail account, and that switch "
                    "is currently OFF.\n\nTurn it on now and handle the "
                    f"{movable} message(s)?\n\n"
                    + ("(Deleted mail goes to the Gmail Trash and stays "
                       "there 30 days. Nothing is erased.)" if trashing else
                       "(Mail is moved between labels. Nothing is deleted.)"),
                    parent=parent, default="no"):
                if on_done:
                    on_done(0, list(problems or []))
                return
            self.cfg["allow_server_changes"] = True
            _save_settings(self.cfg)
            log.info("allow_server_changes enabled from the Relocator")

        probs = list(problems or [])

        def worker():
            moved = 0
            for r, groups in plans:
                for (acct, folder), items in groups.items():
                    pwd = self._secret_for(acct)
                    if not pwd:
                        probs.append(f"no stored password for {acct}")
                        continue
                    uids = [m.get("uid") for m in items if m.get("uid")]
                    self._activity_log(
                        "move-try", account=acct, rule=r["name"],
                        detail=f"Relocator: {len(uids)} message(s) "
                               f"{folder} → {_reloc_dest_label(r)}")
                    try:
                        if r["mark_read"] and uids:
                            # Before the move: after it, these uids no longer
                            # exist in the source folder.
                            err = _imap_mark_seen(acct, pwd, folder, uids)
                            if err:
                                probs.append(f"{acct}/{folder}: could not "
                                             f"mark read ({err})")
                        if r["action"] == "trash":
                            n, pr = _imap_trash_uids(acct, pwd, folder, uids)
                            moved += n
                            probs.extend(pr)
                            self._activity_log(
                                "moved", account=acct, rule=r["name"],
                                detail=f"Relocator: deleted {n} message(s) "
                                       f"from {folder}  (Gmail Trash)")
                        elif r["dest_account"]:
                            moved += self._reloc_cross(r, items, probs)
                        else:
                            n, pr = _imap_move_uids(acct, pwd, folder, uids,
                                                    r["dest_folder"])
                            moved += n
                            probs.extend(pr)
                            self._activity_log(
                                "moved", account=acct, rule=r["name"],
                                detail=f"Relocator: {n} message(s) {folder} "
                                       f"→ {r['dest_folder']}")
                    except Exception as e:
                        probs.append(f"{acct}/{folder}: {e}")
                        log.error("Relocator move failed %s/%s: %s",
                                  acct, folder, e)
                        self._activity_log(
                            "move-failed", account=acct, rule=r["name"],
                            detail=f"Relocator: {folder} → "
                                   f"{_reloc_dest_label(r)} — {e}"[:400])

            def done():
                log.info("Relocator moved %d message(s)", moved)
                if moved and plans and plans[0][0]["action"] == "move":
                    # A destination the Relocator really used belongs in the
                    # Move picker's most-used list too (DEL 09i). The Trash
                    # is not a destination anybody picks from a list.
                    self._record_move_folder(plans[0][0]["dest_folder"])
                if probs:
                    messagebox.showwarning(
                        "Mail Relocator",
                        f"{moved} message(s) moved. Some had problems:\n\n"
                        + "\n".join(f"• {p}" for p in probs[:8]),
                        parent=self.root)
                else:
                    self._flash(f"Relocator: {moved} message(s) moved")
                self._refresh_messages()
                self._maybe_refresh_counts(force=True)
                if on_done:
                    on_done(moved, probs)
            try:
                self.root.after(0, done)
            except Exception:
                pass

        threading.Thread(target=worker, daemon=True).start()

    def _reloc_cross(self, rule, msgs, probs) -> int:
        """The cross-account half. Goes through _deliver_cross_account, which
        refuses to upload a header-only copy and will not deliver the same
        message twice — the two faults that cost Issu a folder full of empty
        receipts in August."""
        moved = 0
        for m in msgs:
            prob, delivered, verified = self._deliver_cross_account(
                m, rule["dest_account"], rule["dest_folder"])
            if prob:
                probs.append(f"{(m.get('subject') or '')[:40]}: {prob}")
                continue
            if not verified:
                probs.append(f"{(m.get('subject') or '')[:40]}: could not be "
                             f"verified in {rule['dest_account']} — left "
                             f"where it is")
                continue
            src = m.get("account_email", "")
            spwd = self._secret_for(src)
            if spwd and m.get("uid"):
                tprob = _imap_trash_message(src, spwd,
                                            m.get("_folder", "Inbox"),
                                            m.get("uid"))
                if tprob:
                    probs.append(f"{(m.get('subject') or '')[:40]}: copied, "
                                 f"but the original could not be removed "
                                 f"({tprob})")
            moved += 1
        return moved

    def _sweep_dialog(self):
        """Run ONE rule against the whole mailbox on the server, and offer to
        move everything it matches to the Trash.

        Two clearly separated steps, because the second one is the dangerous
        half: “🔍 Find matches” is a read-only IMAP SEARCH that fills the list
        below with what would go; “🗑 Move all to Trash” asks once, with the
        real number in front of you, and then does it in batches."""
        if self._demo_mode:
            messagebox.showinfo(
                "Clean the whole mailbox",
                "This searches your real mailbox on Gmail, so it needs an "
                "account.\n\nAccounts → Add Gmail account…",
                parent=self.root)
            return

        filters = [f for f in self._filter_store.get("filters", [])
                   if f.get("enabled", True)]
        if not filters:
            messagebox.showinfo(
                "Clean the whole mailbox",
                "You have no enabled mail filters yet.\n\nMake one in "
                "Tools → Mail filters…, or select some junk in the list and "
                "use the “🚫 Junk filter…” button.",
                parent=self.root)
            return

        top = self._dialog_shell("Clean the whole mailbox", 760, 660)

        tk.Label(top,
                 text="A normal filter run only sees the messages already "
                      "downloaded (about forty per folder). This asks Gmail "
                      "itself for EVERYTHING one rule matches — years of it — "
                      "and can then move the whole lot to the Trash, where "
                      "Gmail keeps it for 30 days.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 wraplength=700, justify="left").pack(fill="x", padx=14,
                                                      pady=(6, 8))

        body = tk.Frame(top, bg=C_BG3)
        body.pack(fill="both", expand=True, padx=14)

        # ── Rule ─────────────────────────────────────────────────────────────
        tk.Label(body, text="Rule:", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 9, "bold"), anchor="w").pack(fill="x")
        rwrap = tk.Frame(body, bg=C_BG2)
        rwrap.pack(fill="x", pady=(2, 8))
        rsb = tk.Scrollbar(rwrap, bg=C_BG3, troughcolor=C_BG1)
        rsb.pack(side="right", fill="y")
        rlb = tk.Listbox(rwrap, bg=C_BG2, fg=C_FG, height=5,
                         selectbackground=C_MSG_SEL, selectforeground=C_FG_UNRD,
                         highlightthickness=0, relief="flat", activestyle="none",
                         font=("Segoe UI", 9), exportselection=False,
                         yscrollcommand=rsb.set)
        rsb.configure(command=rlb.yview)
        rlb.pack(side="left", fill="both", expand=True)

        plans = []
        for f in filters:
            plan = _sweep_plan(f)
            plans.append(plan)
            mark = "✔" if plan["ok"] else "✖"
            what = ("Trash" if f.get("action_trash") else
                    "hide/mark only" if not _filter_has_server_action(f)
                    else "move/mark")
            rlb.insert("end", f" {mark}  {f.get('name') or '(unnamed rule)'}"
                              f"      · match {f.get('match_mode', 'all')}"
                              f" · does: {what}"
                              + ("" if plan["ok"] else
                                 f"      — cannot be swept: {plan['why']}"))
        if filters:
            rlb.selection_set(0)

        # ── Folders + account scope ──────────────────────────────────────────
        opts = tk.Frame(body, bg=C_BG3)
        opts.pack(fill="x", pady=(0, 6))
        tk.Label(opts, text="Look in:", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 9, "bold")).pack(side="left")
        fvars = {}
        for name in _SWEEP_FOLDERS:
            v = tk.BooleanVar(value=name in ("Inbox", "Spam"))
            fvars[name] = v
            tk.Checkbutton(opts, text=name, variable=v, bg=C_BG3, fg=C_FG,
                           selectcolor=C_BG2, activebackground=C_BG3,
                           activeforeground=C_FG, font=("Segoe UI", 9),
                           highlightthickness=0).pack(side="left", padx=(8, 0))

        # One-click scopes, so the common cases need no thinking
        # (Issu 2026-08-03: "checkboxar för all / only inbox / …").
        def _scope(which):
            for nm, vv in fvars.items():
                vv.set(which == "all" or (which == "inbox" and nm == "Inbox")
                       or (which == "junk" and nm in ("Inbox", "Spam")))
        for txt, which, tip in (
                ("Inbox only", "inbox", "Search the Inbox and nothing else."),
                ("Inbox + Spam", "junk", "The usual junk clean-out."),
                ("Everything", "all",
                 "Includes All Mail, which holds a copy of nearly everything "
                 "— slow, and it reaches archived mail.")):
            b = tk.Button(opts, text=txt, bg=C_BG2, fg=C_FG_DIM,
                          font=("Segoe UI", 7), relief="flat", cursor="hand2",
                          padx=6, pady=0, command=lambda w=which: _scope(w))
            b.pack(side="left", padx=(6, 0))
            add_tooltip(b, tip)

        # ── How far back (Issu 2026-08-03: "only last 7 days of all") ────────
        # Both limits are real IMAP SEARCH terms (SINCE / BEFORE) against the
        # date the server stored, so they narrow the search itself rather than
        # downloading everything and throwing most of it away.
        agerow = tk.Frame(body, bg=C_BG3)
        agerow.pack(fill="x", pady=(4, 0))
        tk.Label(agerow, text="How far back:", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 9, "bold")).pack(side="left")
        v_age = tk.StringVar(value="all")
        v_days = tk.StringVar(value="7")
        for val, txt in (("all", "everything"),
                         ("newer", "only the last"),
                         ("older", "only older than")):
            tk.Radiobutton(agerow, text=txt, value=val, variable=v_age,
                           bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                           activebackground=C_BG3, activeforeground=C_FG,
                           font=("Segoe UI", 8),
                           highlightthickness=0).pack(side="left", padx=(8, 2))
        sp_days = tk.Spinbox(agerow, from_=1, to=3650, width=5,
                             textvariable=v_days, justify="center",
                             bg=C_BG2, fg=C_FG, buttonbackground=C_BG4,
                             relief="flat", font=("Segoe UI", 9),
                             highlightthickness=0, insertbackground=C_ACCENT,
                             insertofftime=0, insertontime=9999999)
        no_blink(sp_days)
        sp_days.pack(side="left", padx=(4, 2))
        tk.Label(agerow, text="days", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(side="left")
        for txt, n in (("7", 7), ("30", 30), ("365", 365)):
            tk.Button(agerow, text=txt, bg=C_BG2, fg=C_FG_DIM,
                      font=("Segoe UI", 7), relief="flat", cursor="hand2",
                      padx=5, pady=0,
                      command=lambda d=n: v_days.set(str(d))).pack(side="left",
                                                                   padx=1)

        def _age_terms():
            """The SINCE/BEFORE terms for the current choice, and a label."""
            try:
                days = max(1, int(v_days.get().strip() or "7"))
            except ValueError:
                days = 7
            mode = v_age.get()
            if mode == "newer":
                return _sweep_age_terms(newer_days=days), \
                    f"only the last {days} day(s)"
            if mode == "older":
                return _sweep_age_terms(older_days=days), \
                    f"only mail older than {days} day(s)"
            return [], ""

        tk.Label(body,
                 text="“All Mail” holds a copy of nearly everything, Sent "
                      "included — tick it only when a rule really has to reach "
                      "archived mail. The same message found twice is listed "
                      "once. The Trash itself is never swept.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 7, "italic"),
                 anchor="w", wraplength=700,
                 justify="left").pack(fill="x", pady=(2, 0))

        real = [a for a in self._accounts if not a.get("virtual")]
        acct_row = tk.Frame(body, bg=C_BG3)
        acct_row.pack(fill="x", pady=(0, 8))
        tk.Label(acct_row, text="Account:", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 9, "bold")).pack(side="left")
        cur = self._current_acct
        all_label = "All accounts"
        acct_var = tk.StringVar(
            value=all_label if cur == ALL_ACCOUNTS_ID or not real
            else cur)
        choices = [all_label] + [a["email"] for a in real]
        om = tk.OptionMenu(acct_row, acct_var, *choices)
        om.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                     activeforeground=C_FG, highlightthickness=0,
                     relief="flat", font=("Segoe UI", 9), anchor="w")
        om["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                             activeforeground=C_FG)
        om.pack(side="left", padx=8)

        # ── Result list ──────────────────────────────────────────────────────
        tk.Label(body, text="What would go:", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 9, "bold"), anchor="w").pack(fill="x")
        lwrap = tk.Frame(body, bg=C_BG2)
        lwrap.pack(fill="both", expand=True, pady=(2, 6))
        lsb = tk.Scrollbar(lwrap, bg=C_BG3, troughcolor=C_BG1)
        lsb.pack(side="right", fill="y")
        lb = tk.Listbox(lwrap, bg=C_BG2, fg=C_FG,
                        selectbackground=C_MSG_SEL, selectforeground=C_FG_UNRD,
                        highlightthickness=0, relief="flat", activestyle="none",
                        font=("Consolas", 8), exportselection=False,
                        yscrollcommand=lsb.set)
        lsb.configure(command=lb.yview)
        lb.pack(side="left", fill="both", expand=True)

        status = tk.Label(body, text="Pick a rule and press “Find matches”.",
                          bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9),
                          anchor="w", wraplength=700, justify="left")
        status.pack(fill="x", pady=(0, 4))

        found = {"msgs": [], "rule": None, "busy": False}

        def _set_busy(on, text=""):
            found["busy"] = on
            if text:
                status.configure(text=text)
            for b in (btn_find, btn_trash):
                b.configure(state="disabled" if on else "normal")

        def _selected_rule():
            cur_sel = rlb.curselection()
            if not cur_sel:
                messagebox.showinfo("Clean the whole mailbox",
                                    "Pick a rule first.", parent=top)
                return None, None
            i = cur_sel[0]
            return filters[i], plans[i]

        def _targets():
            want = acct_var.get()
            if want == all_label:
                return list(real)
            return [a for a in real if a.get("email") == want]

        # ── Step 1: find (read-only) ─────────────────────────────────────────
        def _find():
            flt, plan = _selected_rule()
            if flt is None:
                return
            if not plan["ok"]:
                messagebox.showinfo(
                    "Cannot sweep this rule",
                    f"“{flt.get('name') or '(unnamed rule)'}” cannot be run "
                    f"over the whole mailbox because {plan['why']}.\n\n"
                    f"Add a From, Subject or Body condition that says what to "
                    f"look FOR, and try again.",
                    parent=top)
                return
            folders = [n for n in _SWEEP_FOLDERS if fvars[n].get()]
            if not folders:
                messagebox.showinfo("Clean the whole mailbox",
                                    "Tick at least one folder to look in.",
                                    parent=top)
                return
            # A rule limited to certain folders ("Only in folders:") can only
            # ever act there — so search there and nowhere else, instead of
            # fetching a pile of messages the rule would then throw away.
            scope = _filter_folders(flt)
            if scope:
                low = {s.lower() for s in scope}
                folders = [n for n in folders if n.lower() in low]
                if not folders:
                    messagebox.showinfo(
                        "Clean the whole mailbox",
                        f"“{flt.get('name') or 'This rule'}” only runs in: "
                        f"{', '.join(scope)}.\n\nTick one of those folders "
                        f"above, or take the folder limit off the rule.",
                        parent=top)
                    return
            targets = _targets()
            if not targets:
                messagebox.showinfo("Clean the whole mailbox",
                                    "No account to search.", parent=top)
                return
            lb.delete(0, "end")
            found["msgs"], found["rule"] = [], flt
            age_terms, age_label = _age_terms()
            _set_busy(True, "Searching Gmail…"
                            + (f"  ({age_label})" if age_label else ""))

            def worker():
                collected, notes, errors = [], [], []
                def _say(text):
                    try:
                        self.root.after(0, lambda t=text:
                                        status.configure(text=t)
                                        if top.winfo_exists() else None)
                    except Exception:
                        pass
                for a in targets:
                    try:
                        pwd = _decrypt_secret(a.get("secret", ""))
                        msgs, nts = _imap_sweep_search(
                            a["email"], pwd, plan, folders, progress=_say,
                            extra_terms=age_terms)
                        collected.extend(msgs)
                        notes.extend(f"{a['email']} · {n}" for n in nts)
                    except Exception as e:
                        errors.append(f"{a['email']}: {e}")
                        log.error("Sweep failed for %s: %s", a["email"], e)

                # Local re-check, so the sweep is never wider than the rule,
                # and drop the messages that must never be auto-trashed.
                # Gmail keeps ONE message under several labels, so the same mail
                # comes back from Inbox AND All Mail: keep the copy from the
                # earliest folder in the list, or the second trash attempt would
                # just fail on a message that is already gone.
                order = {n: i for i, n in enumerate(_SWEEP_FOLDERS)}
                collected.sort(key=lambda m: order.get(m.get("_folder", ""), 99))
                keep, skipped_self, dupes, seen_ids = [], 0, 0, set()
                rechecked = 0          # dropped by the LOCAL re-check
                for m in collected:
                    if not _sweep_keep(flt, m):
                        rechecked += 1
                        if rechecked <= 5:
                            # The five most useful lines in the log when the
                            # sweep "finds nothing": Gmail said yes, we said
                            # no, and here is which condition said no.
                            exp = _filter_explain(flt, m, trigger="manual")
                            log.info("SWEEP dropped by local re-check: %s | %s "
                                     "→ %s",
                                     (m.get("from", "") or "")[:40],
                                     (m.get("subject", "") or "")[:50],
                                     exp["why"] or "conditions did not hold")
                        continue
                    if _is_self_message(m):
                        skipped_self += 1
                        continue
                    mid = (m.get("_message_id") or "").strip()
                    if mid:
                        if mid in seen_ids:
                            dupes += 1
                            continue
                        seen_ids.add(mid)
                    keep.append(m)
                keep.sort(key=lambda m: m.get("_sortkey", 0.0), reverse=True)
                log.info("SWEEP result for rule '%s': server returned %d, "
                         "local re-check dropped %d, self-addressed %d, "
                         "duplicates %d → %d to trash",
                         flt.get("name", ""), len(collected), rechecked,
                         skipped_self, dupes, len(keep))

                def done():
                    if not top.winfo_exists():
                        return
                    found["msgs"] = keep
                    for m in keep[:1500]:
                        lb.insert("end",
                                  f" {m.get('_folder',''):<9} "
                                  f"{(m.get('date','') or '')[:16]:<17}"
                                  f"{(m.get('from','') or '')[:34]:<35}"
                                  f"{(m.get('subject','') or '')[:60]}")
                    if len(keep) > 1500:
                        lb.insert("end", f"   … and {len(keep) - 1500} more")
                    bits = [f"{len(keep)} message(s) match "
                            f"“{flt.get('name') or 'this rule'}”"
                            + (f", {age_label}" if age_label else "")]
                    # Say what happened between "Gmail found N" and "N are
                    # listed" — a silent zero is the thing that made this
                    # feature look broken (Issu 2026-08-03).
                    if collected and not keep:
                        bits.append(f"Gmail returned {len(collected)}, but the "
                                    f"local re-check dropped {rechecked} of "
                                    f"them (IMAP search is always a SUBSTRING "
                                    f"match, so “is” / “begins with” / “ends "
                                    f"with” are re-tested here). Freemail.log "
                                    f"names the condition that said no")
                    elif not collected:
                        bits.append("Gmail found nothing at all for this "
                                    "rule's From / Subject / Body text — check "
                                    "the spelling, and that the ticked folders "
                                    "are the ones the mail is in")
                    elif rechecked:
                        bits.append(f"{rechecked} of Gmail's {len(collected)} "
                                    f"hits were dropped by the local re-check")
                    if skipped_self:
                        bits.append(f"{skipped_self} sent to yourself were "
                                    f"skipped (Gmail keeps one copy for Inbox "
                                    f"and Sent — trashing it removes both)")
                    if dupes:
                        bits.append(f"{dupes} were the same message under "
                                    f"another label")
                    if notes:
                        bits.append(" · ".join(notes))
                    if errors:
                        bits.append("Problems: " + " · ".join(errors))
                    _set_busy(False, ".  ".join(bits))
                    if not keep:
                        lb.insert("end", "   (nothing matched)")
                try:
                    self.root.after(0, done)
                except Exception:
                    pass

            threading.Thread(target=worker, daemon=True).start()

        # ── Step 2: trash (the only part that changes anything) ──────────────
        def _trash():
            msgs = list(found["msgs"])
            flt  = found["rule"]
            if not msgs:
                messagebox.showinfo("Clean the whole mailbox",
                                    "Press “Find matches” first.", parent=top)
                return
            if not self.cfg.get("allow_server_changes", False):
                if not messagebox.askyesno(
                        "Server changes are off",
                        "Moving mail to the Trash changes your Gmail account, "
                        "and that switch is currently OFF.\n\n"
                        "Turn it on now and continue?\n\n"
                        "(Mail goes to the Gmail Trash, where it stays for 30 "
                        "days and can be put back from any mail program. "
                        "Nothing is erased.)",
                        parent=top, default="no"):
                    return
                self.cfg["allow_server_changes"] = True
                _save_settings(self.cfg)
                log.info("allow_server_changes enabled from the mailbox sweep")

            # Group by (account, folder) — one connection per group.
            groups = {}
            for m in msgs:
                groups.setdefault((m.get("account_email", ""),
                                   m.get("_folder", "")), []).append(m)
            where = "\n".join(f"  • {len(v)} in {k[1]}  ({k[0]})"
                              for k, v in sorted(groups.items()))
            if not messagebox.askyesno(
                    "Move to Trash",
                    f"Move {len(msgs)} message(s) to the Gmail Trash?\n\n"
                    f"{where}\n\n"
                    f"Rule: {flt.get('name') or '(unnamed rule)'}\n\n"
                    f"They stay in the Trash for 30 days and can be put back "
                    f"from any mail program. Nothing is erased.\n\n"
                    f"Note: only the headers were downloaded, so no local "
                    f"copies are written for these — getting one back means "
                    f"the Gmail Trash, within those 30 days.",
                    parent=top, default="no"):
                return
            _set_busy(True, f"Moving {len(msgs)} message(s) to the Trash…")

            def worker():
                moved, problems = 0, []
                for (acct, folder), items in groups.items():
                    pwd = self._secret_for(acct)
                    if not pwd:
                        problems.append(f"No stored password for {acct}.")
                        continue
                    try:
                        n, probs = _imap_trash_uids(
                            acct, pwd, folder,
                            [m.get("uid") for m in items])
                        moved += n
                        problems.extend(probs)
                    except Exception as e:
                        problems.append(f"{acct}/{folder}: {e}")
                        log.error("Sweep trash failed %s/%s: %s",
                                  acct, folder, e)

                def done():
                    log.info("Mailbox sweep: %d message(s) trashed by rule '%s'",
                             moved, flt.get("name", ""))
                    if top.winfo_exists():
                        lb.delete(0, "end")
                        found["msgs"] = []
                        _set_busy(False, f"{moved} message(s) moved to the "
                                         f"Trash.")
                    if problems:
                        messagebox.showwarning(
                            "Move to Trash",
                            f"{moved} message(s) were moved, but some had "
                            f"problems:\n\n"
                            + "\n".join(f"• {p}" for p in problems[:8]),
                            parent=self.root)
                    else:
                        self._flash(f"{moved} message(s) moved to the Trash")
                    # The list on screen may now show mail that is gone.
                    self._refresh_messages()
                    self._maybe_refresh_counts(force=True)
                try:
                    self.root.after(0, done)
                except Exception:
                    pass

            threading.Thread(target=worker, daemon=True).start()

        def _bulk(kind):
            """Move, or mark read, everything the search found.

            Shares every safeguard the Trash button has: the real count in
            front of you, a per-folder breakdown, one confirmation, batched
            work over one connection per group, and Server changes required."""
            msgs = list(found.get("msgs") or [])
            flt  = found.get("rule")
            if not msgs or flt is None:
                messagebox.showinfo(
                    "Clean the whole mailbox",
                    "Press “🔍 Find matches” first.", parent=top)
                return
            target = ""
            if kind == "move":
                target = self._pick_target_folder(
                    f"File {len(msgs)} message(s) into…")
                if not target:
                    return
            if not self.cfg.get("allow_server_changes", False):
                if not messagebox.askyesno(
                        "Server changes are off",
                        f"{'Moving' if kind == 'move' else 'Marking'} mail "
                        f"changes your Gmail account, and that switch is "
                        f"currently OFF.\n\nTurn it on now and continue?\n\n"
                        + ("(Mail is moved between labels. Nothing is "
                           "deleted.)" if kind == "move" else
                           "(This only ADDS “read”. It never marks anything "
                           "unread.)"),
                        parent=top, default="no"):
                    return
                self.cfg["allow_server_changes"] = True
                _save_settings(self.cfg)
                log.info("allow_server_changes enabled from the mailbox sweep "
                         "(%s)", kind)

            groups = {}
            for m in msgs:
                groups.setdefault((m.get("account_email", ""),
                                   m.get("_folder", "")), []).append(m)
            # Never move mail out of a protected folder, even in bulk — the
            # same promise the filters make (Issu 2026-08-08). Marking read
            # is not a move and is not blocked by it.
            blocked = {}
            if kind == "move":
                groups, blocked = _split_protected(groups, self._is_protected)
                if blocked and not groups:
                    messagebox.showinfo(
                        "Move",
                        f"Every match is in a folder you have protected "
                        f"({', '.join(sorted(k[1] for k in blocked))}), so "
                        f"nothing was moved.", parent=top)
                    return
            where = "\n".join(f"  • {len(v)} in {k[1]}  ({k[0]})"
                              for k, v in sorted(groups.items()))
            n = sum(len(v) for v in groups.values())
            if kind == "move":
                q = (f"File {n} message(s) into “{target}”?\n\n{where}\n\n"
                     f"Rule: {flt.get('name') or '(unnamed rule)'}\n\n"
                     + (f"🔒 {sum(len(v) for v in blocked.values())} more are "
                        f"in protected folders and will be left alone.\n\n"
                        if blocked else "")
                     + f"This is a real move on Gmail. Nothing is deleted.")
            else:
                q = (f"Mark {n} message(s) as read on Gmail?\n\n{where}\n\n"
                     f"Rule: {flt.get('name') or '(unnamed rule)'}\n\n"
                     f"This only ADDS “read” — it never marks anything unread.")
            if not messagebox.askyesno(
                    "Move" if kind == "move" else "Mark read", q,
                    parent=top, default="no"):
                return
            _set_busy(True, f"{'Filing' if kind == 'move' else 'Marking'} "
                            f"{n} message(s)…")

            def worker():
                did, problems = 0, []
                for (acct, folder), items in groups.items():
                    pwd = self._secret_for(acct)
                    if not pwd:
                        problems.append(f"No stored password for {acct}.")
                        continue
                    uids = [m.get("uid") for m in items if m.get("uid")]
                    try:
                        if kind == "move":
                            c, probs = _imap_move_uids(acct, pwd, folder,
                                                       uids, target)
                            did += c
                            problems.extend(probs)
                        else:
                            err = _imap_mark_seen(acct, pwd, folder, uids)
                            if err:
                                problems.append(f"{acct}/{folder}: {err}")
                            else:
                                did += len(uids)
                    except Exception as e:
                        problems.append(f"{acct}/{folder}: {e}")
                        log.error("Sweep %s failed %s/%s: %s",
                                  kind, acct, folder, e)

                def done():
                    log.info("Mailbox sweep: %s %d message(s) by rule '%s'",
                             kind, did, flt.get("name", ""))
                    self._activity_log(
                        "moved" if kind == "move" else "filtered",
                        rule=flt.get("name", ""),
                        detail=(f"whole-mailbox sweep: filed {did} message(s) "
                                f"into {target}" if kind == "move" else
                                f"whole-mailbox sweep: marked {did} "
                                f"message(s) read"))
                    if top.winfo_exists():
                        lb.delete(0, "end")
                        found["msgs"] = []
                        _set_busy(False, f"{did} message(s) "
                                         f"{'filed' if kind == 'move' else 'marked read'}.")
                    if problems:
                        messagebox.showwarning(
                            "Move" if kind == "move" else "Mark read",
                            f"{did} done, but some had problems:\n\n"
                            + "\n".join(f"• {p}" for p in problems[:8]),
                            parent=self.root)
                    else:
                        self._flash(f"{did} message(s) "
                                    f"{'filed' if kind == 'move' else 'marked read'}")
                    if kind == "move":
                        try:
                            self._reveal_folder(
                                next(iter(groups))[0], target)
                        except Exception:
                            pass
                        self._refresh_folder_tree()
                    self._refresh_messages()
                    self._maybe_refresh_counts(force=True)
                try:
                    self.root.after(0, done)
                except Exception:
                    pass

            threading.Thread(target=worker, daemon=True).start()

        brow = tk.Frame(top, bg=C_BG3)
        brow.pack(pady=10)
        btn_find = tk.Button(brow, text="🔍 Find matches", bg=C_BTN_NEW,
                             fg=C_BTN_FG, font=("Segoe UI", 9, "bold"),
                             relief="flat", cursor="hand2", padx=14, pady=4,
                             command=_find)
        btn_find.pack(side="left", padx=5)
        add_tooltip(btn_find, "Read-only: asks Gmail which messages this rule "
                              "matches, in the ticked folders. Nothing is "
                              "changed.")
        btn_trash = tk.Button(brow, text="🗑 Move all to Trash", bg=C_BTN_DEL,
                              fg=C_BTN_FG, font=("Segoe UI", 9, "bold"),
                              relief="flat", cursor="hand2", padx=14, pady=4,
                              command=_trash)
        btn_trash.pack(side="left", padx=5)
        add_tooltip(btn_trash, "Moves everything listed above to the Gmail "
                               "Trash (30 days, recoverable). Asks first.")
        # ── The other two things you want to do to a whole mailbox ──────────
        # Trashing was the job originally asked for, but it is not the common
        # one. After widening a rule (see Rule health) the backlog needs
        # FILING, not binning — and a newsletter you have stopped reading
        # wants marking read, not deleting. Same search, same batching, same
        # confirmation; only the verb differs.
        btn_move = tk.Button(brow, text="📁 Move all to…", bg="#3a6a8a",
                             fg=C_BTN_FG, font=("Segoe UI", 9, "bold"),
                             relief="flat", cursor="hand2", padx=14, pady=4,
                             command=lambda: _bulk("move"))
        btn_move.pack(side="left", padx=5)
        add_tooltip(btn_move, "File everything listed above into a folder you "
                              "pick — the whole backlog, not just what is "
                              "loaded. Asks first.")
        btn_read = tk.Button(brow, text="● Mark all read", bg=C_BTN_STD,
                             fg=C_BTN_FG, font=("Segoe UI", 9),
                             relief="flat", cursor="hand2", padx=12, pady=4,
                             command=lambda: _bulk("read"))
        btn_read.pack(side="left", padx=5)
        add_tooltip(btn_read, "Adds \\Seen on Gmail to everything listed "
                              "above, so your phone stops showing it as new. "
                              "Never marks anything unread.")
        tk.Button(brow, text="Mail filters…", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=14, pady=4,
                  command=lambda: (top.destroy(), self._filters_dialog())
                  ).pack(side="left", padx=5)
        tk.Button(brow, text="Close", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=14, pady=4, command=top.destroy).pack(side="left", padx=5)
        top.bind("<Return>", lambda e: _find() if not found["busy"] else None)

    def _find_duplicates_dialog(self):
        """A real overview of duplicate deliveries in one folder (and,
        optionally, everything nested under it) of one account — grouped by
        Message-ID, straight from the server.

        Issu 2026-08-15: "kan du se om jag har massvis med dubletter?" after
        the cross-account rescue loop had a chance to copy the same shipping
        receipt into 0---Frakt & Kvitto more than once before it was fixed.
        Neither the activity log nor filters.json is a folder inventory —
        this is the one place that actually asks the mailbox."""
        if self._demo_mode:
            messagebox.showinfo(
                "Find duplicates",
                "This looks at your real mailbox on Gmail, so it needs an "
                "account.\n\nAccounts → Add Gmail account…",
                parent=self.root)
            return

        real = [a for a in self._accounts if not a.get("virtual")]
        if not real:
            messagebox.showinfo("Find duplicates", "No account configured.",
                                parent=self.root)
            return

        top = self._dialog_shell("Find duplicates", 760, 620)
        tk.Label(top,
                 text="Groups every message in a folder — and, if ticked, "
                      "everything nested under it — by Message-ID. Two "
                      "messages with the SAME Message-ID are, by definition, "
                      "the same mail: one genuinely arrived twice, or one is "
                      "a copy this program (or Gmail) made of the other. "
                      "Each copy's SIZE is checked too — a copy under half "
                      "the size of the largest in its group is treated as a "
                      "likely empty/header-only stub and is never kept just "
                      "because of which folder it happens to be in. "
                      "Read-only until you press Trash below.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 wraplength=700, justify="left").pack(fill="x", padx=14,
                                                      pady=(6, 8))

        body = tk.Frame(top, bg=C_BG3)
        body.pack(fill="both", expand=True, padx=14)

        arow = tk.Frame(body, bg=C_BG3); arow.pack(fill="x", pady=(0, 4))
        tk.Label(arow, text="Account:", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 9, "bold")).pack(side="left")
        emails = [a["email"] for a in real]
        acct_var = tk.StringVar(
            value=self._current_acct if self._current_acct in emails
            else emails[0])
        om = tk.OptionMenu(arow, acct_var, *emails)
        om.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                     activeforeground=C_FG, highlightthickness=0,
                     relief="flat", font=("Segoe UI", 9), anchor="w")
        om["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                             activeforeground=C_FG)
        om.pack(side="left", fill="x", expand=True, padx=(4, 0))

        frow = tk.Frame(body, bg=C_BG3); frow.pack(fill="x", pady=(4, 0))
        tk.Label(frow, text="Folder:", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 9, "bold")).pack(side="left")
        e_folder = tk.Entry(frow, bg=C_BG2, fg=C_FG, relief="flat",
                            insertbackground=C_ACCENT, font=("Segoe UI", 10),
                            insertofftime=0, insertontime=9999999)
        no_blink(e_folder)
        e_folder.insert(0, self._current_folder or "")
        e_folder.pack(side="left", fill="x", expand=True, padx=(4, 0))

        v_sub = tk.BooleanVar(value=True)
        tk.Checkbutton(body, text="include everything nested under it "
                                  "(e.g. the month folders under "
                                  "0---Frakt & Kvitto)",
                       variable=v_sub, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9),
                       highlightthickness=0).pack(anchor="w", pady=(2, 6))

        tk.Label(body, text="Duplicates found:", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 9, "bold"), anchor="w").pack(fill="x")
        lwrap = tk.Frame(body, bg=C_BG2)
        lwrap.pack(fill="both", expand=True, pady=(2, 6))
        lsb = tk.Scrollbar(lwrap, bg=C_BG3, troughcolor=C_BG1)
        lsb.pack(side="right", fill="y")
        lb = tk.Listbox(lwrap, bg=C_BG2, fg=C_FG,
                        selectbackground=C_MSG_SEL, selectforeground=C_FG_UNRD,
                        highlightthickness=0, relief="flat", activestyle="none",
                        font=("Consolas", 8), exportselection=False,
                        yscrollcommand=lsb.set)
        lsb.configure(command=lb.yview)
        lb.pack(side="left", fill="both", expand=True)

        status = tk.Label(body, text="Pick an account and folder, then "
                                     "press “Scan”.",
                          bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9),
                          anchor="w", wraplength=700, justify="left")
        status.pack(fill="x", pady=(0, 4))

        state = {"groups": {}, "dupe_ids": [], "account": "", "busy": False,
                 "total_msgs": 0}

        def _set_busy(on, text=""):
            state["busy"] = on
            if text:
                status.configure(text=text)
            for b in (btn_scan, btn_trash, btn_export):
                b.configure(state="disabled" if on else "normal")

        def _refresh_list():
            lb.delete(0, "end")
            for mid in state["dupe_ids"]:
                hits = state["groups"][mid]
                subj = (hits[0]["subject"] or "(no subject)")[:60]
                folders = ", ".join(sorted({h["folder"] for h in hits}))
                sizes = [h.get("size") or 0 for h in hits]
                keep = _pick_duplicate_to_keep(hits)
                # Flag it when the copies are NOT all roughly the same size —
                # that is the empty/stub-body case Issu was right to worry
                # about, worth a second look before trusting the auto-pick.
                warn = " ⚠ sizes differ a lot" if (
                    max(sizes) > 0 and min(sizes) < max(sizes) * 0.5) else ""
                lb.insert("end",
                         f" {len(hits)}×  {subj}   [{folders}]   "
                         f"sizes: {', '.join(f'{s:,}' for s in sizes)}"
                         f"   → keep {keep['folder']}{warn}")

        def _scan():
            acct = acct_var.get()
            folder = e_folder.get().strip()
            if not folder:
                messagebox.showinfo("Find duplicates",
                                    "Type a folder to scan.", parent=top)
                return
            pwd = self._secret_for(acct)
            if not pwd:
                messagebox.showinfo("Find duplicates",
                                    "No saved password for that account.",
                                    parent=top)
                return
            _set_busy(True, f"Scanning {acct} / {folder}"
                            + (" and its subfolders…" if v_sub.get()
                               else "…"))
            lb.delete(0, "end")

            def worker():
                try:
                    groups = _imap_scan_for_duplicates(
                        acct, pwd, folder, include_subfolders=v_sub.get())
                    err = None
                except Exception as e:
                    groups, err = {}, str(e)

                def done():
                    if not top.winfo_exists():
                        return
                    _set_busy(False)
                    if err:
                        status.configure(text=f"Scan failed: {err}")
                        return
                    state["groups"] = groups
                    state["account"] = acct
                    state["total_msgs"] = sum(len(v) for v in groups.values())
                    state["dupe_ids"] = sorted(
                        (mid for mid, hits in groups.items()
                         if len(hits) > 1),
                        key=lambda m: -len(groups[m]))
                    _refresh_list()
                    extra = sum(len(groups[m]) - 1 for m in state["dupe_ids"])
                    if not state["dupe_ids"]:
                        status.configure(
                            text=f"No duplicates — {state['total_msgs']} "
                                 f"message(s) checked, every Message-ID "
                                 f"seen exactly once.")
                    else:
                        status.configure(
                            text=f"{len(state['dupe_ids'])} message(s) have "
                                 f"more than one copy — {extra} extra "
                                 f"cop{'y' if extra == 1 else 'ies'} out of "
                                 f"{state['total_msgs']} checked. Select "
                                 f"“Trash extra copies” to clean them up, or "
                                 f"“Export report…” to save this list first.")
                try:
                    self.root.after(0, done)
                except Exception:
                    pass

            threading.Thread(target=worker, daemon=True).start()

        def _trash_extras():
            if not state["dupe_ids"]:
                messagebox.showinfo("Find duplicates",
                                    "Nothing to trash — scan first.",
                                    parent=top)
                return
            extra = sum(len(state["groups"][m]) - 1
                       for m in state["dupe_ids"])
            risky = sum(
                1 for m in state["dupe_ids"]
                if (lambda s: max(s) > 0 and min(s) < max(s) * 0.5)(
                    [h.get("size") or 0 for h in state["groups"][m]]))
            risky_line = (f"\n\n{risky} of those group(s) are flagged ⚠ in "
                          f"the list — their copies are NOT all roughly the "
                          f"same size, which is exactly what an empty/"
                          f"header-only stub next to a real copy looks "
                          f"like. The larger copy is always the one kept, "
                          f"but it's worth glancing at those specific "
                          f"rows first." if risky else "")
            if not messagebox.askyesno(
                    "Trash extra copies",
                    f"For each of the {len(state['dupe_ids'])} duplicated "
                    f"message(s), ONE copy is kept — never the smallest "
                    f"(an empty/header-only stub is never mistaken for the "
                    f"real thing just because of which folder it's in), "
                    f"and among the real ones, a modern YYYY-MM month "
                    f"folder over an old-style one, then the deepest "
                    f"folder — and the other {extra} "
                    f"cop{'y is' if extra == 1 else 'ies are'} moved to "
                    f"Gmail's Trash, where they keep Gmail's normal 30-day "
                    f"undo window. Nothing is ever permanently deleted "
                    f"here.{risky_line}\n\nProceed?",
                    parent=top, default="no"):
                return
            acct = state["account"]
            pwd = self._secret_for(acct)
            _set_busy(True, "Trashing extra copies…")

            def worker():
                ok, fail = 0, 0
                for mid in state["dupe_ids"]:
                    hits = state["groups"][mid]
                    keep = _pick_duplicate_to_keep(hits)
                    for h in hits:
                        if h is keep:
                            continue
                        try:
                            prob = _imap_trash_message(
                                acct, pwd, h["folder"], h["uid"])
                            if prob:
                                fail += 1
                            else:
                                ok += 1
                        except Exception as e:
                            fail += 1
                            log.warning("Duplicate trash failed: %s", e)

                def done():
                    if top.winfo_exists():
                        _set_busy(
                            False,
                            f"Trashed {ok} extra cop{'y' if ok == 1 else 'ies'}"
                            + (f", {fail} failed" if fail else "") + ".")
                    self._flash(f"Trashed {ok} duplicate message(s)")
                try:
                    self.root.after(0, done)
                except Exception:
                    pass

            threading.Thread(target=worker, daemon=True).start()

        def _export():
            if not state["groups"]:
                messagebox.showinfo("Find duplicates",
                                    "Nothing to export — scan first.",
                                    parent=top)
                return
            from tkinter import filedialog
            path = filedialog.asksaveasfilename(
                parent=top, title="Save duplicate report",
                defaultextension=".txt",
                initialfile=(f"duplicates_{state['account']}_"
                            f"{datetime.now().strftime('%Y-%m-%d_%H%M')}.txt"),
                filetypes=[("Text file", "*.txt"), ("All files", "*.*")])
            if not path:
                return
            try:
                with open(path, "w", encoding="utf-8") as f:
                    f.write(f"Duplicate report — {state['account']} — "
                           f"{datetime.now().strftime('%Y-%m-%d %H:%M')}\n")
                    f.write(f"{len(state['dupe_ids'])} message(s) with more "
                           f"than one copy, out of {state['total_msgs']} "
                           f"checked. '*' marks the copy that would be kept "
                           f"(never the smallest — see _pick_duplicate_to_"
                           f"keep).\n\n")
                    for mid in state["dupe_ids"]:
                        hits = state["groups"][mid]
                        keep = _pick_duplicate_to_keep(hits)
                        f.write(f"{len(hits)}x  {hits[0]['subject']}\n")
                        f.write(f"    Message-ID: {mid}\n")
                        for h in hits:
                            mark = "*" if h is keep else " "
                            f.write(f"  {mark} {h['folder']}  (uid {h['uid']}, "
                                   f"{h.get('size', 0):,} bytes, "
                                   f"{h['date']})\n")
                        f.write("\n")
                self._flash("Duplicate report saved")
            except Exception as e:
                messagebox.showerror("Find duplicates",
                                     f"Could not save the report: {e}",
                                     parent=top)

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(fill="x", padx=14, pady=(0, 10))
        btn_scan = tk.Button(btns, text="🔍 Scan", bg=C_BTN_NEW, fg=C_BTN_FG,
                             font=("Segoe UI", 9), relief="flat",
                             cursor="hand2", padx=14, pady=4, command=_scan)
        btn_scan.pack(side="left", padx=4)
        btn_trash = tk.Button(btns, text="🗑 Trash extra copies", bg=C_BTN_DEL,
                              fg=C_BTN_FG, font=("Segoe UI", 9), relief="flat",
                              cursor="hand2", padx=14, pady=4,
                              command=_trash_extras)
        btn_trash.pack(side="left", padx=4)
        btn_export = tk.Button(btns, text="💾 Export report…", bg=C_BTN_STD,
                               fg=C_BTN_FG, font=("Segoe UI", 9), relief="flat",
                               cursor="hand2", padx=14, pady=4,
                               command=_export)
        btn_export.pack(side="left", padx=4)
        tk.Button(btns, text="Close", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=14, pady=4, command=top.destroy).pack(side="left",
                                                              padx=4)
        top.bind("<Return>", lambda e: _scan() if not state["busy"] else None)

    # ==========================================================================
    # DEL 04z8 — REPAIR MAIL THAT ARRIVED WITHOUT ITS BODY
    # ==========================================================================
    #
    # Issu 2026-08-16: "en del av dem verkar tappa sitt body-innehåll."
    #
    # The cause is fixed (see DEL 04y2 — nothing without a verified body is
    # ever uploaded again), but the empty copies the old code made are still on
    # Gmail: a receipt whose subject and sender are right and whose contents —
    # the tracking number, the label, the amount — are simply not there.
    #
    # This finds them and puts the real message back. Where the intact original
    # can still be found, it is uploaded into the same folder and the empty one
    # goes to the Trash. Where it cannot, the empty copy is LEFT ALONE and
    # listed, because an empty receipt is still better than no receipt and that
    # judgement is not this program's to make quietly.

    def _empty_body_dialog(self):
        """Find (and offer to repair) messages that arrived with no body."""
        if self._demo_mode:
            messagebox.showinfo(
                "Mail with no body",
                "This looks at your real mailbox on Gmail, so it needs an "
                "account.\n\nAccounts → Add Gmail account…",
                parent=self.root)
            return
        real = [a for a in self._accounts if not a.get("virtual")]
        if not real:
            messagebox.showinfo("Mail with no body", "No account configured.",
                                parent=self.root)
            return

        top = self._dialog_shell("Mail with no body", 820, 640)
        tk.Label(top,
                 text="Looks inside every message in a folder (and, if ticked, "
                      "everything nested under it) and finds the ones whose "
                      "BODY is empty — the envelope arrived, the contents did "
                      "not. These were made by an older version of the "
                      "cross-account move, which could upload a message before "
                      "its body had been downloaded. Repair looks for the "
                      "intact original — in this account or in the account the "
                      "copy came from — puts it back in the same folder, and "
                      "moves the empty one to the Trash. Anything that cannot "
                      "be repaired is left exactly as it is. "
                      "Read-only until you press Repair.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 wraplength=760, justify="left").pack(fill="x", padx=14,
                                                      pady=(6, 8))

        body = tk.Frame(top, bg=C_BG3)
        body.pack(fill="both", expand=True, padx=14)

        arow = tk.Frame(body, bg=C_BG3); arow.pack(fill="x", pady=(0, 4))
        tk.Label(arow, text="Account:", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 9, "bold")).pack(side="left")
        emails = [a["email"] for a in real]
        acct_var = tk.StringVar(
            value=self._current_acct if self._current_acct in emails
            else emails[0])
        om = tk.OptionMenu(arow, acct_var, *emails)
        om.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                     activeforeground=C_FG, highlightthickness=0,
                     relief="flat", font=("Segoe UI", 9), anchor="w")
        om["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                             activeforeground=C_FG)
        om.pack(side="left", fill="x", expand=True, padx=(4, 0))

        frow = tk.Frame(body, bg=C_BG3); frow.pack(fill="x", pady=(4, 0))
        tk.Label(frow, text="Folder:", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 9, "bold")).pack(side="left")
        e_folder = tk.Entry(frow, bg=C_BG2, fg=C_FG, relief="flat",
                            insertbackground=C_ACCENT, font=("Segoe UI", 10),
                            insertofftime=0, insertontime=9999999)
        no_blink(e_folder)
        # The folder this whole problem lives in, pre-filled: whatever the
        # shipping rules deliver to, else the folder you have open.
        guess = ""
        for f in (self._filter_store.get("filters", []) or []):
            if (f.get("action_move_account") or "").strip() and \
                    (f.get("action_move") or "").strip():
                guess = f["action_move"].strip()
                break
        e_folder.insert(0, guess or self._current_folder or "")
        e_folder.pack(side="left", fill="x", expand=True, padx=(4, 0))

        v_sub = tk.BooleanVar(value=True)
        tk.Checkbutton(body, text="include everything nested under it "
                                  "(the month folders too)",
                       variable=v_sub, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9),
                       highlightthickness=0).pack(anchor="w", pady=(2, 6))

        tk.Label(body, text="Messages with an empty body:", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 9, "bold"), anchor="w").pack(fill="x")
        lwrap = tk.Frame(body, bg=C_BG2)
        lwrap.pack(fill="both", expand=True, pady=(2, 6))
        lsb = tk.Scrollbar(lwrap, bg=C_BG3, troughcolor=C_BG1)
        lsb.pack(side="right", fill="y")
        lb = tk.Listbox(lwrap, bg=C_BG2, fg=C_FG,
                        selectbackground=C_MSG_SEL, selectforeground=C_FG_UNRD,
                        highlightthickness=0, relief="flat", activestyle="none",
                        font=("Consolas", 8), exportselection=False,
                        yscrollcommand=lsb.set)
        lsb.configure(command=lb.yview)
        lb.pack(side="left", fill="both", expand=True)

        status = tk.Label(body, text="Pick an account and folder, then press "
                                     "“Scan”.",
                          bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9),
                          anchor="w", wraplength=760, justify="left")
        status.pack(fill="x", pady=(0, 4))

        state = {"empties": [], "intact_here": set(), "account": "",
                 "busy": False, "total": 0}

        def _set_busy(on, text=""):
            state["busy"] = on
            if text:
                status.configure(text=text)
            for b in (btn_scan, btn_repair):
                b.configure(state="disabled" if on else "normal")

        def _render():
            lb.delete(0, "end")
            if not state["empties"]:
                lb.insert("end", "  Nothing empty found — every message in "
                                 "these folders has a body.")
                return
            for e in state["empties"]:
                # A duplicate of something intact in the SAME scan needs no
                # download at all: the good copy is already where it belongs.
                dupe = e["message_id"] in state["intact_here"]
                mark = "↺ intact copy is already here" if dupe else \
                       "? original must be found"
                lb.insert("end",
                          f"  {e['size']:>6,}B  {e['folder'][-38:]:<40} "
                          f"{(e['subject'] or '(no subject)')[:44]:<46} {mark}")

        def _scan():
            acct   = acct_var.get()
            folder = e_folder.get().strip()
            if not folder:
                messagebox.showinfo("Mail with no body",
                                    "Type the folder to look in.", parent=top)
                return
            pwd = self._secret_for(acct)
            if not pwd:
                messagebox.showwarning("Mail with no body",
                                       f"No stored password for {acct}.",
                                       parent=top)
                return
            _set_busy(True, "Scanning…")
            sub = bool(v_sub.get())

            def worker():
                rows, err = [], ""
                try:
                    rows = _imap_scan_for_empty_bodies(
                        acct, pwd, folder, include_subfolders=sub,
                        progress=lambda t: self.root.after(
                            0, lambda: status.configure(text=t)))
                except Exception as e:
                    err = str(e)
                    log.error("Empty-body scan failed for %s/%s: %s",
                              acct, folder, e)

                def done():
                    if not top.winfo_exists():
                        return
                    if err:
                        _set_busy(False, f"Could not scan: {err}")
                        return
                    state["account"] = acct
                    state["total"]   = len(rows)
                    state["empties"] = sorted(
                        (r for r in rows if r["empty"]),
                        key=lambda r: (r["folder"], r["subject"]))
                    state["intact_here"] = {
                        r["message_id"] for r in rows
                        if not r["empty"] and r["message_id"]}
                    _render()
                    n = len(state["empties"])
                    _set_busy(
                        False,
                        f"{len(rows)} message(s) checked · {n} with an EMPTY "
                        f"body" + (" — press Repair to put the real messages "
                                   "back." if n else " — nothing to repair."))
                try:
                    self.root.after(0, done)
                except Exception:
                    pass

            threading.Thread(target=worker, daemon=True).start()

        def _repair():
            empties = list(state["empties"])
            if not empties:
                messagebox.showinfo("Mail with no body",
                                    "Scan first — nothing is listed.",
                                    parent=top)
                return
            if not self.cfg.get("allow_server_changes", False):
                messagebox.showwarning(
                    "Server changes are off",
                    "Repairing puts the real message back on Gmail and moves "
                    "the empty copy to the Trash, so it needs "
                    "Tools → Server changes ON.", parent=top)
                return
            acct = state["account"]
            others = [a["email"] for a in self._accounts
                      if not a.get("virtual") and a["email"] != acct]
            if not messagebox.askyesno(
                    "Repair mail with no body",
                    f"Look for the real version of {len(empties)} empty "
                    f"message(s), and where it is found:\n\n"
                    f"  • upload it into the same folder, and\n"
                    f"  • move the empty copy to the Trash.\n\n"
                    f"Searched: {acct}, then "
                    f"{', '.join(others) or '(no other account)'}.\n\n"
                    f"Anything whose real version cannot be found is left "
                    f"completely alone. Nothing is ever erased — empties go "
                    f"to the Trash, exactly like every other delete here.",
                    parent=top, default="no"):
                return
            _set_busy(True, "Repairing…")

            def worker():
                fixed = dropped = stuck = 0
                problems = []
                pwd = self._secret_for(acct)
                for i, e in enumerate(empties, 1):
                    try:
                        self.root.after(0, lambda i=i: status.configure(
                            text=f"Repairing {i}/{len(empties)}…"))
                    except Exception:
                        pass
                    mid = e["message_id"]
                    if not (mid and pwd):
                        stuck += 1
                        continue
                    # 1) An intact copy already sitting in the scanned tree
                    #    makes this one simply redundant — bin it, upload
                    #    nothing.
                    if mid in state["intact_here"]:
                        prob = _imap_trash_message(acct, pwd, e["folder"],
                                                   e["uid"])
                        if prob:
                            problems.append(f"{e['subject'][:40]}: {prob}")
                        else:
                            dropped += 1
                        continue
                    # 2) Otherwise go and find the real message: this account
                    #    first (another label, the Trash), then every other
                    #    account — which is where it usually is, because the
                    #    old move trashed the source after copying.
                    raw, where = _fetch_full_by_message_id(acct, pwd, mid)
                    if not raw:
                        for other in others:
                            opwd = self._secret_for(other)
                            if not opwd:
                                continue
                            raw, where = _fetch_full_by_message_id(other, opwd,
                                                                   mid)
                            if raw:
                                break
                    if not raw:
                        stuck += 1
                        log.info("Empty-body repair: no intact copy of %r "
                                 "anywhere — left it alone",
                                 (e["subject"] or "")[:60])
                        continue
                    # Put the real one in the SAME folder, keeping its own
                    # DATE and marking it read. Both matter: this is old,
                    # filed mail, and without INTERNALDATE a year of repaired
                    # receipts would all claim to have arrived today and every
                    # date sort in that folder would be ruined — which would
                    # be a second mess made while clearing up the first.
                    when = None
                    try:
                        when = parsedate_to_datetime(
                            _email.message_from_bytes(raw).get("Date"))
                    except Exception:
                        when = None
                    prob = _imap_append_full(acct, pwd, e["folder"], raw,
                                             flags=["\\Seen"],
                                             internaldate=when)
                    if prob:
                        problems.append(f"{e['subject'][:40]}: {prob}")
                        continue
                    # PROVE it landed before removing anything. Gmail can
                    # refuse a second message carrying a Message-ID the
                    # account already holds — and the empty copy holds exactly
                    # that one — so an "OK" from APPEND is not evidence. See
                    # _folder_has_intact_copy: no proof, no delete.
                    if not _folder_has_intact_copy(acct, pwd, e["folder"],
                                                   mid):
                        stuck += 1
                        problems.append(
                            f"{e['subject'][:40]}: the server would not store "
                            f"a second copy alongside the empty one, so "
                            f"nothing was changed — the real message is still "
                            f"safe in {where or 'the other account'}")
                        continue
                    prob = _imap_trash_message(acct, pwd, e["folder"], e["uid"])
                    if prob:
                        problems.append(f"{e['subject'][:40]}: the real "
                                        f"message is back, but the empty copy "
                                        f"could not be removed: {prob}")
                    fixed += 1
                    log.info("Empty-body repair: restored %r into %s/%s "
                             "from %s (%d bytes)",
                             (e["subject"] or "")[:60], acct, e["folder"],
                             where, len(raw))

                def done():
                    if not top.winfo_exists():
                        return
                    lb.delete(0, "end")
                    state["empties"] = []
                    _set_busy(False,
                              f"{fixed} repaired · {dropped} empty duplicate(s) "
                              f"binned · {stuck} could not be repaired and were "
                              f"left alone.")
                    self._activity_log(
                        "moved", account=acct,
                        detail=f"empty-body repair: {fixed} message(s) "
                               f"restored, {dropped} empty duplicate(s) "
                               f"trashed, {stuck} left alone")
                    if problems:
                        messagebox.showwarning(
                            "Repair finished with problems",
                            f"{fixed} repaired, but some had trouble:\n\n"
                            + "\n".join(f"• {p}" for p in problems[:8]),
                            parent=top)
                    else:
                        self._flash(f"Repaired {fixed} message(s)")
                    self._maybe_refresh_counts(force=True)
                try:
                    self.root.after(0, done)
                except Exception:
                    pass

            threading.Thread(target=worker, daemon=True).start()

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(fill="x", padx=14, pady=(0, 10))
        btn_scan = tk.Button(btns, text="🔍 Scan", bg=C_BTN_NEW, fg=C_BTN_FG,
                             font=("Segoe UI", 9), relief="flat",
                             cursor="hand2", padx=14, pady=4, command=_scan)
        btn_scan.pack(side="left", padx=4)
        add_tooltip(btn_scan, "Read-only. Fetches the first bytes of each "
                              "message's body to see whether there is one.")
        btn_repair = tk.Button(btns, text="🩹 Repair", bg="#3a6a8a",
                               fg=C_BTN_FG, font=("Segoe UI", 9, "bold"),
                               relief="flat", cursor="hand2", padx=14, pady=4,
                               command=_repair)
        btn_repair.pack(side="left", padx=4)
        add_tooltip(btn_repair, "Puts the real message back where the empty "
                                "copy is, and bins the empty one. Asks first.")
        tk.Button(btns, text="Close", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=14, pady=4, command=top.destroy).pack(side="left",
                                                             padx=4)
        top.bind("<Return>", lambda e: _scan() if not state["busy"] else None)

    # ── Rescue what is stuck in the Trash ────────────────────────────────────
    #
    # Issu 2026-08-18: "jag har massvis av 0---frakt & kvitto-mail i ALL
    # Accounts Trash … varför skickas de inte enligt reglerna, från Trash?"
    #
    # A normal filter run only sees the ~40 newest messages per folder, so
    # eighty receipts spread over three accounts' Trash would take many checks
    # to work through and the oldest would never come up at all — while Gmail's
    # 30-day purge runs the other way. This asks the SERVER for every message
    # the cross-account rules match, in the Trash of every other account, and
    # delivers them properly in one go.
    #
    # It is deliberately additive: the original is left in the Trash exactly
    # where it is. Delivery goes through _deliver_cross_account, so it inherits
    # every promise that path makes — the body is downloaded and verified
    # before anything is uploaded, an empty shell in the target's Trash is
    # cleared out of the way first, and the ledger stops a second copy.

    def _rescue_trash_dialog(self):
        """Find, and deliver, the mail that cross-account rules have left
        stranded in the Trash."""
        if self._demo_mode:
            messagebox.showinfo(
                "Rescue mail from the Trash",
                "This searches your real mailbox on Gmail, so it needs an "
                "account.\n\nAccounts → Add Gmail account…",
                parent=self.root)
            return

        rules = [f for f in (self._filter_store.get("filters", []) or [])
                 if f.get("enabled", True)
                 and (f.get("action_move_account") or "").strip()
                 and (f.get("action_move") or "").strip()]
        if not rules:
            messagebox.showinfo(
                "Rescue mail from the Trash",
                "None of your rules deliver mail to another account, so "
                "there is nothing for this to rescue.",
                parent=self.root)
            return

        top = self._dialog_shell("Rescue mail from the Trash", 860, 620)
        tk.Label(top,
                 text="Your rules that file mail into ANOTHER account can "
                      "leave the original sitting in the Trash. A normal check "
                      "only sees the newest forty messages per folder, so old "
                      "ones never come up again — and Gmail erases the Trash "
                      "after 30 days. This asks Gmail directly for every "
                      "message those rules match, in the Trash of every other "
                      "account, and delivers the ones that never arrived.\n"
                      "Nothing is deleted: the original stays in the Trash, "
                      "and anything already filed is skipped.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 wraplength=800, justify="left").pack(fill="x", padx=14,
                                                      pady=(6, 8))

        body = tk.Frame(top, bg=C_BG3)
        body.pack(fill="both", expand=True, padx=14)

        v_spam = tk.BooleanVar(value=False)
        tk.Checkbutton(body, text="look in Spam as well",
                       variable=v_spam, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9),
                       highlightthickness=0).pack(anchor="w", pady=(0, 6))

        tk.Label(body, text="Stranded in the Trash:", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 9, "bold"), anchor="w").pack(fill="x")
        lwrap = tk.Frame(body, bg=C_BG2)
        lwrap.pack(fill="both", expand=True, pady=(2, 6))
        lsb = tk.Scrollbar(lwrap, bg=C_BG3, troughcolor=C_BG1)
        lsb.pack(side="right", fill="y")
        lb = tk.Listbox(lwrap, bg=C_BG2, fg=C_FG,
                        selectbackground=C_MSG_SEL, selectforeground=C_FG_UNRD,
                        highlightthickness=0, relief="flat", activestyle="none",
                        font=("Consolas", 8), exportselection=False,
                        yscrollcommand=lsb.set)
        lsb.configure(command=lb.yview)
        lb.pack(side="left", fill="both", expand=True)

        status = tk.Label(body, text="Press “🔍 Find them” to look.",
                          bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9),
                          anchor="w", wraplength=800, justify="left")
        status.pack(fill="x", pady=(0, 4))

        state = {"found": [], "busy": False}

        def _set_busy(on, text=""):
            state["busy"] = on
            if text:
                status.configure(text=text)
            for b in (btn_find, btn_go):
                b.configure(state="disabled" if on else "normal")

        def _render():
            lb.delete(0, "end")
            if not state["found"]:
                lb.insert("end", "  Nothing stranded — every message those "
                                 "rules match has been filed.")
                return
            for r in state["found"]:
                m = r["msg"]
                lb.insert("end",
                          f"  {r['rule'][:16]:<18}{m.get('account_email','')[:26]:<28}"
                          f"{m.get('_folder',''):<8}"
                          f"{(m.get('subject') or '(no subject)')[:52]}")

        def _find():
            folders = ["Trash"] + (["Spam"] if v_spam.get() else [])
            _set_busy(True, "Asking Gmail…")

            def worker():
                out, notes = [], []
                for flt in rules:
                    target = (flt.get("action_move_account") or "").strip()
                    plan   = _sweep_plan(flt)
                    if not plan["ok"]:
                        notes.append(f"{flt.get('name','')}: {plan['why']}")
                        continue
                    for a in self._accounts:
                        if a.get("virtual") or a["email"] == target:
                            continue      # never sweep the destination itself
                        pwd = self._secret_for(a["email"])
                        if not pwd:
                            notes.append(f"no stored password for {a['email']}")
                            continue
                        try:
                            msgs, n = _imap_sweep_search(
                                a["email"], pwd, plan, folders,
                                progress=lambda t: self.root.after(
                                    0, lambda t=t: status.configure(text=t)))
                            notes.extend(n)
                        except Exception as e:
                            notes.append(f"{a['email']}: {e}")
                            log.error("Trash rescue search failed for %s: %s",
                                      a["email"], e)
                            continue
                        for m in msgs:
                            if not _sweep_keep(flt, m):
                                continue
                            mid = (m.get("_message_id") or "").strip()
                            if mid and _delivered_already(self._delivered, mid,
                                                          target):
                                continue        # already filed, properly
                            out.append({"msg": m, "flt": flt,
                                        "rule": flt.get("name") or "(unnamed)",
                                        "target": target})
                # One message can match two rules (the Tradera receipts match
                # a Frakt rule twice over); deliver it once.
                seen, uniq = set(), []
                for r in out:
                    k = ((r["msg"].get("_message_id") or "").strip(),
                         r["target"])
                    if k[0] and k in seen:
                        continue
                    seen.add(k)
                    uniq.append(r)

                def done():
                    if not top.winfo_exists():
                        return
                    state["found"] = uniq
                    _render()
                    msg = (f"{len(uniq)} message(s) stranded in the Trash and "
                           f"never filed.")
                    if notes:
                        msg += f"  ({len(notes)} note(s) — see the log.)"
                    for n in notes[:20]:
                        log.info("Trash rescue note: %s", n)
                    _set_busy(False, msg)
                try:
                    self.root.after(0, done)
                except Exception:
                    pass

            threading.Thread(target=worker, daemon=True).start()

        def _rescue():
            rows = list(state["found"])
            if not rows:
                messagebox.showinfo("Rescue mail from the Trash",
                                    "Press “🔍 Find them” first.", parent=top)
                return
            if not self.cfg.get("allow_server_changes", False):
                if not messagebox.askyesno(
                        "Server changes are off",
                        "Delivering mail into your Main account changes it on "
                        "Gmail, and that switch is currently OFF.\n\n"
                        "Turn it on now and continue?\n\n"
                        "(Only ADDS mail. The originals stay in the Trash.)",
                        parent=top, default="no"):
                    return
                self.cfg["allow_server_changes"] = True
                _save_settings(self.cfg)
            where = {}
            for r in rows:
                where[f"{r['target']}/{r['flt'].get('action_move','')}"] = \
                    where.get(f"{r['target']}/{r['flt'].get('action_move','')}",
                              0) + 1
            if not messagebox.askyesno(
                    "Rescue from the Trash",
                    f"Deliver {len(rows)} message(s)?\n\n"
                    + "\n".join(f"  • {n} → {t}" for t, n in
                                sorted(where.items(), key=lambda kv: -kv[1]))
                    + "\n\nThe body of each one is downloaded and checked "
                      "before anything is uploaded — a message whose contents "
                      "cannot be got is skipped, not half-copied.\n\n"
                      "The originals stay in the Trash.",
                    parent=top, default="no"):
                return
            _set_busy(True, f"Delivering {len(rows)} message(s)…")

            def worker():
                ok = skipped = failed = 0
                problems = []
                for i, r in enumerate(rows, 1):
                    try:
                        self.root.after(
                            0, lambda i=i: status.configure(
                                text=f"Delivering {i}/{len(rows)}…"))
                    except Exception:
                        pass
                    try:
                        prob, delivered, _v = self._deliver_cross_account(
                            r["msg"], r["target"],
                            r["flt"].get("action_move", ""),
                            flt_id=r["flt"].get("id", ""))
                    except Exception as e:
                        failed += 1
                        problems.append(str(e))
                        log.error("Trash rescue delivery crashed: %s", e)
                        continue
                    if prob:
                        failed += 1
                        problems.append(
                            f"{(r['msg'].get('subject') or '')[:44]}: {prob}")
                    elif delivered:
                        ok += 1
                    else:
                        skipped += 1

                def done():
                    log.info("Trash rescue: %d delivered, %d already there, "
                             "%d could not be done", ok, skipped, failed)
                    self._activity_log(
                        "moved",
                        detail=f"Trash rescue: {ok} message(s) delivered from "
                               f"the Trash, {skipped} were already filed, "
                               f"{failed} could not be done")
                    if top.winfo_exists():
                        state["found"] = []
                        _render()
                        _set_busy(False,
                                  f"{ok} delivered · {skipped} already there · "
                                  f"{failed} could not be done.")
                    if problems:
                        messagebox.showwarning(
                            "Rescue from the Trash",
                            f"{ok} message(s) were delivered, but some had "
                            f"problems:\n\n"
                            + "\n".join(f"• {p}" for p in problems[:8]),
                            parent=self.root)
                    else:
                        self._flash(f"Rescued {ok} message(s) from the Trash")
                    self._maybe_refresh_counts(force=True)
                try:
                    self.root.after(0, done)
                except Exception:
                    pass

            threading.Thread(target=worker, daemon=True).start()

        brow = tk.Frame(top, bg=C_BG3)
        brow.pack(fill="x", padx=14, pady=(0, 12))
        btn_find = tk.Button(brow, text="🔍 Find them", bg=C_BG4, fg=C_FG,
                             font=("Segoe UI", 9, "bold"), relief="flat",
                             cursor="hand2", padx=14, pady=4, command=_find)
        btn_find.pack(side="left", padx=4)
        btn_go = tk.Button(brow, text="📥 Deliver them", bg=C_BG4, fg=C_FG,
                           font=("Segoe UI", 9, "bold"), relief="flat",
                           cursor="hand2", padx=14, pady=4, command=_rescue)
        btn_go.pack(side="left", padx=4)
        tk.Button(brow, text="Close", bg=C_BG2, fg=C_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=14, pady=4, command=top.destroy).pack(side="left",
                                                             padx=4)
        _render()

    def _delivered_dialog(self):
        """What this program has delivered from one account to another, and
        the one place to UNDO that memory (DEL 04y2).

        The ledger is what stops the same shipping receipt being copied into
        the Main account over and over while the source sits in Trash still
        matching its rule. That is exactly what you want — until the day you
        delete a delivered message on purpose and then want the rule to bring
        it again. Forgetting one line here is how you say so; nothing else in
        the program can override the ledger, which is the point of it."""
        store = self._delivered.get("delivered") or {}
        top = self._dialog_shell("Cross-account delivery log", 860, 560)
        tk.Label(top,
                 text="Every message a rule has copied from one of your "
                      "accounts into another, and when. This list is what "
                      "guarantees the same message is never delivered twice — "
                      "even after a restart, and even while the original sits "
                      "in the source account's Trash matching its rule on "
                      "every check. Forget a line only if you have deleted "
                      "the delivered copy and want the rule to send it again.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 wraplength=800, justify="left").pack(fill="x", padx=14,
                                                      pady=(6, 8))

        wrap = tk.Frame(top, bg=C_BG2)
        wrap.pack(fill="both", expand=True, padx=14, pady=(0, 6))
        sb = tk.Scrollbar(wrap, bg=C_BG3, troughcolor=C_BG1)
        sb.pack(side="right", fill="y")
        lb = tk.Listbox(wrap, bg=C_BG2, fg=C_FG, selectbackground=C_MSG_SEL,
                        selectforeground=C_FG_UNRD, highlightthickness=0,
                        relief="flat", activestyle="none", font=("Consolas", 8),
                        exportselection=False, selectmode="extended",
                        yscrollcommand=sb.set)
        sb.configure(command=lb.yview)
        lb.pack(side="left", fill="both", expand=True)

        status = tk.Label(top, text="", bg=C_BG3, fg=C_FG_DIM,
                          font=("Segoe UI", 9), anchor="w")
        status.pack(fill="x", padx=14)

        rows = []          # ledger keys, in the same order as the listbox

        def _render():
            lb.delete(0, "end")
            rows.clear()
            items = sorted(store.items(),
                           key=lambda kv: kv[1].get("when", ""), reverse=True)
            for key, rec in items:
                rows.append(key)
                lb.insert("end",
                          f" {rec.get('when','')[:16]}  "
                          f"{(rec.get('source') or '?')[:24]:<25} → "
                          f"{(rec.get('account') or '')[:24]:<25} "
                          f"{(rec.get('folder') or '')[-30:]:<32} "
                          f"{(rec.get('subject') or '')[:44]}")
            if not items:
                lb.insert("end", "  Nothing has been delivered across "
                                 "accounts yet.")
            status.configure(text=f"{len(items)} delivery(ies) remembered.")

        def _forget():
            picks = [rows[i] for i in lb.curselection() if i < len(rows)]
            if not picks:
                messagebox.showinfo("Cross-account delivery log",
                                    "Select one or more lines first.",
                                    parent=top)
                return
            if not messagebox.askyesno(
                    "Forget these deliveries?",
                    f"Forget {len(picks)} remembered delivery(ies)?\n\n"
                    f"Nothing on Gmail changes. The only effect is that the "
                    f"rules may deliver those messages again the next time "
                    f"they match — which is what you want if you deleted the "
                    f"delivered copy and would like it back.",
                    parent=top, default="no"):
                return
            for k in picks:
                store.pop(k, None)
            _save_delivered(self._delivered)
            _render()
            self._flash(f"Forgot {len(picks)} delivery(ies)")

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(fill="x", padx=14, pady=(4, 10))
        b_forget = tk.Button(btns, text="Forget selected", bg=C_BTN_DEL,
                             fg=C_BTN_FG, font=("Segoe UI", 9), relief="flat",
                             cursor="hand2", padx=14, pady=4, command=_forget)
        b_forget.pack(side="left", padx=4)
        add_tooltip(b_forget, "Only forgets that it happened — no mail is "
                              "touched on any server.")
        tk.Button(btns, text="Close", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=14, pady=4, command=top.destroy).pack(side="left",
                                                             padx=4)
        _render()

    # ==========================================================================
    # DEL 04t3 — THE HIDE-BOILERPLATE EDITOR
    # ==========================================================================
    #
    # One window: the rules on the left, the rule you picked on the right, and
    # a LIVE PREVIEW of the message currently open in the reading pane at the
    # bottom. The preview is the part that matters — a hiding rule you cannot
    # see the effect of is a rule you will not trust, and the honest worry with
    # anything that hides text is "what did it take that I wanted?".

    def _trim_rules_dialog(self, focus_name: str = ""):
        """Edit the standing "always hide this" rules (DEL 04t2)."""
        top = self._dialog_shell("Hide boilerplate in messages", 900, 700)
        tk.Label(top,
                 text="Text that arrives in EVERY message from a sender — "
                      "standard paragraphs, footers, legal notes — folded away "
                      "on sight. This only changes what is SHOWN: the message "
                      "itself is untouched, replies still quote the full text, "
                      "and nothing is ever changed on the server. Every folded "
                      "block leaves a marker you can click to see it again.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 wraplength=840, justify="left").pack(fill="x", padx=14,
                                                      pady=(6, 8))

        body = tk.Frame(top, bg=C_BG3)
        body.pack(fill="both", expand=True, padx=14)

        left = tk.Frame(body, bg=C_BG3)
        left.pack(side="left", fill="y")
        tk.Label(left, text="Rules", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 9, "bold"), anchor="w").pack(fill="x")
        lb = self._listbox(left, width=34)
        lb.pack(fill="y", expand=True, pady=(2, 4))

        right = tk.Frame(body, bg=C_BG3)
        right.pack(side="left", fill="both", expand=True, padx=(12, 0))

        v_name = tk.StringVar(); v_from = tk.StringVar()
        v_subj = tk.StringVar(); v_kind = tk.StringVar(value="line")
        v_end  = tk.StringVar()
        v_on   = tk.BooleanVar(value=True); v_rx = tk.BooleanVar(value=False)

        def _row(label, var, hint=""):
            r = tk.Frame(right, bg=C_BG3); r.pack(fill="x", pady=2)
            tk.Label(r, text=label, bg=C_BG3, fg=C_FG_DIM, width=16,
                     anchor="e", font=("Segoe UI", 9)).pack(side="left")
            e = tk.Entry(r, textvariable=var, bg=C_BG2, fg=C_FG, relief="flat",
                         insertbackground=C_ACCENT, font=("Segoe UI", 10),
                         insertofftime=0, insertontime=9999999)
            no_blink(e)
            e.pack(side="left", fill="x", expand=True, ipady=3)
            if hint:
                tk.Label(right, text=hint, bg=C_BG3, fg=C_FG_DIM,
                         font=("Segoe UI", 7, "italic"), anchor="w",
                         justify="left", wraplength=470).pack(fill="x",
                                                              padx=(120, 0))
            return e
        _row("Name:", v_name)
        _row("Only from sender:", v_from,
             "part of the address — e.g. boardgamegeek.com. Empty = every sender.")
        _row("Only if subject has:", v_subj, "empty = any subject")

        krow = tk.Frame(right, bg=C_BG3); krow.pack(fill="x", pady=(6, 0))
        tk.Label(krow, text="What to hide:", bg=C_BG3, fg=C_FG_DIM, width=16,
                 anchor="e", font=("Segoe UI", 9)).pack(side="left")
        for lbl, val in (("whole lines", "line"), ("a block", "block"),
                         ("to the end", "tail"), ("just the text", "strip"),
                         ("nothing under it", "orphan")):
            tk.Radiobutton(krow, text=lbl, value=val, variable=v_kind,
                           bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                           activebackground=C_BG3, activeforeground=C_FG,
                           font=("Segoe UI", 8),
                           highlightthickness=0).pack(side="left")
        tk.Label(right,
                 text="whole lines = fold every line that contains a pattern "
                      "(the safe one, and what the built-ins use) · a block = "
                      "from a matching line down to the “ends with” line · to "
                      "the end = everything from the match onwards (careful: "
                      "real content often follows boilerplate) · just the text "
                      "= remove only what matches, keep the rest of the line · "
                      "nothing under it = fold the matching line ONLY when "
                      "every line below it is empty (for a “… wrote:” over a "
                      "quote that never arrived).\n"
                      "No rule may hide a line carrying a link unless its own "
                      "patterns mention one — switch that off in "
                      "Tools → Reading if you really want to.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 7, "italic"),
                 anchor="w", justify="left", wraplength=470).pack(
                     fill="x", padx=(120, 0), pady=(0, 4))
        _row("Block ends with:", v_end, "only used by “a block”")

        crow = tk.Frame(right, bg=C_BG3); crow.pack(fill="x", pady=(4, 0))
        tk.Checkbutton(crow, text="rule is on", variable=v_on, bg=C_BG3,
                       fg=C_FG, selectcolor=C_BG2, activebackground=C_BG3,
                       activeforeground=C_FG, font=("Segoe UI", 9),
                       highlightthickness=0).pack(side="left")
        tk.Checkbutton(crow, text="patterns are regular expressions",
                       variable=v_rx, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9),
                       highlightthickness=0).pack(side="left", padx=(12, 0))

        tk.Label(right, text="Text to hide — ONE PATTERN PER LINE:",
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 9, "bold"),
                 anchor="w").pack(fill="x", pady=(8, 2))
        pat = tk.Text(right, height=7, bg=C_BG2, fg=C_FG, relief="flat",
                      font=("Consolas", 9), padx=6, pady=4, wrap="none",
                      insertbackground=C_ACCENT,
                      insertofftime=0, insertontime=9999999)
        no_blink(pat)
        pat.pack(fill="both", expand=True)

        # ── Live preview against the message you have open ──────────────────
        tk.Label(top, text="Preview — the message open in the reading pane:",
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 9, "bold"),
                 anchor="w").pack(fill="x", padx=14, pady=(8, 2))
        pv = tk.Text(top, height=8, bg=C_BG2, fg=C_FG, relief="flat",
                     font=("Consolas", 8), padx=8, pady=4, wrap="none",
                     insertofftime=0, insertontime=9999999)
        no_blink(pv)
        pv.pack(fill="both", expand=True, padx=14)
        pv.tag_configure("cut", foreground="#e06c75")
        pv.tag_configure("keep", foreground=C_FG)

        rules = self._trim_store.setdefault("rules", [])
        state = {"i": -1}

        def _collect() -> dict:
            return {
                "name": v_name.get().strip() or "(unnamed)",
                "from_contains": v_from.get().strip(),
                "subject_contains": v_subj.get().strip(),
                "kind": v_kind.get(), "end_pattern": v_end.get().strip(),
                "enabled": bool(v_on.get()), "regex": bool(v_rx.get()),
                "patterns": [p for p in pat.get("1.0", "end-1c").splitlines()
                             if p.strip()],
            }

        def _refresh_preview(*_a):
            pv.delete("1.0", "end")
            msg = self._selected_msg
            if not msg or not (msg.get("body") or "").strip():
                pv.insert("end", "  Open a message in the reading pane to see "
                                 "what these rules would hide.")
                return
            # The rule being edited RIGHT NOW, plus every other saved rule, so
            # the preview is what you would actually see.
            live = [dict(r) for i, r in enumerate(rules) if i != state["i"]]
            if state["i"] >= 0 or any(_collect()["patterns"]):
                cur = dict(_TRIM_DEFAULTS); cur.update(_collect())
                cur["id"] = "preview"
                live.append(cur)
            parts, labels, silent = _trim_hidden_parts(
                msg["body"], live, msg,
                keep_links=self.cfg.get("trim_keep_links", True))
            for kind, val in _segment_body(msg["body"], parts):
                if kind == "text":
                    pv.insert("end", val, "keep")
                elif val in silent:
                    # Shown in the PREVIEW even though the real pane drops it
                    # silently: this window exists to answer "what is it
                    # taking?", so nothing may disappear here without a word.
                    pv.insert("end", "·", "cut")
                else:
                    pv.insert("end", f"⟨hidden: {labels.get(val,'?')}⟩", "cut")
            pv.see("1.0")

        def _fill(i):
            state["i"] = i
            r = rules[i] if 0 <= i < len(rules) else dict(_TRIM_DEFAULTS)
            v_name.set(r.get("name", "")); v_from.set(r.get("from_contains", ""))
            v_subj.set(r.get("subject_contains", "")); v_kind.set(r.get("kind", "line"))
            v_end.set(r.get("end_pattern", "")); v_on.set(r.get("enabled", True))
            v_rx.set(bool(r.get("regex")))
            pat.delete("1.0", "end")
            pat.insert("1.0", "\n".join(r.get("patterns", []) or []))
            _refresh_preview()

        def _refresh_list(select=None):
            lb.delete(0, "end")
            for r in rules:
                mark = "  " if r.get("enabled", True) else "✖ "
                scope = r.get("from_contains") or "all senders"
                lb.insert("end", f"{mark}{(r.get('name') or '(unnamed)')[:26]}"
                                 f"  · {scope[:14]}")
            if select is not None and 0 <= select < len(rules):
                lb.selection_clear(0, "end"); lb.selection_set(select)
                lb.see(select); _fill(select)

        lb.bind("<<ListboxSelect>>",
                lambda e: (_fill(lb.curselection()[0])
                           if lb.curselection() else None))
        pat.bind("<KeyRelease>", _refresh_preview)
        for v in (v_from, v_subj, v_kind, v_end, v_rx, v_on):
            v.trace_add("write", _refresh_preview)

        def _save():
            rec = dict(_TRIM_DEFAULTS)
            if 0 <= state["i"] < len(rules):
                rec.update(rules[state["i"]])
            rec.update(_collect())
            if not rec["patterns"]:
                messagebox.showinfo("Hide boilerplate",
                                    "Type at least one line of text to hide.",
                                    parent=top)
                return
            if rec["regex"]:
                for p in rec["patterns"]:
                    try:
                        _re.compile(p)
                    except _re.error as e:
                        messagebox.showwarning(
                            "That is not a valid regular expression",
                            f"“{p}”\n\n{e}\n\nFix it, or untick “patterns are "
                            f"regular expressions”.", parent=top)
                        return
            if 0 <= state["i"] < len(rules):
                rules[state["i"]] = rec
                sel = state["i"]
            else:
                rec["id"] = _new_id(); rec["builtin"] = False
                rules.append(rec); sel = len(rules) - 1
            _save_trim_rules(self._trim_store)
            _refresh_list(sel)
            self._flash("Hide rule saved")
            if self._selected_msg:
                self._show_message_in_reading_pane(self._selected_msg)

        def _new():
            state["i"] = -1
            v_name.set(""); v_from.set(""); v_subj.set(""); v_kind.set("line")
            v_end.set(""); v_on.set(True); v_rx.set(False)
            pat.delete("1.0", "end")
            lb.selection_clear(0, "end")
            _refresh_preview()

        def _delete():
            i = state["i"]
            if not (0 <= i < len(rules)):
                return
            if not messagebox.askyesno(
                    "Delete this rule?",
                    f"Delete “{rules[i].get('name','')}”?\n\n"
                    f"Nothing in any message changes — text this rule was "
                    f"folding simply becomes visible again.",
                    parent=top, default="no"):
                return
            rules.pop(i)
            _save_trim_rules(self._trim_store)
            _new(); _refresh_list()
            if self._selected_msg:
                self._show_message_in_reading_pane(self._selected_msg)

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(fill="x", padx=14, pady=(8, 10))
        for text, colour, cmd in (
                ("💾 Save rule", C_BTN_NEW, _save),
                ("✚ New rule", C_BTN_STD, _new),
                ("🗑 Delete", C_BTN_DEL, _delete),
                ("Close", C_BTN_STD, top.destroy)):
            tk.Button(btns, text=text, bg=colour, fg=C_BTN_FG,
                      font=("Segoe UI", 9), relief="flat", cursor="hand2",
                      padx=14, pady=4, command=cmd).pack(side="left", padx=4)

        _refresh_list()
        # Opened from a folded block's right-click → land on that rule.
        if focus_name:
            for i, r in enumerate(rules):
                if r.get("name") == focus_name:
                    _refresh_list(i)
                    break
        elif rules:
            _refresh_list(0)
        else:
            _new()

    def _run_filters_on(self, msgs, trigger, rescue_only=False):
        """Run the rules that opted into a specific trigger (DEL 04z2) —
        "archive" (a message archived out of the inbox) or "sent" (a message
        just delivered) — over messages that are NOT the on-screen list.

        Applies local actions to each dict, dispatches any Gmail server actions
        (gated by "Server changes" exactly like every other filter action, so
        no new risk), logs to the Filter log + Freemail.log, and honours snooze.
        It never redraws the message list — those messages already left it."""
        if not msgs or self._demo_mode:
            return
        try:
            stats = _apply_filters(
                msgs, self._filter_store, self._tag_store, trigger=trigger,
                allow_server=self.cfg.get("allow_server_changes", False),
                rescue_only=rescue_only)
        except Exception as e:
            log.error("Filter run (%s) failed: %s", trigger, e)
            return
        if stats.get("server_actions"):
            self._dispatch_filter_server_actions(stats["server_actions"])
        for ev in stats.get("events", []):
            token = (ev["fid"], ev["key"], ev["actions"])
            if token in self._filter_log_seen:
                continue
            self._filter_log_seen.add(token)
            ev = dict(ev, when=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
            self._filter_log.append(ev)
            log.info("filter '%s' [%s] → %s : %s", ev["fname"], trigger,
                     ev["actions"], ev["subject"][:60])
            self._log_filter_events([ev], trigger=trigger)
            self._bump_rule_stats([ev])
        if len(self._filter_log) > 500:
            self._filter_log = self._filter_log[-500:]
        for msg, mins in stats.get("snoozed", []):
            self._snooze_message(msg, datetime.now() + timedelta(minutes=mins),
                                 quiet=True)
        self._handle_filter_unsubs(stats)

    # ── Activity log (Issu 2026-08-08) ──────────────────────────────────────
    def _activity_log(self, kind, account="", sender="", subject="",
                      detail="", rule=""):
        """Record one thing that happened, in plain words, on disk.

        Called from the filter runs, the send path, deletes and moves. Kept
        deliberately cheap and never allowed to raise: a logging problem must
        not stop mail from being handled."""
        try:
            _activity_add(self._activity_store, kind, account=account,
                          sender=sender, subject=subject, detail=detail,
                          rule=rule)
            _save_activity(self._activity_store)
        except Exception as e:
            log.debug("activity log write failed: %s", e)

    def _bump_rule_stats(self, events):
        """Count what each rule actually did, on disk. One line per rule; the
        Rule health window reads it."""
        if not events:
            return
        try:
            for ev in events:
                _rule_stat_bump(self._rule_stats, ev.get("fid", ""),
                                ev.get("fname", ""))
            _save_rule_stats(self._rule_stats)
        except Exception as e:
            log.debug("rule stats write failed: %s", e)

    def _log_filter_events(self, events, trigger=""):
        """Mirror a filter run's events into the on-disk activity log.

        This is the answer to "mailet försvann — vart tog det vägen?": every
        rule that touched a message leaves a line saying which account it came
        into, which rule fired, and exactly what the rule did with it."""
        for ev in events:
            actions = ev.get("actions", "")
            detail  = actions
            if trigger:
                detail = f"{actions}  (trigger: {trigger})"
            self._activity_log(
                "filtered",
                account=ev.get("account", "") or ev.get("folder", ""),
                sender=ev.get("sender", ""),
                subject=ev.get("subject", ""),
                rule=ev.get("fname", ""),
                detail=detail)

    def _snooze_message(self, msg, until, quiet=False):
        """"Snooze" no longer hides anything (Issu 2026-11-24): the mail stays
        exactly where it is and, at `until`, a pop-up tells you to deal with it.
        Technically it is a one-shot follow-up of kind "snooze", so it lives in
        followups.json, shows in the Follow-ups folder with a 🔔 in the list,
        and fires from the same always-on ticker (catching up if the program
        was closed at the time)."""
        key = msg.get("_key_override") or _msg_key(msg)
        store = self._followup_store
        # One reminder of this kind per mail: a new date replaces the old one.
        store["items"] = [i for i in store.get("items", [])
                          if not (i.get("key") == key
                                  and i.get("kind") == "snooze"
                                  and not i.get("done"))]
        item = _followup_new(msg, until, kind="snooze")
        item["key"] = key
        store["items"].append(item)
        _save_followups(store)
        if not quiet:
            self._flash(f"You will be notified {until.strftime('%Y-%m-%d %H:%M')}")
            self._followups_changed()

    def _unsnooze(self, key):
        self._snooze_store["snoozed"] = [
            s for s in self._snooze_store.get("snoozed", [])
            if s.get("key") != key]
        _save_snooze(self._snooze_store)

    def _migrate_old_snoozes(self):
        """Mail hidden by the OLD snooze (snooze.json) becomes a reminder: it
        is visible again at once and you are notified at the old time."""
        old = list(self._snooze_store.get("snoozed", []))
        if not old:
            return False
        now = datetime.now()
        for s in old:
            until = _parse_iso(s.get("until", "")) or now
            item = _followup_new(
                {"account_email": s.get("account", ""),
                 "_folder": s.get("folder", "") or "Inbox",
                 "subject": s.get("subject", ""),
                 "from": s.get("from", ""), "from_name": s.get("from", "")},
                max(until, now), kind="snooze")
            item["key"] = s.get("key", "")
            if item["key"]:
                self._followup_store.setdefault("items", []).append(item)
        _save_followups(self._followup_store)
        self._snooze_store["snoozed"] = []
        _save_snooze(self._snooze_store)
        return True

    def _check_snooze_due(self):
        """Old-style snoozes: hand them over to the reminder system once.

        (Nothing is hidden any more, so there is nothing to bring back; the
        pop-up itself comes from _followup_tick.) Runs from the always-on
        ticker, as before."""
        try:
            if self._migrate_old_snoozes():
                self._followups_changed()
        except Exception as e:
            log.warning("Could not convert old snoozes: %s", e)

    def _snooze_selected(self):
        """"Notify me on…" for the selected message (toolbar / keyboard)."""
        self._resync_selected_msg()
        if not self._selected_msg:
            messagebox.showinfo("Notify me", "Select a message first.",
                                parent=self.root)
            return
        when = _ask_send_time(self.root, self.root, purpose="snooze")
        if when is None:
            return
        self._snooze_message(self._selected_msg, when)

    def _render_snoozed(self):
        """Show the snooze list as if it were a normal folder.

        Only what was worth remembering is stored (sender, subject, when),
        not whole message bodies — so these rows are place-holders that tell
        you what is waiting and let you bring it back early. The real message
        never left Gmail, so "Unsnooze now" simply stops hiding it."""
        rows = []
        for s in self._snooze_store.get("snoozed", []):
            until = _parse_iso(s.get("until", ""))
            if until is None:
                continue
            rows.append({
                "id": s.get("key", ""), "thread_id": s.get("key", ""),
                "uid": None,
                "account_email": s.get("account", ""),
                "from": s.get("from", ""), "from_name": s.get("from", ""),
                "subject": s.get("subject", "(no subject)"),
                "date": until.strftime("%Y-%m-%d %H:%M"),
                "_sortkey": until.timestamp(), "_dt": s.get("until", ""),
                "body": (f"Snoozed until {until.strftime('%Y-%m-%d %H:%M')}.\n\n"
                         f"It is hidden from {s.get('folder','Inbox')} until "
                         f"then and comes back by itself — nothing on Gmail "
                         f"was changed.\n\nUse \"Unsnooze now\" below to bring "
                         f"it back immediately."),
                "unread": False, "starred": False, "priority": "normal",
                "spam": False, "attachments": [], "_attachment_data": {},
                "_html": "", "_folder": "Snoozed",
                "_snooze_key": s.get("key", ""),
            })
        rows.sort(key=lambda m: m["_sortkey"])
        self._all_messages = rows
        self._messages = rows
        self._selected_msg = None
        self._expanded_rows = set()
        self._search_active = False
        self.lbl_folder.configure(text=f"  Snoozed  ({len(rows)})")
        self._render_msg_list()
        self._show_reading_pane_empty()

    def _trust_sender(self, msg):
        """Stop the phishing heuristics from warning about this sender.

        Deliberately narrow: it matches the sender ADDRESS, not the domain,
        so trusting one newsletter does not trust everyone at that provider.
        Reversible in Tools → Blocked senders."""
        sender = (msg.get("from") or "").strip()
        if not sender:
            return
        if not messagebox.askyesno(
                "Trust this sender",
                f"Stop showing phishing warnings for:\n\n{sender}\n\n"
                f"Warnings about executable or disguised attachments will "
                f"STILL be shown — if this sender's account is ever taken "
                f"over, that is exactly when you need them.\n\n"
                f"You can undo this in Tools → Blocked senders.",
                parent=self.root):
            return
        self._blocklist_store.setdefault("trusted", []).append(
            {"match": sender, "added": _now_iso(), "reason": "manual"})
        _save_blocklist(self._blocklist_store)
        # Drop the cached verdict so the banner updates straight away.
        for m in self._messages:
            if (m.get("from") or "").strip() == sender:
                m.pop("_phish", None)
        self._flash("Sender trusted")
        if self._selected_msg:
            self._show_message_in_reading_pane(self._selected_msg)

    def _trust_domain(self, msg):
        """Trust an entire sending domain, not just one address (Issu: lots of
        false phishing warnings on mail sent through boardgamegeek.com, where
        each message comes from a different member address at the same domain).

        Stored as the bare domain in the same trusted list; _is_trusted_sender
        already matches it as a substring of every from-address at that domain.
        Attachment warnings still stay loud, exactly as for a trusted sender."""
        domain = (parseaddr(msg.get("from", ""))[1] or "").split("@")[-1].strip().lower()
        if not domain:
            return
        if not messagebox.askyesno(
                "Trust this whole domain",
                f"Stop showing phishing warnings for EVERY sender at:\n\n"
                f"@{domain}\n\n"
                f"Use this for a site that relays mail from many people "
                f"(e.g. boardgamegeek.com), where the address changes but the "
                f"domain is the one you trust.\n\n"
                f"Warnings about executable or disguised attachments will STILL "
                f"be shown.\n\nUndo in Tools → Blocked & trusted senders.",
                parent=self.root):
            return
        self._blocklist_store.setdefault("trusted", []).append(
            {"match": domain, "added": _now_iso(), "reason": "manual-domain"})
        _save_blocklist(self._blocklist_store)
        for m in self._messages:
            if domain in (m.get("from") or "").lower():
                m.pop("_phish", None)
        self._flash("Domain trusted")
        if self._selected_msg:
            self._show_message_in_reading_pane(self._selected_msg)

    # ── Notes (DEL 04g) ───────────────────────────────────────────────────────
    def _render_notes(self):
        """Show the local Notes folder as if it were a mailbox."""
        notes = _notes_list(self.cfg)
        self._all_messages  = notes
        self._messages      = notes
        self._selected_msg  = None
        self._expanded_rows = set()
        self._search_active = False
        self._apply_sort()
        self.lbl_folder.configure(text=f"  Notes  ({len(notes)})")
        self._render_msg_list()
        self._show_reading_pane_empty()
        self._update_title()

    # ── Deleted archive view (DEL 04s) ─────────────────────────────────────────
    def _render_deleted(self):
        """Show the hidden local archive of permanently-deleted messages."""
        metas = _deleted_load_all()
        msgs  = [_deleted_to_msg(m) for m in metas]
        self._all_messages  = msgs
        self._messages      = msgs
        self._selected_msg  = None
        self._expanded_rows = set()
        self._search_active = False
        self._apply_sort()
        days = int(self.cfg.get("deleted_keep_days", 30) or 0)
        keep = f"kept {days} days" if days > 0 else "kept forever"
        self.lbl_folder.configure(
            text=f"  Deleted  ({len(msgs)})   ·   {keep}   ·   "
                 f"right-click a message to restore or forward")
        self._render_msg_list()
        self._show_reading_pane_empty()
        self._update_title()

    def _restore_deleted(self, msg):
        """Try to upload a saved copy back onto Gmail (IMAP APPEND). Falls back
        to keeping the local copy, which can still be read or forwarded."""
        meta = msg.get("_deleted_meta") or {}
        acct = meta.get("account_email", "")
        raw  = msg.get("_raw")
        can_server = (self.cfg.get("allow_server_changes", False)
                      and not self._demo_mode and acct and raw)
        if not can_server:
            messagebox.showinfo(
                "Restore",
                "This can't be put back on Gmail automatically (server changes "
                "are off, or there is no saved content).\n\nThe message is safe "
                "here in Deleted — right-click → \"Continue (write to sender)\" "
                "to forward it, or turn on Tools → Server changes to upload it "
                "back to Gmail.", parent=self.root)
            return
        self._flash("Restoring…")

        def worker():
            problem = ""
            try:
                pwd = self._secret_for(acct)
                problem = (f"No stored password for {acct}." if not pwd
                           else _imap_append_message(acct, pwd, "Inbox", raw))
            except Exception as e:
                problem = str(e)

            def done():
                if problem:
                    messagebox.showwarning(
                        "Restore",
                        "Could not upload it back to Gmail:\n\n" + problem +
                        "\n\nThe local copy is kept — you can still read or "
                        "forward it.", parent=self.root)
                else:
                    _deleted_remove(meta)
                    self._flash("Restored to the Gmail Inbox")
                    if self._current_folder == "Deleted":
                        self._render_deleted()
            try:
                self.root.after(0, done)
            except Exception:
                pass
        threading.Thread(target=worker, daemon=True).start()

    def _continue_deleted(self, msg):
        """Open a reply to the sender with the rescued message quoted, so a
        permanently-deleted thread can still be continued."""
        self._focus_message(msg)
        self._reply()

    def _remove_deleted(self, msg):
        meta = msg.get("_deleted_meta") or {}
        if not messagebox.askyesno(
                "Remove copy",
                "Delete this saved local copy for good?\n\nIt is already gone "
                "from Gmail; this only removes Freemail's safety copy.",
                parent=self.root, default="no"):
            return
        _deleted_remove(meta)
        self._flash("Local copy removed")
        if self._current_folder == "Deleted":
            self._render_deleted()

    def _empty_deleted(self):
        metas = _deleted_load_all()
        if not metas:
            self._flash("The Deleted archive is already empty")
            return
        if not messagebox.askyesno(
                "Empty deleted",
                f"Permanently remove all {len(metas)} saved copies from the "
                f"Deleted archive?\n\nThese messages were already deleted from "
                f"Gmail; this clears the local safety copies too and CANNOT be "
                f"undone.", parent=self.root, default="no"):
            return
        n = _deleted_clear_all()
        self._flash(f"Emptied {n} from the Deleted archive")
        if self._current_folder == "Deleted":
            self._render_deleted()

    def _set_deleted_keep_days(self):
        from tkinter import simpledialog
        cur = int(self.cfg.get("deleted_keep_days", 30) or 0)
        val = simpledialog.askinteger(
            "Deleted archive",
            "Keep deleted copies for how many days?\n(0 = keep forever)",
            parent=self.root, initialvalue=cur, minvalue=0, maxvalue=3650)
        if val is None:
            return
        self.cfg["deleted_keep_days"] = int(val)
        _save_settings(self.cfg)
        self._flash(f"Deleted copies kept {val} days" if val > 0
                    else "Deleted copies kept forever")
        if self._current_folder == "Deleted":
            self._render_deleted()

    def _new_note(self):
        """Write a note. It is an ordinary compose window with the sending
        machinery replaced by "write a file" — same editor, same signature
        handling, same crash-safe draft, but nothing leaves the machine.

        This is the LONG note. For "milk, eggs, ring the dentist" use the
        post-it board (📌 Notes) instead — see _postit_board, DEL 04g3."""
        ComposeWindow(self.root, self.cfg, app=self, accounts=self._accounts,
                      note_mode=True)

    # ── DEL 04g3 — the post-it board ─────────────────────────────────────────
    def _postit_board(self):
        """A board of small coloured notes: pick one on the left, write on the
        right, and it saves itself.

        NOT a dialog. It is deliberately non-modal and single-instance, so it
        can sit open beside the mail all day (which is the whole point of a
        post-it) and pressing 📌 Notes again raises the one you already have
        instead of opening a second copy."""
        existing = getattr(self, "_postit_win", None)
        if existing is not None:
            try:
                if existing.winfo_exists():
                    existing.deiconify()
                    existing.lift()
                    existing.focus_force()
                    return
            except Exception:
                pass

        notes = _postit_load()
        state = {"cur": None, "dirty": False}

        win = tk.Toplevel(self.root)
        self._postit_win = win
        win.title("Notes — post-it board")
        win.configure(bg=C_BG3)
        _center_over(win, self.root, 940, 620)
        win.minsize(700, 420)
        try:
            win.iconbitmap(_icon_path())
        except Exception:
            pass

        tk.Label(win, text="📌  Post-it notes", bg=C_BG1, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold"), pady=8).pack(fill="x")

        body = tk.Frame(win, bg=C_BG3)
        body.pack(fill="both", expand=True, padx=10, pady=(6, 0))

        # ── Left: the board ──────────────────────────────────────────────
        left = tk.Frame(body, bg=C_BG3, width=300)
        left.pack(side="left", fill="y")
        left.pack_propagate(False)

        frow = tk.Frame(left, bg=C_BG3)
        frow.pack(fill="x", pady=(0, 4))
        tk.Label(frow, text="🔍", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left")
        e_find = tk.Entry(frow, bg=C_BG2, fg=C_FG, relief="flat",
                          insertbackground=C_ACCENT, font=("Segoe UI", 9),
                          insertofftime=0, insertontime=9999999)
        no_blink(e_find)
        e_find.pack(side="left", fill="x", expand=True, ipady=2, padx=(4, 0))

        board_wrap = tk.Frame(left, bg=C_BG2)
        board_wrap.pack(fill="both", expand=True)
        # Scrollbar packed BEFORE the expanding canvas — the packer trap that
        # renders it one pixel wide otherwise.
        sb = tk.Scrollbar(board_wrap, bg=C_BG3, troughcolor=C_BG1)
        sb.pack(side="right", fill="y")
        canv = tk.Canvas(board_wrap, bg=C_BG2, highlightthickness=0,
                         yscrollcommand=sb.set)
        canv.pack(side="left", fill="both", expand=True)
        sb.configure(command=canv.yview)
        cards = tk.Frame(canv, bg=C_BG2)
        cards_id = canv.create_window((0, 0), window=cards, anchor="nw")
        cards.bind("<Configure>",
                   lambda e: canv.configure(scrollregion=canv.bbox("all")))
        canv.bind("<Configure>",
                  lambda e: canv.itemconfigure(cards_id, width=e.width))
        _bind_mousewheel(cards, canv)

        # ── Right: the note itself ───────────────────────────────────────
        right = tk.Frame(body, bg=C_BG3)
        right.pack(side="left", fill="both", expand=True, padx=(10, 0))

        trow = tk.Frame(right, bg=C_BG3)
        trow.pack(fill="x")
        tk.Label(trow, text="Title:", bg=C_BG3, fg=C_FG_DIM, width=6,
                 anchor="e", font=("Segoe UI", 9)).pack(side="left")
        e_title = tk.Entry(trow, bg=C_BG2, fg=C_FG, relief="flat",
                           insertbackground=C_ACCENT,
                           font=("Segoe UI", 11, "bold"),
                           insertofftime=0, insertontime=9999999)
        no_blink(e_title)
        e_title.pack(side="left", fill="x", expand=True, ipady=4, padx=(4, 6))

        v_pin = tk.BooleanVar(value=False)
        chk_pin = tk.Checkbutton(trow, text="📌 Pin to the top",
                                 variable=v_pin, bg=C_BG3, fg=C_FG_DIM,
                                 selectcolor=C_BG2, activebackground=C_BG3,
                                 activeforeground=C_FG, font=("Segoe UI", 8),
                                 highlightthickness=0, relief="flat",
                                 cursor="hand2")
        chk_pin.pack(side="left")

        crow = tk.Frame(right, bg=C_BG3)
        crow.pack(fill="x", pady=(6, 4))
        tk.Label(crow, text="Colour:", bg=C_BG3, fg=C_FG_DIM, width=6,
                 anchor="e", font=("Segoe UI", 9)).pack(side="left")
        swatches = []

        txt = tk.Text(right, bg=C_BG2, fg=C_FG, relief="flat", wrap="word",
                      font=("Segoe UI", 10), padx=10, pady=8, undo=True,
                      insertbackground=C_FG,
                      insertofftime=0, insertontime=9999999)
        no_blink(txt)
        txt.pack(fill="both", expand=True)
        _bind_mousewheel(txt, None)

        # ── Reading the editor back into the note dict ───────────────────
        def _harvest():
            """Copy what is on screen into the note being edited. Returns True
            if anything actually changed, so an untouched note keeps its
            "last changed" time (otherwise merely LOOKING at a note would
            shuffle the board)."""
            n = state["cur"]
            if n is None:
                return False
            title = e_title.get().strip()
            bodytx = txt.get("1.0", "end-1c")
            color  = int(state.get("color", n.get("color", 0)))
            pinned = bool(v_pin.get())
            if (title == n.get("title", "") and bodytx == n.get("body", "")
                    and color == n.get("color", 0)
                    and pinned == bool(n.get("pinned"))):
                return False
            n["title"], n["body"] = title, bodytx
            n["color"], n["pinned"] = color, pinned
            n["updated"] = _now_iso()
            return True

        def _commit(redraw=True):
            if _harvest():
                _postit_save(notes)
                state["dirty"] = False
                if redraw:
                    _paint_board()

        # ── The board ────────────────────────────────────────────────────
        def _preview(n):
            first = next((ln.strip() for ln in (n.get("body") or "").splitlines()
                          if ln.strip()), "")
            return first[:46] + ("…" if len(first) > 46 else "")

        def _prune_empties():
            """An untouched "➕ New note" leaves an empty shell behind the
            moment you click another card. Nothing empty is ever written to
            disk, so drop them from the board too — except the one you are
            standing in, which is the note you are about to type into."""
            gone = [n for n in notes
                    if n is not state["cur"]
                    and not (n.get("title") or "").strip()
                    and not (n.get("body") or "").strip()]
            for n in gone:
                try:
                    notes.remove(n)
                except ValueError:
                    pass

        def _paint_board():
            _prune_empties()
            for w in cards.winfo_children():
                w.destroy()
            needle = e_find.get().strip().lower()
            shown = 0
            for n in _postit_order(notes):
                if needle and needle not in (
                        (n.get("title", "") + " " + n.get("body", "")).lower()):
                    continue
                shown += 1
                paper, accent = _POSTIT_COLORS[
                    max(0, min(len(_POSTIT_COLORS) - 1,
                               int(n.get("color", 0) or 0)))][1:]
                is_cur = n is state["cur"]
                card = tk.Frame(cards, bg=paper,
                                highlightthickness=2 if is_cur else 0,
                                highlightbackground=C_ACCENT,
                                highlightcolor=C_ACCENT)
                card.pack(fill="x", padx=6, pady=3)
                head = (("📌  " if n.get("pinned") else "")
                        + (n.get("title") or "(untitled)"))
                prev = _preview(n)
                # NOTE: a widget's own `pady` takes ONE distance — the (top,
                # bottom) tuple only works on pack()/grid(). Passing a tuple
                # here raises TclError: bad screen distance "0 6". So the
                # asymmetric spacing is done by pack, not by the widget.
                l1 = tk.Label(card, text=head, bg=paper, fg=C_FG_UNRD,
                              font=("Segoe UI", 10, "bold"), anchor="w",
                              justify="left", wraplength=250, padx=8)
                l1.pack(fill="x", pady=(6, 0) if prev else (6, 6))
                kids = [l1]
                if prev:
                    l2 = tk.Label(card, text=prev, bg=paper, fg=accent,
                                  font=("Segoe UI", 8), anchor="w",
                                  justify="left", wraplength=250, padx=8)
                    l2.pack(fill="x", pady=(1, 6))
                    kids.append(l2)
                for w in [card] + kids:
                    w.configure(cursor="hand2")
                    w.bind("<Button-1>", lambda e, nn=n: _open(nn))
                    w.bind("<Button-3>", lambda e, nn=n: _card_menu(e, nn))
            if not shown:
                tk.Label(cards,
                         text=("Nothing matches that." if needle else
                               "No notes yet.\n\nPress “➕ New note” and just "
                               "start typing — the first line becomes the "
                               "title if you leave Title empty."),
                         bg=C_BG2, fg=C_FG_DIM, font=("Segoe UI", 9, "italic"),
                         wraplength=250, justify="left", padx=10,
                         pady=14).pack(fill="x")

        def _paint_swatches():
            for i, (btn, (_name, paper, _acc)) in enumerate(
                    zip(swatches, _POSTIT_COLORS)):
                chosen = i == int(state.get("color", 0))
                btn.configure(bg=paper,
                              text="✓" if chosen else " ",
                              fg=C_FG_UNRD,
                              highlightbackground=C_ACCENT if chosen else paper,
                              highlightcolor=C_ACCENT if chosen else paper)

        def _set_color(i):
            state["color"] = i
            txt.configure(bg=_POSTIT_COLORS[i][1])
            _paint_swatches()
            _commit()

        for i, (name, paper, _acc) in enumerate(_POSTIT_COLORS):
            b = tk.Label(crow, text=" ", bg=paper, fg=C_FG_UNRD,
                         font=("Segoe UI", 10, "bold"), width=4,
                         highlightthickness=2, highlightbackground=paper,
                         cursor="hand2")
            b.pack(side="left", padx=3)
            b.bind("<Button-1>", lambda e, k=i: _set_color(k))
            add_tooltip(b, name)
            swatches.append(b)

        # ── Opening / creating / deleting ────────────────────────────────
        def _open(n):
            if n is state["cur"]:
                return
            _commit(redraw=False)
            state["cur"] = n
            state["color"] = int(n.get("color", 0) or 0)
            e_title.delete(0, "end")
            e_title.insert(0, n.get("title", ""))
            txt.delete("1.0", "end")
            txt.insert("1.0", n.get("body", ""))
            txt.edit_reset()
            v_pin.set(bool(n.get("pinned")))
            txt.configure(bg=_POSTIT_COLORS[state["color"]][1])
            _paint_swatches()
            _paint_board()
            txt.focus_set()

        def _new():
            _commit(redraw=False)
            n = {"title": "", "body": "", "color": len(notes) % len(_POSTIT_COLORS),
                 "pinned": False, "updated": _now_iso()}
            notes.append(n)
            state["cur"] = None       # so _open does not treat it as unchanged
            _open(n)
            e_title.focus_set()

        def _delete(n=None):
            n = n or state["cur"]
            if n is None:
                return
            name = (n.get("title") or _preview(n) or "this note")[:60]
            if not messagebox.askyesno(
                    "Delete note",
                    f"Delete “{name}”?\n\nThe note is on your own disk — "
                    f"nothing on any server is touched.",
                    parent=win, default="no"):
                return
            try:
                notes.remove(n)
            except ValueError:
                return
            if state["cur"] is n:
                state["cur"] = None
                e_title.delete(0, "end")
                txt.delete("1.0", "end")
                v_pin.set(False)
            _postit_save(notes)
            _paint_board()

        def _card_menu(event, n):
            m = tk.Menu(win, tearoff=0, bg=C_BG2, fg=C_FG,
                        activebackground=C_BG4, activeforeground=C_FG)
            m.add_command(label="📌 Unpin" if n.get("pinned") else "📌 Pin",
                          command=lambda: _toggle_pin(n))
            m.add_command(label="📋 Copy the text",
                          command=lambda: _copy(n))
            m.add_separator()
            m.add_command(label="🗑 Delete this note…",
                          command=lambda: _delete(n))
            try:
                m.tk_popup(event.x_root, event.y_root)
            finally:
                m.grab_release()

        def _toggle_pin(n):
            if n is state["cur"]:
                v_pin.set(not v_pin.get())
                _commit()
                return
            n["pinned"] = not n.get("pinned")
            n["updated"] = _now_iso()
            _postit_save(notes)
            _paint_board()

        def _copy(n):
            try:
                self.root.clipboard_clear()
                self.root.clipboard_append(
                    ((n.get("title") or "") + "\n" + (n.get("body") or "")).strip())
                self._flash("Note copied")
            except Exception:
                pass

        def _show_postit_file():
            """Open postit.txt in whatever reads .txt, having flushed first —
            showing him a file that does not yet contain what is on screen
            would be a small lie."""
            _autotitle()
            _commit(redraw=False)
            path = _postit_path()
            try:
                os.makedirs(os.path.dirname(path), exist_ok=True)
                if not os.path.isfile(path):
                    _postit_save(notes)
                if platform.system() == "Windows":
                    open_path(path)
                elif platform.system() == "Darwin":
                    os.system(f'open "{path}"')
                else:
                    os.system(f'xdg-open "{path}"')
            except Exception as e:
                messagebox.showerror("Notes", f"Could not open the file:\n{e}",
                                     parent=win)

        # A title left empty is filled from the first line when the note is
        # saved — "nothing you MUST fill in" only works if the program does
        # the tidying itself.
        def _autotitle(*_a):
            if state["cur"] is None:
                return
            if not e_title.get().strip():
                first = next((ln.strip() for ln in
                              txt.get("1.0", "end-1c").splitlines()
                              if ln.strip()), "")
                if first:
                    e_title.insert(0, first[:60])

        # ── Buttons ──────────────────────────────────────────────────────
        br = tk.Frame(win, bg=C_BG3)
        br.pack(fill="x", padx=10, pady=8)
        for text, colour, cmd, tip in (
                ("➕ New note", C_BTN_NOTE, _new,
                 "Start a new post-it. Just type — nothing has to be filled in."),
                ("🗑 Delete",   C_BTN_DEL, lambda: _delete(),
                 "Delete the note on screen (from your own disk)."),
                ("✉ Long note (compose window)…", C_BTN_STD,
                 lambda: (self._new_note()),
                 "The other kind of note: a full editor with attachments, "
                 "saved as an .eml file in the Notes folder."),
                ("📁 Open the file", C_BTN_STD,
                 lambda: _show_postit_file(),
                 "Show postit.txt in Explorer. It is ordinary text — you can "
                 "read and edit it in Notepad."),
        ):
            b = tk.Button(br, text=text, bg=colour, fg=C_BTN_FG,
                          font=("Segoe UI", 9), relief="flat", cursor="hand2",
                          padx=12, pady=4, command=cmd)
            b.pack(side="left", padx=4)
            add_tooltip(b, tip)
        tk.Label(br, text="saves itself", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8, "italic")).pack(side="right", padx=6)
        tk.Button(br, text="Close", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=12, pady=4,
                  command=lambda: _close()).pack(side="right", padx=4)

        # ── Saving without a Save button ─────────────────────────────────
        # Typing does not write to disk on every keystroke; it arms a short
        # timer that is pushed forward while you keep typing, so a note is on
        # disk about a second after you stop. Switching notes, closing the
        # window and closing the program all flush it as well.
        def _touch(*_a):
            state["dirty"] = True
            aid = state.get("after")
            if aid:
                try:
                    win.after_cancel(aid)
                except Exception:
                    pass
            state["after"] = win.after(900, lambda: (_autotitle(), _commit()))

        txt.bind("<KeyRelease>", _touch)
        e_title.bind("<KeyRelease>", _touch)
        v_pin.trace_add("write", lambda *_a: _commit())
        e_find.bind("<KeyRelease>", lambda e: _paint_board())

        def _close(*_a):
            aid = state.get("after")
            if aid:
                try:
                    win.after_cancel(aid)
                except Exception:
                    pass
            _autotitle()
            _commit(redraw=False)
            state["cur"] = None
            _prune_empties()
            _postit_save(notes)
            self._postit_win = None
            try:
                win.destroy()
            except Exception:
                pass

        win.protocol("WM_DELETE_WINDOW", _close)
        win.bind("<Escape>", lambda e: _close())
        win.bind("<Control-n>", lambda e: (_new(), "break")[1])

        state["color"] = 0
        _paint_swatches()
        _paint_board()
        if notes:
            _open(_postit_order(notes)[0])
        else:
            _new()
        win.focus_force()

    def _save_message_as_note(self, msg):
        """Copy a received message — attachments and all — into Notes.

        This is the "forward someone else's mail to my own pile" case, except
        nothing is forwarded anywhere: the copy is written straight to disk,
        so it survives whatever happens to the original on the server."""
        try:
            path = _note_write(
                self.cfg,
                subject=msg.get("subject", "") or "(no subject)",
                body=(f"From: {msg.get('from_name','')} <{msg.get('from','')}>\n"
                      f"Date: {msg.get('date','')}\n"
                      f"Folder: {msg.get('_folder','')}\n"
                      f"{'-' * 40}\n\n{msg.get('body','')}"),
                from_addr=msg.get("from", ""),
                to_addr=msg.get("account_email", ""),
                attach_data=msg.get("_attachment_data") or {},
                origin=msg)
        except Exception as e:
            log.error("Could not save note: %s", e)
            messagebox.showerror("Save to Notes",
                                 f"Could not write the note:\n{e}",
                                 parent=self.root)
            return
        self._flash("Saved to Notes!")
        log.info("Message saved as note: %s", path)
        if self._current_folder == "Notes":
            self._render_notes()

    def _delete_note(self, msg):
        path = msg.get("_note_path", "")
        if not path:
            return
        # A note is a FILE, and this really erases it — so a protected note
        # gets the same gate as protected mail (DEL 09p). Bulk-deleted notes
        # already pass through _soft_delete's gate; this is the single-note
        # path, which does not.
        if not self._guard_protected([msg], verb="Deleting"):
            return
        if not messagebox.askyesno(
                "Delete note",
                f"Delete this note?\n\n{os.path.basename(path)}\n\n"
                f"This deletes the file on your own disk. Nothing on any "
                f"server is touched — notes never went there.",
                parent=self.root, default="no"):
            return
        if _note_delete(path):
            self._flash("Note deleted")
            self._render_notes()
        else:
            messagebox.showerror("Delete note",
                                 "Could not delete that file — see the log.",
                                 parent=self.root)

    def _notes_folder_dialog(self):
        """Choose where notes live."""
        from tkinter import filedialog
        current = _notes_dir(self.cfg)
        chosen = filedialog.askdirectory(
            parent=self.root, title="Folder for notes", initialdir=current)
        if not chosen:
            return
        self.cfg["notes_dir"] = chosen
        _save_settings(self.cfg)
        self._flash("Notes folder changed")
        messagebox.showinfo(
            "Notes folder",
            f"New notes will be written to:\n\n{chosen}\n\n"
            f"Notes already in the old folder are NOT moved — they are "
            f"ordinary .eml files, so move them across yourself if you want "
            f"them together:\n\n{current}", parent=self.root)
        if self._current_folder == "Notes":
            self._render_notes()

    def _open_notes_folder(self):
        folder = _notes_dir(self.cfg)
        try:
            os.makedirs(folder, exist_ok=True)
            if platform.system() == "Windows":
                open_path(folder)
            elif platform.system() == "Darwin":
                os.system(f'open "{folder}"')
            else:
                os.system(f'xdg-open "{folder}"')
        except Exception as e:
            messagebox.showerror("Notes", f"Could not open the folder:\n{e}",
                                 parent=self.root)

    # ── Everything about one sender, in one place (DEL 09h) ───────────────────
    def _sender_rules_dialog(self, msg):
        """"Mail from the electricity company: always save the PDF, always tag
        it Bill, never notify me."

        One sentence, but until now it needed two editors — attachment rules
        live in one store and message filters in another. This writes both,
        keyed on the sender, so the thought stays in one piece."""
        sender = (parseaddr(msg.get("from", ""))[1] or
                  msg.get("from", "")).strip()
        if not sender:
            return
        top = self._dialog_shell(f"Rules for {sender}", 660, 760)

        tk.Label(top, text=sender, bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 11, "bold")).pack(pady=(8, 0))
        tk.Label(top, text=f"“{msg.get('from_name','')}”", bg=C_BG3,
                 fg=C_FG_DIM, font=("Segoe UI", 9)).pack()

        f = tk.Frame(top, bg=C_BG3)
        f.pack(fill="both", expand=True, padx=18, pady=8)

        # What is already set up for this sender?
        auto_rule = next((r for r in self._autosave_store.get("rules", [])
                          if (r.get("match_from") or "").lower()
                          in sender.lower() and r.get("match_from")), None)
        flt = next((x for x in self._filter_store.get("filters", [])
                    if (x.get("match_from") or "").lower() in sender.lower()
                    and x.get("match_from")), None)

        # ── Attachments ──────────────────────────────────────────────────────
        tk.Label(f, text="Attachments", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 10, "bold"), anchor="w").pack(fill="x")
        v_save = tk.BooleanVar(value=bool(auto_rule))
        tk.Checkbutton(f, text="Always save them to disk", variable=v_save,
                       bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9), highlightthickness=0,
                       anchor="w").pack(fill="x")
        row = tk.Frame(f, bg=C_BG3); row.pack(fill="x", padx=20)
        tk.Label(row, text="Name prefix:", bg=C_BG3, fg=C_FG_DIM, width=12,
                 anchor="e", font=("Segoe UI", 8)).pack(side="left")
        e_prefix = tk.Entry(row, bg=C_BG2, fg=C_FG, relief="flat",
                            insertbackground=C_ACCENT, font=("Segoe UI", 9),
                            insertofftime=0, insertontime=9999999)
        no_blink(e_prefix)
        e_prefix.pack(side="left", fill="x", expand=True, ipady=2)
        e_prefix.insert(0, (auto_rule or {}).get("prefix", ""))
        _dt_box2 = tk.Frame(f, bg=C_BG3)
        _dt_box2.pack(fill="x", padx=(20, 0))
        self._date_token_row(_dt_box2, e_prefix)
        tk.Label(f, text="            other tokens {sender} {account} — "
                         "e.g. GELF---Sandtorp 32---{YYYY-MM}---",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 7),
                 anchor="w").pack(fill="x")

        # Only some file types? (blank = every attachment.) Substring OR
        # wildcard: ".png" or "*.png", ".pdf", "faktura" all work.
        arow = tk.Frame(f, bg=C_BG3); arow.pack(fill="x", padx=20, pady=(4, 0))
        tk.Label(arow, text="Only files:", bg=C_BG3, fg=C_FG_DIM, width=12,
                 anchor="e", font=("Segoe UI", 8)).pack(side="left")
        e_match = tk.Entry(arow, bg=C_BG2, fg=C_FG, relief="flat",
                           insertbackground=C_ACCENT, font=("Segoe UI", 9),
                           insertofftime=0, insertontime=9999999)
        no_blink(e_match)
        e_match.pack(side="left", fill="x", expand=True, ipady=2)
        e_match.insert(0, (auto_rule or {}).get("match_attachment", ""))
        tk.Label(f, text="            blank = all · e.g.  *.png  ·  .pdf  ·  "
                         "faktura   (name contains / wildcard)",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 7),
                 anchor="w").pack(fill="x")

        # Where to file them. The month/year choices AUTO-CREATE folders and
        # work across every account, so shipping notes / receipts arriving at
        # different accounts all collect in the same dated structure. "Custom
        # folder…" lets you type your own, e.g. 0---Frakt & Kvitto/{YYYY-MM}.
        _FOLDER_MODES = [
            ("One common folder",            "common"),
            ("A sub-folder per sender",      "per_sender"),
            ("By month  (YYYY-MM)",          "{YYYY-MM}"),
            ("By year, then month",          "{YYYY}/{MM}"),
            ("Custom folder…",               "__custom__"),
        ]
        _mode_label = {v: lab for lab, v in _FOLDER_MODES}
        _std_modes = {"common", "per_sender", "{YYYY-MM}", "{YYYY}/{MM}"}
        cur_mode = (auto_rule or {}).get("subfolder", "common") or "common"
        is_custom = cur_mode not in _std_modes
        frow = tk.Frame(f, bg=C_BG3); frow.pack(fill="x", padx=20, pady=(2, 0))
        tk.Label(frow, text="File into:", bg=C_BG3, fg=C_FG_DIM, width=12,
                 anchor="e", font=("Segoe UI", 8)).pack(side="left")
        v_folder = tk.StringVar(
            value="Custom folder…" if is_custom
            else _mode_label.get(cur_mode, "One common folder"))
        om_fold = tk.OptionMenu(frow, v_folder, *[lab for lab, _v in _FOLDER_MODES])
        om_fold.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                          activeforeground=C_FG, highlightthickness=0,
                          relief="flat", font=("Segoe UI", 8), anchor="w")
        om_fold["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                                  activeforeground=C_FG)
        om_fold.pack(side="left", fill="x", expand=True)

        crow = tk.Frame(f, bg=C_BG3); crow.pack(fill="x", padx=20, pady=(2, 0))
        tk.Label(crow, text="Custom:", bg=C_BG3, fg=C_FG_DIM, width=12,
                 anchor="e", font=("Segoe UI", 8)).pack(side="left")
        e_custom = tk.Entry(crow, bg=C_BG2, fg=C_FG, relief="flat",
                            insertbackground=C_ACCENT, font=("Segoe UI", 9),
                            insertofftime=0, insertontime=9999999)
        no_blink(e_custom)
        e_custom.pack(side="left", fill="x", expand=True, ipady=2)
        if is_custom:
            e_custom.insert(0, cur_mode)
        tk.Label(f, text="            e.g.  0---Frakt & Kvitto/{YYYY-MM}   "
                         "(a folder under your base folder; {MM}{YYYY} auto-made)",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 7),
                 anchor="w").pack(fill="x")

        # The base folder everything is filed UNDER. If it is empty, auto-save
        # can't write anywhere, so show it and let it be set right here.
        base_dir = (self._autosave_store.get("default_dir") or "").strip()
        brow = tk.Frame(f, bg=C_BG3); brow.pack(fill="x", padx=20, pady=(4, 0))
        tk.Label(brow, text="Base folder:", bg=C_BG3, fg=C_FG_DIM, width=12,
                 anchor="e", font=("Segoe UI", 8)).pack(side="left")
        v_base = tk.StringVar(value=base_dir)
        e_base = tk.Entry(brow, textvariable=v_base, bg=C_BG2, fg=C_FG,
                          relief="flat", insertbackground=C_ACCENT,
                          font=("Segoe UI", 9),
                          insertofftime=0, insertontime=9999999)
        no_blink(e_base)
        e_base.pack(side="left", fill="x", expand=True, ipady=2)

        def _browse_base():
            from tkinter import filedialog
            d = filedialog.askdirectory(parent=top, title="Base folder for "
                                        "saved attachments",
                                        initialdir=v_base.get() or None)
            if d:
                v_base.set(d)
        tk.Button(brow, text="…", bg=C_BTN_STD, fg=C_BTN_FG, relief="flat",
                  cursor="hand2", font=("Segoe UI", 8), padx=6,
                  command=_browse_base).pack(side="left", padx=(4, 0))
        if not base_dir:
            tk.Label(f, text="            ⚠ set a base folder or nothing can be "
                             "saved to disk",
                     bg=C_BG3, fg="#e0b050", font=("Segoe UI", 7),
                     anchor="w").pack(fill="x")

        tk.Frame(f, bg=C_SEP, height=1).pack(fill="x", pady=10)

        # ── What happens to the message ──────────────────────────────────────
        tk.Label(f, text="Every message from them", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 10, "bold"), anchor="w").pack(fill="x")

        trow = tk.Frame(f, bg=C_BG3); trow.pack(fill="x", pady=3)
        tk.Label(trow, text="Tag it:", bg=C_BG3, fg=C_FG_DIM, width=12,
                 anchor="e", font=("Segoe UI", 9)).pack(side="left")
        tag_names = ["(no tag)"] + [f"{t.get('icon','●')} {t['name']}"
                                    for t in self._tag_store.get("tags", [])]
        cur_tag = (flt or {}).get("action_tag", "")
        cur_label = "(no tag)"
        for t in self._tag_store.get("tags", []):
            if t["id"] == cur_tag:
                cur_label = f"{t.get('icon','●')} {t['name']}"
        v_tag = tk.StringVar(value=cur_label)
        om = tk.OptionMenu(trow, v_tag, *tag_names)
        om.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                     activeforeground=C_FG, highlightthickness=0,
                     relief="flat", font=("Segoe UI", 9), anchor="w")
        om["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                             activeforeground=C_FG)
        om.pack(side="left", fill="x", expand=True)

        v_read = tk.BooleanVar(value=bool((flt or {}).get("action_read")))
        v_star = tk.BooleanVar(value=bool((flt or {}).get("action_star")))
        v_hide = tk.BooleanVar(value=bool((flt or {}).get("action_hide")))
        for text, var in (("Mark it read straight away", v_read),
                          ("Star it", v_star),
                          ("Keep it out of the message list", v_hide)):
            tk.Checkbutton(f, text=text, variable=var, bg=C_BG3, fg=C_FG,
                           selectcolor=C_BG2, activebackground=C_BG3,
                           activeforeground=C_FG, font=("Segoe UI", 9),
                           highlightthickness=0, anchor="w").pack(fill="x",
                                                                  padx=20)

        nrow = tk.Frame(f, bg=C_BG3); nrow.pack(fill="x", pady=(6, 0))
        tk.Label(nrow, text="Notify:", bg=C_BG3, fg=C_FG_DIM, width=12,
                 anchor="e", font=("Segoe UI", 9)).pack(side="left")
        v_notify = tk.StringVar(value=(flt or {}).get("action_notify",
                                                      "default"))
        for val, text in (("default", "as usual"), ("always", "always"),
                          ("never", "never")):
            tk.Radiobutton(nrow, text=text, value=val, variable=v_notify,
                           bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                           activebackground=C_BG3, activeforeground=C_FG,
                           font=("Segoe UI", 9),
                           highlightthickness=0).pack(side="left", padx=3)

        tk.Label(f,
                 text="This rule applies to mail from this sender to ANY of "
                      "your accounts. Everything here is local: files on your "
                      "disk and how this program shows the message. Nothing is "
                      "changed on Gmail.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 anchor="w", justify="left",
                 wraplength=560).pack(fill="x", pady=(12, 0))

        def _save():
            # Base folder first — without it, nothing can be filed.
            new_base = v_base.get().strip()
            if new_base != base_dir:
                self._autosave_store["default_dir"] = new_base
            # 1) the attachment rule
            rules = self._autosave_store.setdefault("rules", [])
            if auto_rule in rules:
                rules.remove(auto_rule)
            if v_save.get():
                folder_mode = next((v for lab, v in _FOLDER_MODES
                                    if lab == v_folder.get()), "common")
                if folder_mode == "__custom__":
                    folder_mode = e_custom.get().strip() or "common"
                only = e_match.get().strip()
                rules.append({
                    "match_from": sender, "match_subject": "",
                    "match_attachment": only,
                    # "Only files" now also restricts WHICH files are saved, so
                    # "*QR*" saves just the QR PNGs, not every attachment on the
                    # message (Issu 2026-08-01). Same value for both fields.
                    "save_only": only,
                    "account": "",                           # "" = ALL accounts
                    "subfolder": folder_mode,
                    "prefix": e_prefix.get(), "enabled": True})
            _save_autosave_rules(self._autosave_store)

            # 2) the message filter
            tag_id = ""
            label = v_tag.get()
            for t in self._tag_store.get("tags", []):
                if f"{t.get('icon','●')} {t['name']}" == label:
                    tag_id = t["id"]
            filters = self._filter_store.setdefault("filters", [])
            if flt in filters:
                filters.remove(flt)
            wants_filter = (tag_id or v_read.get() or v_star.get()
                            or v_hide.get() or v_notify.get() != "default")
            if wants_filter:
                filters.append(dict(
                    _FILTER_DEFAULTS, id=(flt or {}).get("id") or _new_id(),
                    name=f"Rules for {sender}", enabled=True,
                    match_from=sender, action_tag=tag_id,
                    action_read=bool(v_read.get()),
                    action_star=bool(v_star.get()),
                    action_hide=bool(v_hide.get()),
                    action_notify=v_notify.get()))
            _save_filters(self._filter_store)

            top.destroy()
            self._flash(f"Rules saved for {sender}")
            self._refresh_messages()

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(pady=10)
        for text, colour, cmd in (
                ("Save", C_BTN_NEW, _save),
                ("Attachment rules…", C_BTN_STD,
                 lambda: (top.destroy(), self._autosave_rules_dialog())),
                ("Mail filters…", C_BTN_STD,
                 lambda m=msg: (top.destroy(), self._filters_dialog(prefill_msg=m))),
                ("Cancel", C_BTN_STD, top.destroy)):
            tk.Button(btns, text=text, bg=colour, fg=C_BTN_FG,
                      font=("Segoe UI", 9), relief="flat", cursor="hand2",
                      padx=12, pady=4, command=cmd).pack(side="left", padx=4)

    # ── Import (DEL 04q) ──────────────────────────────────────────────────────
    def _import_dialog(self):
        """Bring old mail and contacts in from another program."""
        top = self._dialog_shell("Import", 700, 520)

        tk.Label(top,
                 text="Mail you already have should not be stranded in the "
                      "program you are leaving. Imported messages go into your "
                      "LOCAL ARCHIVE as .eml files — nothing is uploaded to "
                      "Gmail, and importing the same folder twice does not "
                      "double it.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9), wraplength=650,
                 justify="left", pady=8).pack(fill="x", padx=16)

        out = tk.Text(top, bg=C_BG2, fg=C_FG, relief="flat", height=12,
                      font=("Consolas", 9), wrap="word", padx=10, pady=8,
                      insertofftime=0, insertontime=9999999)
        no_blink(out)
        out.pack(fill="both", expand=True, padx=16, pady=6)

        def _say(text):
            out.configure(state="normal")
            out.insert("end", text + "\n")
            out.see("end")
            out.configure(state="disabled")
            top.update_idletasks()

        def _import_mail(folder=False):
            from tkinter import filedialog
            if folder:
                d = filedialog.askdirectory(
                    parent=top, title="Folder of mail files (mbox or .eml)")
                if not d:
                    return
                paths = []
                for root_, _dirs, names in os.walk(d):
                    for n in names:
                        if n.lower().endswith((".eml", ".mbox")) or "." not in n:
                            paths.append(os.path.join(root_, n))
            else:
                paths = list(filedialog.askopenfilenames(
                    parent=top, title="Mail files to import",
                    filetypes=[("Mail", "*.eml *.mbox"), ("All files", "*.*")]))
            if not paths:
                return
            label = self._current_acct if self._current_acct != ALL_ACCOUNTS_ID \
                else "imported"
            _say(f"Reading {len(paths)} file(s)…")
            stats = _import_messages(self.cfg, paths, account_label=label,
                                     folder_label="Imported",
                                     progress=lambda n, s: _say(f"  {n}"))
            _say(f"\nFound {stats['messages']} message(s) in "
                 f"{stats['files']} file(s).")
            _say(f"  {stats['written']} added to the archive")
            _say(f"  {stats['skipped']} were already there")
            for e in stats["errors"][:8]:
                _say(f"  ! {e}")
            _say(f"\nArchive: {_archive_dir(self.cfg)}")
            _say("Open it with View → Statistics, or search it from any "
                 "saved search.")

        def _import_vcf():
            from tkinter import filedialog
            paths = filedialog.askopenfilenames(
                parent=top, title="Contact file",
                filetypes=[("vCard", "*.vcf"), ("All files", "*.*")])
            if not paths:
                return
            total = 0
            for p in paths:
                try:
                    with open(p, "r", encoding="utf-8", errors="replace") as f:
                        people = _vcard_parse(f.read())
                except Exception as e:
                    _say(f"! {os.path.basename(p)}: {e}")
                    continue
                added = _merge_contacts(self._addressbook_store, people)
                total += added
                _say(f"{os.path.basename(p)}: {len(people)} card(s), "
                     f"{added} new")
            _say(f"\n{total} contact(s) added to the address book.")

        def _import_csv():
            # Thunderbird / Google / Outlook contact CSV (Issu 2026-08-01).
            from tkinter import filedialog
            paths = filedialog.askopenfilenames(
                parent=top, title="Contacts CSV",
                filetypes=[("CSV", "*.csv"), ("All files", "*.*")])
            if not paths:
                return
            total = 0
            for p in paths:
                try:
                    with open(p, "r", encoding="utf-8-sig", errors="replace") as f:
                        people = _csv_contacts_parse(f.read())
                except Exception as e:
                    _say(f"! {os.path.basename(p)}: {e}")
                    continue
                added = _merge_contacts(self._addressbook_store, people)
                total += added
                _say(f"{os.path.basename(p)}: {len(people)} row(s), "
                     f"{added} new")
            _say(f"\n{total} contact(s) added to the address book.")

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(pady=10)
        for text, colour, cmd in (
                ("📥 Mail files…", C_BTN_NEW, lambda: _import_mail(False)),
                ("📂 A whole folder…", C_BTN_STD, lambda: _import_mail(True)),
                ("👤 Contacts (.vcf)…", C_BTN_STD, _import_vcf),
                ("👤 Contacts (.csv)…", C_BTN_STD, _import_csv),
                ("Close", C_BTN_STD, top.destroy)):
            tk.Button(btns, text=text, bg=colour, fg=C_BTN_FG,
                      font=("Segoe UI", 9), relief="flat", cursor="hand2",
                      padx=12, pady=4, command=cmd).pack(side="left", padx=4)

        tk.Label(top,
                 text="Thunderbird mail: its folders are MBOX files with no "
                      "extension, under your profile's Mail directory — pick the "
                      "folder and everything inside comes across.\n"
                      "Thunderbird contacts: Address Book → Tools → Export → "
                      "either vCard (.vcf) or CSV, then import it here.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 wraplength=650, justify="left").pack(padx=16, pady=(0, 10))
        out.configure(state="disabled")

    # ── Opening links (DEL 04o) ───────────────────────────────────────────────
    def _open_url(self, url, msg=None, account=None):
        """Open a link — in the browser profile that belongs to the account
        the mail arrived at, when one is configured.

        EVERY outgoing link in this program goes through here, so the rule is
        applied in one place and there is no path that quietly falls back to
        whichever login the browser happened to be showing.

        Three ways out, fastest first:
          1. the browser is already open  → push the link into it (~1 ms)
          2. it is not                    → launch it ourselves, with the
                                            profile on the command line
          3. all else fails               → hand it to Windows
        """
        url = (url or "").strip()
        if not url:
            return
        acct = account or (msg or {}).get("account_email", "") or \
            (self._current_acct if self._current_acct != ALL_ACCOUNTS_ID else "")
        store = self._browser_store
        profile = _profile_for_account(store, acct)

        # 1. Straight into the browser that is already on screen. This is the
        #    difference between a tab appearing at once and waiting seconds for
        #    a second browser to start up just to pass four words along.
        if store.get("direct_handoff", True) and not store.get("system_default"):
            ok, note, ms = _handoff_to_running_browser(store, url, profile)
            if ok:
                log.info("Handed %s to the open browser in %.1f ms (profile=%s)",
                         url[:80], ms, profile or "-")
                self._set_status(
                    extra=(f"opened in profile “{profile}”" if profile
                           else "opened in the browser already running"))
                return
            log.info("No instant hand-off (%s) — launching the browser instead",
                     note)

        # 2. Nothing listening: start the browser, profile flag and all.
        cmd = _browser_command(store, url, profile)
        if cmd:
            try:
                import subprocess
                subprocess.Popen(cmd, close_fds=True)
                log.info("Opened %s (profile=%s)", url[:80], profile or "-")
                if profile:
                    self._set_status(extra=f"opened in profile “{profile}”")
                return
            except Exception as e:
                log.warning("Browser launch failed (%s), using the system "
                            "default: %s", cmd[0], e)
        try:
            open_url(url)
        except Exception as e:
            log.error("Could not open %s: %s", url, e)
            messagebox.showerror("Open link", f"Could not open:\n{url}\n\n{e}",
                                 parent=self.root)

    def _copy_link(self, url):
        """Put a URL on the clipboard (so links in HTML mail — DHL & co. — can
        be pasted, not only opened)."""
        try:
            self.root.clipboard_clear()
            self.root.clipboard_append(url)
            self.root.update()      # keep it on the clipboard after we return
            self._flash("Link copied")
        except Exception as e:
            log.warning("Copy link failed: %s", e)

    def _links_popup(self, msg):
        """Pick a link from the message. Each link can be OPENED (with this
        account's browser login) or COPIED to the clipboard — so an HTML mail's
        link (e.g. a DHL tracking URL) can be pasted as well as followed.

        Also the safe way to follow a link: the menu shows where each one
        really GOES, so a link whose text says one thing and whose address
        says another has nowhere to hide."""
        links = _links_in_message(msg)
        if not links:
            return
        acct = msg.get("account_email", "")
        prof = _profile_for_account(self._browser_store, acct)
        m = tk.Menu(self.root, tearoff=0, bg=C_BG2, fg=C_FG,
                    activebackground=C_BG4, activeforeground=C_FG)
        if prof:
            m.add_command(label=f"opens as “{prof}”  ({acct})",
                          state="disabled")
            m.add_separator()
        # Each link gets its own submenu: Open here, or Copy the address.
        for url in links:
            label = url if len(url) <= 78 else url[:75] + "…"
            sub = tk.Menu(m, tearoff=0, bg=C_BG2, fg=C_FG,
                          activebackground=C_BG4, activeforeground=C_FG)
            # "Open here" first: it is the one that does NOT hand the address
            # to a browser signed in to everything (DEL 04e2). The real
            # browser is still one line down for anything that needs it.
            sub.add_command(label="🪟  Open here (mini view, no JavaScript)",
                            command=lambda u=url, mm=msg: MiniWebWindow(
                                self, u, title="Page", msg=mm,
                                prefill_email=mm.get("account_email", "")))
            sub.add_command(label="🌐  Open in my real browser",
                            command=lambda u=url, mm=msg: self._open_url(u, msg=mm))
            sub.add_command(label="📋  Copy link",
                            command=lambda u=url: self._copy_link(u))
            m.add_cascade(label=label, menu=sub)
        m.add_separator()
        if len(links) > 1:
            m.add_command(label="📋  Copy ALL links",
                          command=lambda ls=links: self._copy_link("\n".join(ls)))
        m.add_command(label="Browser profiles…",
                      command=self._browser_profiles_dialog)
        try:
            m.tk_popup(self.root.winfo_pointerx(), self.root.winfo_pointery())
        finally:
            m.grab_release()

    def _browser_profiles_dialog(self):
        """Tie each Gmail account to a browser profile."""
        # Taller than it was: the Speed block below earns its space.
        top = self._dialog_shell("Browser profiles", 760, 800)
        store = self._browser_store

        tk.Label(top,
                 text="When mail arrives at one of your accounts, its links "
                      "can open with the browser login that belongs to THAT "
                      "account — so a sale on the gotanetreserv address opens "
                      "as that identity, not as whoever the browser was "
                      "showing last.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9), wraplength=680,
                 justify="left", pady=6).pack(fill="x", padx=14)

        f = tk.Frame(top, bg=C_BG3)
        f.pack(fill="both", expand=True, padx=14)

        v_on = tk.BooleanVar(value=bool(store.get("enabled", True)))
        tk.Checkbutton(f, text="Use a specific browser profile per account",
                       variable=v_on, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 10, "bold"), highlightthickness=0,
                       anchor="w").pack(fill="x", pady=(4, 6))

        row = tk.Frame(f, bg=C_BG3)
        row.pack(fill="x", pady=3)
        tk.Label(row, text="Browser:", bg=C_BG3, fg=C_FG_DIM, width=12,
                 anchor="e", font=("Segoe UI", 9)).pack(side="left")
        e_path = tk.Entry(row, bg=C_BG2, fg=C_FG, relief="flat",
                          insertbackground=C_ACCENT, font=("Segoe UI", 9),
                          insertofftime=0, insertontime=9999999)
        no_blink(e_path)
        e_path.pack(side="left", fill="x", expand=True, ipady=3, padx=4)
        e_path.insert(0, store.get("browser_path") or _guess_browser_path())

        def _browse():
            from tkinter import filedialog
            p = filedialog.askopenfilename(
                parent=top, title="The browser to use",
                filetypes=[("Programs", "*.exe"), ("Python", "*.py"),
                           ("All files", "*.*")])
            if p:
                e_path.delete(0, "end"); e_path.insert(0, p)

        tk.Button(row, text="…", bg=C_BTN_STD, fg=C_BTN_FG, relief="flat",
                  padx=8, command=_browse).pack(side="left")
        tk.Label(f, text="Leave it empty and WhyBrowse is looked up next to "
                         "this program. Naming it here is still worth doing: "
                         "it is how we know where to find the browser that is "
                         "already running.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8), wraplength=560,
                 justify="left", anchor="w").pack(fill="x", padx=90)

        row2 = tk.Frame(f, bg=C_BG3)
        row2.pack(fill="x", pady=3)
        tk.Label(row2, text="Profile flag:", bg=C_BG3, fg=C_FG_DIM, width=12,
                 anchor="e", font=("Segoe UI", 9)).pack(side="left")
        e_flag = tk.Entry(row2, bg=C_BG2, fg=C_FG, relief="flat",
                          insertbackground=C_ACCENT, font=("Consolas", 9),
                          insertofftime=0, insertontime=9999999)
        no_blink(e_flag)
        e_flag.pack(side="left", fill="x", expand=True, ipady=3, padx=4)
        e_flag.insert(0, store.get("profile_flag") or "--profile={profile}")
        tk.Label(f,
                 text="WhyBrowse: --profile={profile}   ·   "
                      "Chrome: --profile-directory={profile}   ·   "
                      "Firefox: -P {profile}",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8),
                 anchor="w").pack(fill="x", padx=90)

        # ---- How fast a link opens (the whole point of DEL 04o's fast path) --
        tk.Frame(f, bg=C_SEP, height=1).pack(fill="x", pady=10)
        tk.Label(f, text="Speed", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 10, "bold"), anchor="w").pack(fill="x")

        v_direct = tk.BooleanVar(value=bool(store.get("direct_handoff", True)))
        tk.Checkbutton(f,
                       text="Hand the link to the browser that is already open "
                            "(fast — nothing is launched)",
                       variable=v_direct, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9), highlightthickness=0,
                       anchor="w").pack(fill="x")

        v_sysdef = tk.BooleanVar(value=bool(store.get("system_default", False)))
        tk.Checkbutton(f,
                       text="Ignore all of this — let Windows open links its "
                            "own way (slow)",
                       variable=v_sysdef, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9), highlightthickness=0,
                       anchor="w").pack(fill="x")

        tk.Label(f,
                 text="Without the fast path, every link starts a SECOND "
                      "browser process whose only job is to tell the window "
                      "you already have open to show a page — that is where "
                      "the several seconds went, not the address lookup.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 wraplength=650, justify="left", anchor="w").pack(fill="x",
                                                                  padx=22)

        lbl_speed = tk.Label(f, text="", bg=C_BG3, fg=C_FG_DIM,
                             font=("Segoe UI", 9), wraplength=650,
                             justify="left", anchor="w")
        lbl_speed.pack(fill="x", padx=22, pady=(4, 0))

        def _check_speed():
            """Knock on the running browser's door without opening a page."""
            _collect()
            ok, note, ms = _handoff_to_running_browser(
                store, "", "", ping_only=True)
            if ok:
                lbl_speed.configure(
                    fg="#7ddc7d",
                    text=f"✓  Reached the browser already running in "
                         f"{ms:.1f} ms — links open instantly.")
            elif note == "not running":
                lbl_speed.configure(
                    fg=C_FG_DIM,
                    text="No browser is running right now, so the first link "
                         "will start one (that part is unavoidable). Open "
                         "WhyBrowse and press this again.")
            else:
                lbl_speed.configure(
                    fg="#ffb86c",
                    text=f"✗  Could not hand a link over: {note}. Links will "
                         f"still open — by launching the browser, the slow "
                         f"way.")

        tk.Button(f, text="⚡  Check the connection", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=12, pady=3,
                  command=_check_speed).pack(anchor="w", padx=22, pady=(4, 0))

        tk.Frame(f, bg=C_SEP, height=1).pack(fill="x", pady=10)
        tk.Label(f, text="Which profile for which account:", bg=C_BG3,
                 fg=C_FG, font=("Segoe UI", 10, "bold"),
                 anchor="w").pack(fill="x")
        tk.Label(f, text="Pick the browser profile of each account (the list is "
                         "WhyBrowse's own profiles).  'Add all (profiles)' fills "
                         "every account where one profile is clearly the right "
                         "one - nothing is guessed when it is not clear.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8),
                 wraplength=650, justify="left", anchor="w").pack(fill="x")

        entries = {}
        wb_profiles = ps_wb_profiles()
        choices = [_PS_NONE] + ["%s  [%s]" % (p["name"], p["id"])
                                for p in wb_profiles]
        grid = tk.Frame(f, bg=C_BG3)
        grid.pack(fill="x", pady=4)
        for a in self._accounts:
            if a.get("virtual"):
                continue
            r = tk.Frame(grid, bg=C_BG3)
            r.pack(fill="x", pady=2)
            tk.Label(r, text="  ", bg=(getattr(self, "_acct_colors", {}) or {}
                                       ).get(a["email"], C_BG4)
                     ).pack(side="left", padx=(0, 6))
            tk.Label(r, text=a["email"], bg=C_BG3, fg=C_FG, width=36,
                     anchor="w", font=("Segoe UI", 9)).pack(side="left")
            tk.Label(r, text="→", bg=C_BG3, fg=C_FG_DIM).pack(side="left")
            e = _PsChoice(r, choices, _ps_profile_label(
                wb_profiles, (store.get("map") or {}).get(a["email"], "")))
            e.pack(side="left", padx=6)
            entries[a["email"]] = e

        lbl_all = tk.Label(f, text="", bg=C_BG3, fg=C_FG_DIM,
                           font=("Segoe UI", 9), anchor="w")

        def _add_all():
            accts = [{"email": a["email"], "name": a.get("name")}
                     for a in self._accounts if not a.get("virtual")]
            found = ps_match_profiles(accts, wb_profiles)
            n = 0
            for em, pid in found.items():
                if not entries[em].get():
                    entries[em].set(_ps_profile_label(wb_profiles, pid))
                    n += 1
            left = [em for em, e in entries.items() if not e.get()]
            lbl_all.configure(
                text="Filled in %d account(s)." % n + (
                    "  Still empty (pick by hand): " + ", ".join(left)
                    if left else "  All accounts have a profile."))

        tk.Button(f, text="Add all (profiles)", bg=C_BTN_NEW, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=12, pady=3, command=_add_all).pack(anchor="w", pady=(2, 0))
        lbl_all.pack(fill="x")

        r3 = tk.Frame(f, bg=C_BG3)
        r3.pack(fill="x", pady=(8, 0))
        tk.Label(r3, text="Fallback:", bg=C_BG3, fg=C_FG_DIM, width=32,
                 anchor="w", font=("Segoe UI", 9, "italic")).pack(side="left")
        e_def = tk.Entry(r3, bg=C_BG2, fg=C_FG, relief="flat", width=24,
                         insertbackground=C_ACCENT, font=("Segoe UI", 10),
                         insertofftime=0, insertontime=9999999)
        no_blink(e_def)
        e_def.pack(side="left", ipady=3)
        e_def.insert(0, store.get("default_profile", ""))

        def _collect():
            store["enabled"] = bool(v_on.get())
            store["browser_path"] = e_path.get().strip()
            store["profile_flag"] = e_flag.get().strip() or "--profile={profile}"
            store["default_profile"] = e_def.get().strip()
            store["direct_handoff"] = bool(v_direct.get())
            store["system_default"] = bool(v_sysdef.get())
            store["map"] = {acct: _ps_profile_value(e.get())
                            for acct, e in entries.items() if e.get().strip()}

        def _save():
            _collect()
            _save_browser_profiles(store)
            top.destroy()
            self._flash("Browser profiles saved")

        def _test():
            _collect()
            acct = next(iter(store.get("map") or {}), "")
            prof = _profile_for_account(store, acct)
            cmd = _browser_command(store, "https://example.com", prof)
            ok, note, ms = _handoff_to_running_browser(store, "", "",
                                                       ping_only=True)
            first = (f"A browser is already open and reachable ({ms:.1f} ms) — "
                     f"links go straight into it and none of the command below "
                     f"is run.\n\n" if ok and store.get("direct_handoff", True)
                     and not store.get("system_default")
                     else f"Nothing to hand the link to right now ({note}), so "
                          f"this is what would happen:\n\n")
            messagebox.showinfo(
                "Test",
                first + (
                    "The system default browser would be used.\n"
                    "(No browser program is set, or the path does not exist.)"
                    if not cmd else
                    f"For {acct or '(no account)'} this runs:\n\n"
                    + " ".join(f'"{c}"' if " " in c else c for c in cmd)),
                parent=top)

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(pady=10)
        for text, colour, cmd in (("Save", C_BTN_NEW, _save),
                                  ("Show the command", C_BTN_STD, _test),
                                  ("Cancel", C_BTN_STD, top.destroy)):
            tk.Button(btns, text=text, bg=colour, fg=C_BTN_FG,
                      font=("Segoe UI", 9), relief="flat", cursor="hand2",
                      padx=16, pady=4, command=cmd).pack(side="left", padx=5)

    # ── Newsletters / senders (DEL 09g) ───────────────────────────────────────
    def _senders_dialog(self):
        """Who mails you, how much, and what you never open — with the tools
        to do something about it, several at a time."""
        top = self._dialog_shell("Senders & newsletters", 940, 620)

        bar = tk.Frame(top, bg=C_BG3)
        bar.pack(fill="x", padx=12)
        v_scope = tk.StringVar(value="both")
        tk.Label(bar, text="Look at:", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left")
        for val, text in (("loaded", "this folder"), ("archive", "archive"),
                          ("both", "both")):
            tk.Radiobutton(bar, text=text, value=val, variable=v_scope,
                           bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                           activebackground=C_BG3, activeforeground=C_FG,
                           font=("Segoe UI", 8),
                           highlightthickness=0).pack(side="left")
        v_ignored = tk.BooleanVar(value=False)
        tk.Checkbutton(bar, text="only the ones I never open",
                       variable=v_ignored, bg=C_BG3, fg=C_FG,
                       selectcolor=C_BG2, activebackground=C_BG3,
                       activeforeground=C_FG, font=("Segoe UI", 8),
                       highlightthickness=0).pack(side="left", padx=12)
        v_unsub = tk.BooleanVar(value=False)
        tk.Checkbutton(bar, text="only ones I can unsubscribe from",
                       variable=v_unsub, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 8),
                       highlightthickness=0).pack(side="left")

        tk.Label(top,
                 text="“Never open” means every message from them is still "
                      "unread — a conservative signal, not a guess about what "
                      "you read elsewhere.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 pady=2).pack(fill="x", padx=12)

        frm = tk.Frame(top, bg=C_BG2)
        frm.pack(fill="both", expand=True, padx=12, pady=4)
        sb = tk.Scrollbar(frm, bg=C_BG3, troughcolor=C_BG1)
        sb.pack(side="right", fill="y")
        lb = tk.Listbox(frm, bg=C_BG2, fg=C_FG, selectbackground=C_MSG_SEL,
                        selectforeground=C_FG_UNRD, highlightthickness=0,
                        relief="flat", activestyle="none",
                        selectmode="extended",     # several at once
                        font=("Consolas", 9), yscrollcommand=sb.set)
        sb.configure(command=lb.yview)
        lb.pack(fill="both", expand=True)

        rows = []

        def _refresh():
            pool = []
            scope = v_scope.get()
            if scope in ("loaded", "both"):
                pool.extend(self._all_messages or self._messages)
            if scope in ("archive", "both"):
                pool.extend(self._archive_messages())
            data = _sender_summary(pool, self._blocklist_store,
                                   self._tag_store, exclude_junk=False)
            rows.clear()
            lb.delete(0, "end")
            for r in data:
                if v_ignored.get() and not r["ignored"]:
                    continue
                if v_unsub.get() and not r["unsub"]:
                    continue
                rows.append(r)
                flag = "✖" if r["unsub"] else " "
                eye  = "🚫" if r["ignored"] else "  "
                days = (f"{r['days_since']}d ago" if r["days_since"] != ""
                        else "")
                lb.insert("end",
                          f" {flag} {eye}  {r['name'][:28]:<30}"
                          f"{r['addr'][:34]:<36}"
                          f"{r['count']:>4} mail  "
                          f"{r['unread']:>4} unread   {days}")
            if not rows:
                lb.insert("end", "   (nothing matches)")
            top.title(f"Senders & newsletters — {len(rows)}")

        for v in (v_scope, v_ignored, v_unsub):
            v.trace_add("write", lambda *a: _refresh())

        def _picked():
            return [rows[i] for i in lb.curselection() if i < len(rows)]

        def _unsub_selected():
            picked = [r for r in _picked() if r["unsub"]]
            if not picked:
                messagebox.showinfo(
                    "Unsubscribe",
                    "None of the selected senders offer an unsubscribe link.",
                    parent=top)
                return
            if not messagebox.askyesno(
                    "Unsubscribe",
                    f"Go through {len(picked)} sender(s) one at a time?\n\n"
                    f"Each one asks separately before anything is sent or "
                    f"opened — nothing happens behind your back.",
                    parent=top):
                return
            top.destroy()
            for r in picked:
                self._unsubscribe_dialog(r["sample"])

        def _block_selected():
            picked = _picked()
            if not picked or not messagebox.askyesno(
                    "Block senders",
                    f"Hide every message from {len(picked)} sender(s) from "
                    f"now on?\n\nLocal only — nothing is deleted and Gmail is "
                    f"not changed. Undo in Tools → Blocked & trusted senders.",
                    parent=top):
                return
            for r in picked:
                self._blocklist_store.setdefault("blocked", []).append(
                    {"match": r["addr"], "added": _now_iso(),
                     "reason": "sender overview"})
            _save_blocklist(self._blocklist_store)
            self._flash(f"{len(picked)} sender(s) blocked")
            _refresh()
            self._refresh_messages()

        def _tag_selected():
            picked = _picked()
            if not picked:
                return
            junk = next((t for t in self._tag_store.get("tags", [])
                         if t.get("id") == "junk"), None)
            if junk is None:
                messagebox.showinfo("Tag", "No “Junk” tag is defined.",
                                    parent=top)
                return
            n = 0
            pool = self._all_messages or self._messages
            addrs = {r["addr"] for r in picked}
            for m in pool:
                a = (parseaddr(m.get("from", ""))[1] or "").lower()
                if a in addrs:
                    have = {t["id"] for t in _tags_of(self._tag_store, m)}
                    if junk["id"] not in have:
                        _tag_toggle(self._tag_store, m, junk["id"])
                        n += 1
            self._flash(f"Tagged {n} message(s) as Junk")
            self._render_msg_list()

        def _show_mail():
            picked = _picked()
            if picked:
                top.destroy()
                self._all_from_sender(picked[0]["sample"])

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(pady=8)
        for text, colour, cmd in (
                ("✖ Unsubscribe…", C_BTN_LATER, _unsub_selected),
                ("🚫 Block", C_BTN_DEL, _block_selected),
                ("🗑 Tag as Junk", C_BTN_STD, _tag_selected),
                ("📇 Show their mail", C_BTN_STD, _show_mail),
                ("Refresh", C_BTN_STD, _refresh),
                ("Close", C_BTN_STD, top.destroy)):
            tk.Button(btns, text=text, bg=colour, fg=C_BTN_FG,
                      font=("Segoe UI", 9), relief="flat", cursor="hand2",
                      padx=10, pady=4, command=cmd).pack(side="left", padx=3)
        tk.Label(top, text="Ctrl+click or Shift+click to pick several.  "
                           "✖ = can be unsubscribed   🚫 = never opened",
                 bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(pady=(0, 8))
        _refresh()

    # ── Statistics (DEL 09g) ──────────────────────────────────────────────────
    def _stats_dialog(self):
        """What is in the archive, by year and month — kept because it is on
        disk anyway and nobody ever looks at it."""
        top = self._dialog_shell("Statistics", 780, 620)
        v_junk = tk.BooleanVar(value=True)      # exclude junk, default ON

        head = tk.Frame(top, bg=C_BG3)
        head.pack(fill="x", padx=12)
        tk.Checkbutton(head, text="Leave out blocked and junk senders",
                       variable=v_junk, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9), highlightthickness=0,
                       anchor="w").pack(side="left")

        frm = tk.Frame(top, bg=C_BG2)
        frm.pack(fill="both", expand=True, padx=12, pady=6)
        sb = tk.Scrollbar(frm, bg=C_BG3, troughcolor=C_BG1)
        sb.pack(side="right", fill="y")
        t = tk.Text(frm, bg=C_BG2, fg=C_FG, relief="flat",
                    font=("Consolas", 9), wrap="none", yscrollcommand=sb.set,
                    padx=10, pady=8, insertofftime=0, insertontime=9999999)
        no_blink(t)
        sb.configure(command=t.yview)
        t.pack(fill="both", expand=True)
        _bind_mousewheel(t, None)

        def _bar(n, top_n, width=28):
            if not top_n:
                return ""
            return "█" * max(1, int(width * n / top_n))

        def _build():
            t.configure(state="normal")
            t.delete("1.0", "end")
            base = _archive_dir(self.cfg)
            rep = _archive_size_report(base)

            t.insert("end", "THE ARCHIVE\n")
            t.insert("end", "=" * 62 + "\n")
            if not rep["files"]:
                t.insert("end",
                         "\nNothing archived yet.\n\n"
                         "File → Local archive keeps a copy of every message\n"
                         "on your own disk. With it on, this page fills up by\n"
                         "itself and these numbers become worth reading.\n")
                t.configure(state="disabled")
                return
            t.insert("end", f"\n  {rep['files']:,} messages   "
                            f"{_human_size(rep['bytes'])}\n"
                            f"  in {base}\n\n")

            t.insert("end", "BY YEAR\n" + "-" * 62 + "\n")
            years = sorted(rep["years"].items(), reverse=True)
            top_y = max((v["files"] for _k, v in years), default=0)
            for year, v in years:
                t.insert("end", f"  {year:<10}{v['files']:>7,} msg "
                                f"{_human_size(v['bytes']):>10}  "
                                f"{_bar(v['files'], top_y)}\n")

            t.insert("end", "\nBY MONTH (most recent 24)\n" + "-" * 62 + "\n")
            months = sorted(rep["months"].items(), reverse=True)[:24]
            top_m = max((v["files"] for _k, v in months), default=0)
            for month, v in months:
                t.insert("end", f"  {month:<10}{v['files']:>7,} msg "
                                f"{_human_size(v['bytes']):>10}  "
                                f"{_bar(v['files'], top_m)}\n")

            t.insert("end", "\nBY ACCOUNT\n" + "-" * 62 + "\n")
            for acct, v in sorted(rep["accounts"].items(),
                                  key=lambda kv: -kv[1]["files"]):
                t.insert("end", f"  {acct:<34}{v['files']:>7,} msg "
                                f"{_human_size(v['bytes']):>10}\n")

            t.insert("end", "\nBY FOLDER\n" + "-" * 62 + "\n")
            for fold, v in sorted(rep["folders"].items(),
                                  key=lambda kv: -kv[1]["files"]):
                t.insert("end", f"  {fold:<34}{v['files']:>7,} msg "
                                f"{_human_size(v['bytes']):>10}\n")

            # Who sends the most — from what is loaded plus a slice of the
            # archive, so it is quick but still says something real.
            pool = list(self._all_messages or self._messages)
            pool.extend(self._archive_messages(limit=400))
            senders = _sender_summary(pool, self._blocklist_store,
                                      self._tag_store,
                                      exclude_junk=bool(v_junk.get()))
            t.insert("end", "\nWHO SENDS THE MOST\n" + "-" * 62 + "\n")
            top_c = senders[0]["count"] if senders else 0
            for r in senders[:20]:
                mark = " 🚫" if r["ignored"] else "   "
                t.insert("end", f"  {r['name'][:26]:<28}{r['count']:>5} "
                                f"{mark} {_bar(r['count'], top_c, 20)}\n")
            if not senders:
                t.insert("end", "  (nothing loaded to count)\n")
            t.insert("end", "\n  🚫 = you have never opened any of them\n")
            t.configure(state="disabled")

        v_junk.trace_add("write", lambda *a: _build())

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(pady=8)
        tk.Button(btns, text="Refresh", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=14, pady=4, command=_build).pack(side="left", padx=4)
        tk.Button(btns, text="Senders & newsletters…", bg=C_BTN_STD,
                  fg=C_BTN_FG, font=("Segoe UI", 9), relief="flat",
                  cursor="hand2", padx=14, pady=4,
                  command=lambda: (top.destroy(),
                                   self._senders_dialog())).pack(side="left",
                                                                 padx=4)
        tk.Button(btns, text="Close", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=18, pady=4, command=top.destroy).pack(side="left",
                                                             padx=4)
        _build()

    # ── Attachment browser (DEL 09f) ──────────────────────────────────────────
    def _attachments_dialog(self):
        """Every file you have received, in one place.

        The read side of the auto-save rules: those decide where files LAND,
        this shows you what arrived. Sources are the loaded folder and the
        local archive, so it reaches back past what is currently fetched."""
        top = self._dialog_shell("Attachments", 900, 600)

        bar = tk.Frame(top, bg=C_BG3)
        bar.pack(fill="x", padx=12, pady=(0, 4))
        tk.Label(bar, text="Filter:", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left")
        e_filter = tk.Entry(bar, bg=C_BG2, fg=C_FG, relief="flat",
                            insertbackground=C_ACCENT, font=("Segoe UI", 10),
                            insertofftime=0, insertontime=9999999)
        no_blink(e_filter)
        e_filter.pack(side="left", fill="x", expand=True, ipady=3, padx=6)
        v_scope = tk.StringVar(value="both")
        for val, text in (("loaded", "this folder"), ("archive", "archive"),
                          ("both", "both")):
            tk.Radiobutton(bar, text=text, value=val, variable=v_scope,
                           bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                           activebackground=C_BG3, activeforeground=C_FG,
                           font=("Segoe UI", 8),
                           highlightthickness=0).pack(side="left")

        frm = tk.Frame(top, bg=C_BG2)
        frm.pack(fill="both", expand=True, padx=12, pady=4)
        sb = tk.Scrollbar(frm, bg=C_BG3, troughcolor=C_BG1)
        sb.pack(side="right", fill="y")
        lb = tk.Listbox(frm, bg=C_BG2, fg=C_FG, selectbackground=C_MSG_SEL,
                        selectforeground=C_FG_UNRD, highlightthickness=0,
                        relief="flat", activestyle="none",
                        font=("Consolas", 9), yscrollcommand=sb.set)
        sb.configure(command=lb.yview)
        lb.pack(fill="both", expand=True)

        rows = []          # (filename, msg)

        def _collect():
            pool = []
            scope = v_scope.get()
            if scope in ("loaded", "both"):
                pool.extend(self._all_messages or self._messages)
            if scope in ("archive", "both"):
                pool.extend(self._archive_messages())
            out = []
            seen = set()
            for m in pool:
                for fname in (m.get("attachments") or []):
                    key = (fname, m.get("_message_id") or _msg_key(m))
                    if key in seen:
                        continue
                    seen.add(key)
                    out.append((fname, m))
            out.sort(key=lambda r: r[1].get("_sortkey", 0.0), reverse=True)
            return out

        def _refresh(event=None):
            q = e_filter.get().strip().lower()
            lb.delete(0, "end")
            rows.clear()
            for fname, m in _collect():
                sender = (m.get("from_name") or m.get("from") or "")[:24]
                when = (m.get("_dt") or "")[:10]
                line = f"{fname[:44]:<46}{sender:<26}{when}  {m.get('_folder','')}"
                if q and q not in line.lower():
                    continue
                rows.append((fname, m))
                lb.insert("end", "  " + line)
            if not rows:
                lb.insert("end", "   (nothing found)")
            top.title(f"Attachments — {len(rows)}")

        e_filter.bind("<KeyRelease>", _refresh)
        v_scope.trace_add("write", lambda *a: _refresh())

        def _selected():
            cur = lb.curselection()
            if not cur or cur[0] >= len(rows):
                return None, None
            return rows[cur[0]]

        def _open():
            fname, m = _selected()
            if fname:
                self._open_attachment(m, fname)

        def _save_as():
            fname, m = _selected()
            if not fname:
                return
            data = (m.get("_attachment_data") or {}).get(fname)
            if not data:
                messagebox.showinfo("Save", "The file content is not "
                                            "available for this message.",
                                    parent=top)
                return
            from tkinter import filedialog
            path = filedialog.asksaveasfilename(parent=top, initialfile=fname)
            if not path:
                return
            try:
                with open(path, "wb") as f:
                    f.write(data)
                self._flash("Saved")
            except Exception as e:
                messagebox.showerror("Save", str(e), parent=top)

        def _show_msg():
            fname, m = _selected()
            if m:
                top.destroy()
                self._selected_msg = m
                self._show_message_in_reading_pane(m)

        lb.bind("<Double-Button-1>", lambda e: _open())
        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(pady=8)
        for text, colour, cmd in (("Open", C_BTN_NEW, _open),
                                  ("Save as…", C_BTN_STD, _save_as),
                                  ("Show the message", C_BTN_STD, _show_msg),
                                  ("Refresh", C_BTN_STD, _refresh),
                                  ("Close", C_BTN_STD, top.destroy)):
            tk.Button(btns, text=text, bg=colour, fg=C_BTN_FG,
                      font=("Segoe UI", 9), relief="flat", cursor="hand2",
                      padx=12, pady=4, command=cmd).pack(side="left", padx=4)
        _refresh()

    # ── "What needs me?" (DEL 09f) ────────────────────────────────────────────
    def _needs_me_data(self):
        """Everything the program already knows that is waiting for you.

        Nothing here is fetched or computed twice — it is the same stores the
        rest of the program uses, read in one place."""
        now = datetime.now()
        out = {"followups": [], "outbox": [], "drafts": [], "events": [],
               "unanswered": []}

        for it in self._followup_store.get("items", []):
            if it.get("done"):
                continue
            nxt = _parse_iso(it.get("next_at", "") or "")
            if nxt and nxt <= now + timedelta(days=1):
                out["followups"].append((nxt, it))
        out["followups"].sort(key=lambda r: r[0])

        for m in self._outbox_store.get("messages", []):
            if m.get("state") in ("queued", "failed"):
                out["outbox"].append(m)

        out["drafts"] = [d for d in _list_drafts()
                         if not d.get("sent") and not d.get("queued")]

        try:
            day_end = now.replace(hour=23, minute=59, second=59)
            out["events"] = _events_between(self._calendar_store, now,
                                            day_end + timedelta(days=1))
        except Exception as e:
            log.debug("needs-me calendar: %s", e)

        # Unanswered: addressed to me, older than a week, and no later
        # message from me in the same conversation. Only across what is
        # LOADED — an honest limit, stated in the window.
        mine = {a.get("email", "").lower() for a in self._accounts
                if not a.get("virtual")}
        threads = {}
        for m in self._all_messages or self._messages:
            threads.setdefault(m.get("thread_id", m.get("id")), []).append(m)
        for tid, msgs in threads.items():
            msgs = sorted(msgs, key=_thread_order)
            last = msgs[-1]
            sender = (parseaddr(last.get("from", ""))[1] or "").lower()
            if sender in mine:
                continue                     # I spoke last
            dt = _parse_msg_dt(last.get("_dt", "") or "")
            if dt is None or (now - dt).days < 7:
                continue
            if last.get("_folder") in ("Sent", "Drafts", "Spam", "Trash"):
                continue
            out["unanswered"].append((dt, last))
        out["unanswered"].sort(key=lambda r: r[0])
        return out

    def _needs_me_dialog(self):
        """One page with whatever is actually waiting. A button, not a
        welcome screen — you open it when you want it."""
        data = self._needs_me_data()
        top = self._dialog_shell("What needs me?", 720, 640)

        outer = tk.Frame(top, bg=C_BG2)
        outer.pack(fill="both", expand=True, padx=10, pady=6)
        canvas = tk.Canvas(outer, bg=C_BG2, highlightthickness=0)
        sb = tk.Scrollbar(outer, command=canvas.yview, bg=C_BG3,
                          troughcolor=C_BG1)
        sb.pack(side="right", fill="y")
        canvas.pack(side="left", fill="both", expand=True)
        canvas.configure(yscrollcommand=sb.set)
        body = tk.Frame(canvas, bg=C_BG2)
        win = canvas.create_window((0, 0), window=body, anchor="nw")
        body.bind("<Configure>",
                  lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
        canvas.bind("<Configure>",
                    lambda e: canvas.itemconfigure(win, width=e.width))
        _bind_mousewheel(body, canvas)

        def _section(title, colour, count):
            tk.Frame(body, bg=C_BG2, height=8).pack(fill="x")
            head = tk.Frame(body, bg=C_BG1)
            head.pack(fill="x")
            tk.Label(head, text=f"  {title}  ({count})", bg=C_BG1,
                     fg=colour if count else C_FG_DIM,
                     font=("Segoe UI", 10, "bold"), anchor="w",
                     pady=4).pack(fill="x")
            return head

        def _row(text, on_click=None, colour=C_FG, sub=""):
            fr = tk.Frame(body, bg=C_BG2)
            fr.pack(fill="x", padx=14, pady=1)
            lbl = tk.Label(fr, text=text, bg=C_BG2, fg=colour,
                           font=("Segoe UI", 9), anchor="w", justify="left",
                           wraplength=620,
                           cursor="hand2" if on_click else "arrow")
            lbl.pack(fill="x")
            if sub:
                tk.Label(fr, text="      " + sub, bg=C_BG2, fg=C_FG_DIM,
                         font=("Segoe UI", 8), anchor="w").pack(fill="x")
            if on_click:
                for w in (fr, lbl):
                    w.bind("<Button-1>", lambda e: (top.destroy(), on_click()))
                lbl.bind("<Enter>", lambda e: lbl.configure(fg=C_ACCENT))
                lbl.bind("<Leave>", lambda e: lbl.configure(fg=colour))

        now = datetime.now()
        total = 0

        _section("🔔  Follow-ups due", C_FOLLOWUP, len(data["followups"]))
        total += len(data["followups"])
        for nxt, it in data["followups"][:12]:
            late = "overdue" if nxt <= now else nxt.strftime("%H:%M")
            _row(f"{it.get('subject','')[:60]}",
                 on_click=lambda i=it: self._open_followup_message(i),
                 colour="#ff9c9c" if nxt <= now else C_FG,
                 sub=f"{late}  ·  {it.get('note') or 'no note'}")
        if not data["followups"]:
            _row("Nothing due.", colour=C_FG_DIM)

        _section("📤  Outbox", C_ACCENT, len(data["outbox"]))
        total += len(data["outbox"])
        for m in data["outbox"][:12]:
            dt = _parse_iso(m.get("send_at", ""))
            state = m.get("state")
            _row(f"{m.get('subject') or '(no subject)'}  →  {m.get('to','')}",
                 on_click=self._outbox_dialog,
                 colour="#ff9c9c" if state == "failed" else C_FG,
                 sub=(f"FAILED: {m.get('error','')[:60]}" if state == "failed"
                      else f"goes out {dt.strftime('%Y-%m-%d %H:%M') if dt else 'soon'}"))
        if not data["outbox"]:
            _row("Empty.", colour=C_FG_DIM)

        _section("📝  Unsent drafts", C_ACCENT, len(data["drafts"]))
        total += len(data["drafts"])
        for d in data["drafts"][:12]:
            _row(f"{d.get('subject') or '(no subject)'}  →  {d.get('to','')}",
                 on_click=lambda dd=d: ComposeWindow(
                     self.root, self.cfg, app=self, accounts=self._accounts,
                     draft=dd),
                 sub=f"last saved {(d.get('saved') or '')[:16]}")
        if not data["drafts"]:
            _row("None.", colour=C_FG_DIM)

        _section("📅  Today and tomorrow", C_ACCENT, len(data["events"]))
        for occ, ev in data["events"][:12]:
            _row(f"{_fmt_event_time(occ, ev)}   {ev.get('title','')}",
                 on_click=lambda d=occ: self._open_calendar(d),
                 sub=ev.get("location", ""))
        if not data["events"]:
            _row("Nothing planned.", colour=C_FG_DIM)

        _section("✉  Unanswered, older than a week", C_ACCENT,
                 len(data["unanswered"]))
        total += len(data["unanswered"])
        for dt, m in data["unanswered"][:15]:
            days = (now - dt).days
            _row(f"{m.get('subject','')[:60]}",
                 on_click=lambda mm=m: self._jump_to(mm),
                 sub=f"{days} days  ·  {m.get('from_name') or m.get('from','')}")
        if not data["unanswered"]:
            _row("Nothing waiting on you.", colour=C_FG_DIM)
        tk.Label(body,
                 text="      (searched among the messages currently loaded — "
                      "open a folder and Refresh to widen it)",
                 bg=C_BG2, fg="#555a75", font=("Segoe UI", 7),
                 anchor="w").pack(fill="x", padx=14)

        tk.Label(top,
                 text=(f"{total} thing(s) want your attention"
                       if total else "Nothing needs you right now."),
                 bg=C_BG3, fg=C_ACCENT if total else "#69db7c",
                 font=("Segoe UI", 10, "bold"), pady=6).pack(fill="x")
        tk.Button(top, text="Close", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=20, pady=4, command=top.destroy).pack(pady=(0, 8))

    # ── Saved searches (DEL 04m) ──────────────────────────────────────────────
    def _pool_for_search(self, search):
        """The messages a saved search looks through.

        "loaded" is what is in memory — instant. "archive" reads the .eml
        files you own, which covers mail no longer on the server. "both" is
        the honest default for a question like "everything from X, ever"."""
        scope = search.get("scope", "loaded")
        pool = []
        if scope in ("loaded", "both"):
            pool.extend(self._all_messages or self._messages)
        if scope in ("archive", "both"):
            pool.extend(self._archive_messages())
        # De-duplicate: the same message can be both loaded and archived.
        seen, out = set(), []
        for m in pool:
            k = m.get("_message_id") or _msg_key(m)
            if k in seen:
                continue
            seen.add(k)
            out.append(m)
        return out

    def _archive_messages(self, limit=800):
        """Read the local archive as message dicts (newest files first).

        Capped, because an archive can hold years of mail and a saved search
        should stay instant."""
        base = _archive_dir(self.cfg)
        found = []
        try:
            if not os.path.isdir(base):
                return []
            paths = []
            for root_, _dirs, names in os.walk(base):
                for n in names:
                    if n.lower().endswith(".eml"):
                        paths.append(os.path.join(root_, n))
            paths.sort(key=lambda p: os.path.basename(p), reverse=True)
            for path in paths[:limit]:
                try:
                    with open(path, "rb") as f:
                        em = _email.message_from_bytes(f.read())
                except Exception:
                    continue
                # account/folder are the two levels under the archive root
                rel = os.path.relpath(path, base).split(os.sep)
                acct = rel[0] if len(rel) > 2 else ""
                fold = rel[1] if len(rel) > 2 else "Archive"
                msg = _build_msg_dict(em, [b"\\Seen"], None, None, acct,
                                      fold, "")
                msg["unread"] = False
                msg["id"] = path
                msg["thread_id"] = path
                msg["_archived_path"] = path
                found.append(msg)
        except Exception as e:
            log.warning("Could not read the archive: %s", e)
        return found

    def _run_saved_search(self, search):
        """Open a saved search as if it were a folder."""
        pool = self._pool_for_search(search)
        hits = [m for m in pool
                if _search_matches(search, m, self._tag_store)]
        hits.sort(key=lambda m: m.get("_sortkey", 0.0), reverse=True)
        self._messages      = hits
        self._all_messages  = hits
        self._selected_msg  = None
        self._selected_ids  = set()
        self._expanded_rows = set()
        self._search_active = True
        self._current_search = search
        self.lbl_folder.configure(
            text=f"  🔎 {search.get('name','Search')}  ({len(hits)})   "
                 f"— {_search_describe(search)}")
        self._render_msg_list()
        self._show_reading_pane_empty()
        self._update_title()

    def _all_from_sender(self, msg):
        """"Everything from this person, wherever it is" — the question you
        ask most often, without having to save it first."""
        addr = (msg.get("from") or "").strip()
        if not addr:
            return
        self._run_saved_search({
            "id": "", "name": f"From {addr}", "query": "", "from": addr,
            "subject": "", "folder": "", "tag": "", "unread_only": False,
            "has_attachment": False, "scope": "both", "created": "",
        })

    def _save_current_search(self):
        """Keep whatever is in the search box as a named search."""
        raw = self.e_search.get().strip()
        if raw == "Search mail…":
            raw = ""
        from tkinter import simpledialog
        name = simpledialog.askstring(
            "Save search",
            "Name for this search:\n\n"
            f"(text: {raw or 'everything'}"
            + (", unread only" if self._quick.get("unread") else "")
            + (", with attachment" if self._quick.get("attach") else "") + ")",
            parent=self.root)
        if not name:
            return
        rec = dict(_SEARCH_DEFAULTS)
        rec.update({
            "id": _new_id(), "name": name.strip(), "query": raw,
            "folder": ("" if self._search_active else self._current_folder),
            "unread_only": bool(self._quick.get("unread")),
            "has_attachment": bool(self._quick.get("attach")),
            "scope": "both", "created": _now_iso(),
        })
        self._search_store.setdefault("searches", []).append(rec)
        _save_searches(self._search_store)
        self._populate_sidebar(self.sidebar_inner)
        self._flash(f"Saved search “{rec['name']}”")

    def _delete_saved_search(self, search):
        if not messagebox.askyesno(
                "Delete saved search",
                f"Delete “{search.get('name','')}”?\n\n"
                f"Only the saved question goes — no mail is touched.",
                parent=self.root):
            return
        self._search_store["searches"] = [
            s for s in self._search_store.get("searches", [])
            if s.get("id") != search.get("id")]
        _save_searches(self._search_store)
        self._populate_sidebar(self.sidebar_inner)

    # ── Folder plans (DEL 04l) ────────────────────────────────────────────────
    def _folderplan_tick(self):
        """Run any plan whose day has come. Called from the always-on ticker."""
        store = self._folderplan_store
        for plan in store.get("plans", []):
            if not _plan_due(plan):
                continue
            res = _plan_run(plan)
            _plan_mark_run(store, plan)
            if res["error"]:
                log.error("Folder plan '%s': %s", plan.get("name"),
                          res["error"])
                NotifyToast(self.root, "📁  Folder plan failed",
                            [plan.get("name", ""), res["error"][:60]])
                continue
            log.info("Folder plan '%s': %s, moved %d file(s)",
                     plan.get("name"), res["folder"], len(res["moved"]))
            lines = [os.path.basename(res["folder"])]
            if plan.get("move_files"):
                lines.append(f"{len(res['moved'])} file(s) moved in")
            NotifyToast(self.root, "📁  Folder created", lines,
                        on_click=lambda p=res["folder"]: self._open_path(p))

    def _folderplans_dialog(self):
        """Make dated folders on a schedule and tidy files into them."""
        top = self._dialog_shell("Automatic folders", 760, 620)
        store = self._folderplan_store

        tk.Label(top,
                 text="Create a dated sub-folder on a schedule — e.g. on the "
                      "3rd of every month, make \"08-August\" inside your "
                      "Frakt folder — and optionally move that month's files "
                      "into it. This works on FILES on your disk; nothing on "
                      "Gmail is touched.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 wraplength=720, justify="left",
                 pady=4).pack(fill="x", padx=12)

        body = tk.Frame(top, bg=C_BG3)
        body.pack(fill="both", expand=True, padx=12, pady=6)
        left = tk.Frame(body, bg=C_BG3)
        left.pack(side="left", fill="y")
        lb = self._listbox(left, width=26)
        lb.pack(fill="y", expand=True, pady=4)

        right = tk.Frame(body, bg=C_BG3)
        right.pack(side="left", fill="both", expand=True, padx=(12, 0))

        e_name = self._labelled_entry(right, "Plan name:", width=12)

        row = tk.Frame(right, bg=C_BG3)
        row.pack(fill="x", pady=3)
        tk.Label(row, text="In folder:", bg=C_BG3, fg=C_FG_DIM, width=12,
                 anchor="e", font=("Segoe UI", 9)).pack(side="left")
        e_base = tk.Entry(row, bg=C_BG2, fg=C_FG, relief="flat",
                          insertbackground=C_ACCENT, font=("Segoe UI", 9),
                          insertofftime=0, insertontime=9999999)
        no_blink(e_base)
        e_base.pack(side="left", fill="x", expand=True, ipady=3, padx=(0, 4))

        def _browse():
            from tkinter import filedialog
            d = filedialog.askdirectory(parent=top, title="Folder to work in",
                                        initialdir=e_base.get().strip() or None)
            if d:
                e_base.delete(0, "end"); e_base.insert(0, d)

        tk.Button(row, text="…", bg=C_BTN_STD, fg=C_BTN_FG, relief="flat",
                  padx=8, command=_browse).pack(side="left")

        e_pat = self._labelled_entry(right, "Folder name:", width=12)
        tk.Label(right,
                 text="Tokens: {MM} {M} {YYYY} {YY} {MonthName} {Q} {DD}"
                      "     — e.g. \"{MM}-{MonthName}\" → 08-August",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8),
                 anchor="w").pack(fill="x", padx=4)

        e_months = self._labelled_entry(right, "Month names:", width=12)
        tk.Label(right,
                 text="12 names, comma-separated, if you want them in your "
                      "own language. Leave empty for English.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8),
                 anchor="w").pack(fill="x", padx=4)

        r2 = tk.Frame(right, bg=C_BG3)
        r2.pack(fill="x", pady=(8, 3))
        tk.Label(r2, text="Run on day:", bg=C_BG3, fg=C_FG_DIM, width=12,
                 anchor="e", font=("Segoe UI", 9)).pack(side="left")
        e_day = tk.Entry(r2, bg=C_BG2, fg=C_FG, relief="flat", width=4,
                         insertbackground=C_ACCENT, font=("Segoe UI", 10),
                         insertofftime=0, insertontime=9999999)
        no_blink(e_day); e_day.pack(side="left", ipady=2)
        tk.Label(r2, text="of every", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left", padx=4)
        e_every = tk.Entry(r2, bg=C_BG2, fg=C_FG, relief="flat", width=4,
                           insertbackground=C_ACCENT, font=("Segoe UI", 10),
                           insertofftime=0, insertontime=9999999)
        no_blink(e_every); e_every.pack(side="left", ipady=2)
        tk.Label(r2, text="month(s)   (1 = monthly, 3 = quarterly)",
                 bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(side="left", padx=4)

        v_enabled = tk.BooleanVar(value=True)
        v_move    = tk.BooleanVar(value=True)
        v_window  = tk.StringVar(value="previous_month")

        tk.Checkbutton(right, text="Plan is active", variable=v_enabled,
                       bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9), highlightthickness=0,
                       anchor="w").pack(fill="x", pady=(8, 0))
        tk.Checkbutton(right,
                       text="Also move files into the new folder",
                       variable=v_move, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9, "bold"), highlightthickness=0,
                       anchor="w").pack(fill="x")
        wrow = tk.Frame(right, bg=C_BG3)
        wrow.pack(fill="x", padx=20)
        for val, text in (("previous_month", "last month's files"),
                          ("current_month", "this month's files"),
                          ("custom", "a date range:")):
            tk.Radiobutton(wrow, text=text, value=val, variable=v_window,
                           bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                           activebackground=C_BG3, activeforeground=C_FG,
                           font=("Segoe UI", 9),
                           highlightthickness=0).pack(side="left")
        crow = tk.Frame(right, bg=C_BG3)
        crow.pack(fill="x", padx=20, pady=2)
        e_from = tk.Entry(crow, bg=C_BG2, fg=C_FG, relief="flat", width=12,
                          insertbackground=C_ACCENT, font=("Segoe UI", 9),
                          insertofftime=0, insertontime=9999999)
        no_blink(e_from); e_from.pack(side="left", ipady=2)
        tk.Label(crow, text=" to ", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left")
        e_to = tk.Entry(crow, bg=C_BG2, fg=C_FG, relief="flat", width=12,
                        insertbackground=C_ACCENT, font=("Segoe UI", 9),
                        insertofftime=0, insertontime=9999999)
        no_blink(e_to); e_to.pack(side="left", ipady=2)
        tk.Label(crow, text="  (YYYY-MM-DD)", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(side="left")

        tk.Label(right,
                 text="A file's date comes from a date in its NAME first "
                      "(your prefix rules put one there), and only then from "
                      "its timestamp. Files are never overwritten and folders "
                      "are never moved.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w",
                 justify="left", wraplength=430).pack(fill="x", pady=(8, 0))

        def _refresh(sel=None):
            lb.delete(0, "end")
            for p in store.get("plans", []):
                mark = "" if p.get("enabled", True) else "  (off)"
                lb.insert("end", (p.get("name") or "(unnamed)") + mark)
            if sel is not None and 0 <= sel < lb.size():
                lb.selection_set(sel)

        def _idx():
            cur = lb.curselection()
            return cur[0] if cur else -1

        def _load(event=None):
            i = _idx()
            if i < 0:
                return
            p = store["plans"][i]
            for e, val in ((e_name, p.get("name", "")),
                           (e_base, p.get("base_dir", "")),
                           (e_pat, p.get("pattern", "")),
                           (e_months, ", ".join(p.get("month_names") or [])),
                           (e_day, str(p.get("day_of_month", 1))),
                           (e_every, str(p.get("every_months", 1))),
                           (e_from, p.get("custom_from", "")[:10]),
                           (e_to, p.get("custom_to", "")[:10])):
                e.delete(0, "end"); e.insert(0, val)
            v_enabled.set(bool(p.get("enabled", True)))
            v_move.set(bool(p.get("move_files")))
            v_window.set(p.get("window", "previous_month"))

        lb.bind("<<ListboxSelect>>", _load)

        def _collect():
            name = e_name.get().strip()
            base = e_base.get().strip()
            if not name or not base:
                messagebox.showwarning("Automatic folders",
                                       "A name and a folder are required.",
                                       parent=top)
                return None
            try:
                day = max(1, min(28, int(e_day.get().strip() or "1")))
                every = max(1, int(e_every.get().strip() or "1"))
            except ValueError:
                messagebox.showwarning("Automatic folders",
                                       "Day and interval must be numbers.",
                                       parent=top)
                return None
            months = [m.strip() for m in e_months.get().split(",") if m.strip()]
            if months and len(months) != 12:
                messagebox.showwarning(
                    "Automatic folders",
                    f"Month names must be exactly 12 (you gave "
                    f"{len(months)}), or empty for English.", parent=top)
                return None
            i = _idx()
            rec = dict(_FOLDERPLAN_DEFAULTS)
            rec.update({
                "id": store["plans"][i]["id"] if i >= 0 else _new_id(),
                "name": name, "enabled": bool(v_enabled.get()),
                "base_dir": base,
                "pattern": e_pat.get().strip() or "{MM}-{MonthName}",
                "day_of_month": day, "every_months": every,
                "month_names": months,
                "move_files": bool(v_move.get()),
                "window": v_window.get(),
                "custom_from": e_from.get().strip(),
                "custom_to": e_to.get().strip(),
                "last_run": (store["plans"][i].get("last_run", "")
                             if i >= 0 else ""),
            })
            return rec

        def _save():
            rec = _collect()
            if rec is None:
                return
            i = _idx()
            if i >= 0:
                store["plans"][i] = rec
            else:
                store.setdefault("plans", []).append(rec)
            _save_folderplans(store)
            _refresh()
            self._flash("Folder plan saved")

        def _preview():
            rec = _collect()
            if rec is None:
                return
            res = _plan_run(rec, dry_run=True)
            if res["error"]:
                messagebox.showerror("Preview", res["error"], parent=top)
                return
            moved = res["moved"]
            text = (f"Folder that would be created:\n\n  {res['folder']}\n\n")
            if rec["move_files"]:
                text += (f"Files that would move into it: {len(moved)}\n\n" +
                         "\n".join("  • " + n for n in moved[:15]))
                if len(moved) > 15:
                    text += f"\n  … and {len(moved) - 15} more"
                if not moved:
                    text += "  (none matched the date range)"
            else:
                text += "No files would be moved."
            messagebox.showinfo("Preview — nothing has been done yet", text,
                                parent=top)

        def _run_now():
            rec = _collect()
            if rec is None:
                return
            res = _plan_run(rec, dry_run=True)
            if res["error"]:
                messagebox.showerror("Run now", res["error"], parent=top)
                return
            if not messagebox.askyesno(
                    "Run now",
                    f"Create:\n  {res['folder']}\n\n"
                    f"and move {len(res['moved'])} file(s) into it?",
                    parent=top):
                return
            real = _plan_run(rec)
            if real["error"]:
                messagebox.showerror("Run now", real["error"], parent=top)
                return
            _save()
            messagebox.showinfo(
                "Done",
                f"{real['folder']}\n\n{len(real['moved'])} file(s) moved.",
                parent=top)

        def _new():
            lb.selection_clear(0, "end")
            for e in (e_name, e_base, e_from, e_to, e_months):
                e.delete(0, "end")
            e_pat.delete(0, "end"); e_pat.insert(0, "{MM}-{MonthName}")
            e_day.delete(0, "end"); e_day.insert(0, "1")
            e_every.delete(0, "end"); e_every.insert(0, "1")
            v_enabled.set(True); v_move.set(True)
            v_window.set("previous_month")
            e_name.focus_set()

        def _delete():
            i = _idx()
            if i < 0:
                return
            if messagebox.askyesno(
                    "Delete plan",
                    f"Delete “{store['plans'][i].get('name','')}”?\n\n"
                    f"Folders and files already created are not touched.",
                    parent=top):
                del store["plans"][i]
                _save_folderplans(store)
                _refresh(); _new()

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(fill="x", padx=12, pady=(0, 10))
        for text, colour, cmd in (("Save", C_BTN_NEW, _save),
                                  ("Preview", C_BTN_LATER, _preview),
                                  ("Run now", C_BTN_STD, _run_now),
                                  ("New", C_BTN_STD, _new),
                                  ("Delete", C_BTN_DEL, _delete),
                                  ("Close", C_BTN_STD, top.destroy)):
            tk.Button(btns, text=text, bg=colour, fg=C_BTN_FG,
                      font=("Segoe UI", 9), relief="flat", cursor="hand2",
                      padx=12, pady=4, command=cmd).pack(side="left", padx=3)
        _refresh()
        _new()

    # ── Tags (DEL 04k) ────────────────────────────────────────────────────────
    def _tag_selected(self, index):
        """Keyboard 1-9: toggle the Nth tag on the selected message."""
        self._resync_selected_msg()
        if not self._selected_msg:
            return
        tags = self._tag_store.get("tags", [])
        if not (1 <= index <= len(tags)):
            return
        tag = tags[index - 1]
        on = _tag_toggle(self._tag_store, self._selected_msg, tag["id"])
        self._flash(f"{tag['icon']} {tag['name']} "
                    f"{'added' if on else 'removed'}")
        self._render_msg_list()
        if self._selected_msg:
            self._show_message_in_reading_pane(self._selected_msg)

    def _tags_popup(self, msg):
        """The tag menu for one message — tick what applies."""
        m = tk.Menu(self.root, tearoff=0, bg=C_BG2, fg=C_FG,
                    activebackground=C_BG4, activeforeground=C_FG)
        current = {t["id"] for t in _tags_of(self._tag_store, msg)}
        for i, tag in enumerate(self._tag_store.get("tags", []), start=1):
            mark = "✓ " if tag["id"] in current else "    "
            key  = f"   ({i})" if i <= 9 else ""
            m.add_command(
                label=f"{mark}{tag.get('icon','●')}  {tag['name']}{key}",
                command=lambda t=tag, mm=msg: self._apply_tag(mm, t))
        m.add_separator()
        m.add_command(label="Manage tags…", command=self._tags_dialog)
        try:
            m.tk_popup(self.root.winfo_pointerx(), self.root.winfo_pointery())
        finally:
            m.grab_release()

    def _apply_tag(self, msg, tag):
        on = _tag_toggle(self._tag_store, msg, tag["id"])
        self._flash(f"{tag['icon']} {tag['name']} "
                    f"{'added' if on else 'removed'}")
        self._render_msg_list()
        self._show_message_in_reading_pane(msg)

    def _tags_dialog(self):
        """Edit the tag list: name, colour, icon."""
        top = self._dialog_shell("Tags", 660, 520)
        store = self._tag_store

        tk.Label(top,
                 text="Tags are yours and stay on this computer. Press 1-9 on "
                      "a selected message to toggle the first nine.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 pady=4).pack(fill="x")

        body = tk.Frame(top, bg=C_BG3)
        body.pack(fill="both", expand=True, padx=12, pady=6)
        left = tk.Frame(body, bg=C_BG3)
        left.pack(side="left", fill="y")
        lb = self._listbox(left, width=26)
        lb.pack(fill="y", expand=True, pady=4)

        right = tk.Frame(body, bg=C_BG3)
        right.pack(side="left", fill="both", expand=True, padx=(12, 0))
        e_name = self._labelled_entry(right, "Name:", width=8)
        e_icon = self._labelled_entry(right, "Icon:", width=8)
        e_col  = self._labelled_entry(right, "Colour:", width=8)
        tk.Label(right,
                 text="Icon: one emoji or character, shown in the message "
                      "list.\nColour: #rrggbb — it tints the row.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w",
                 justify="left").pack(fill="x", pady=(4, 8))

        sw = tk.Frame(right, bg=C_BG3)
        sw.pack(fill="x")
        for c in ("#c0392b", "#d68910", "#27ae60", "#2980b9", "#8e44ad",
                  "#16a085", "#7f8c8d", "#b7950b"):
            b = tk.Label(sw, text="   ", bg=c, cursor="hand2", relief="raised",
                         bd=1)
            b.pack(side="left", padx=2)
            b.bind("<Button-1>", lambda e, cc=c: (e_col.delete(0, "end"),
                                                  e_col.insert(0, cc)))

        def _refresh(sel=None):
            lb.delete(0, "end")
            for i, t in enumerate(store.get("tags", []), start=1):
                n = sum(1 for ids in (store.get("assigned") or {}).values()
                        if t["id"] in ids)
                key = f"{i}. " if i <= 9 else "   "
                lb.insert("end", f"{key}{t.get('icon','●')} {t['name']}"
                                 f"   ({n})")
            if sel is not None and 0 <= sel < lb.size():
                lb.selection_set(sel)

        def _idx():
            cur = lb.curselection()
            return cur[0] if cur else -1

        def _load(event=None):
            i = _idx()
            if i < 0:
                return
            t = store["tags"][i]
            for e, k in ((e_name, "name"), (e_icon, "icon"), (e_col, "color")):
                e.delete(0, "end"); e.insert(0, t.get(k, ""))

        lb.bind("<<ListboxSelect>>", _load)

        def _save():
            name = e_name.get().strip()
            if not name:
                messagebox.showwarning("Tags", "Give the tag a name.",
                                       parent=top)
                return
            col = e_col.get().strip()
            if col and not _re.match(r'^#[0-9a-fA-F]{6}$', col):
                messagebox.showwarning("Tags", "Colour must look like #c0392b.",
                                       parent=top)
                return
            i = _idx()
            rec = {"id": store["tags"][i]["id"] if i >= 0 else _new_id(),
                   "name": name, "icon": e_icon.get().strip() or "●",
                   "color": col or "#7f8c8d"}
            if i >= 0:
                store["tags"][i] = rec
            else:
                store.setdefault("tags", []).append(rec)
            _save_tags(store)
            _refresh()
            self._render_msg_list()

        def _new():
            lb.selection_clear(0, "end")
            for e in (e_name, e_icon, e_col):
                e.delete(0, "end")
            e_name.focus_set()

        def _delete():
            i = _idx()
            if i < 0:
                return
            t = store["tags"][i]
            if not messagebox.askyesno(
                    "Delete tag",
                    f"Delete “{t['name']}”?\n\nIt is removed from every "
                    f"message that carries it. The messages themselves are "
                    f"not touched.", parent=top):
                return
            tid = t["id"]
            del store["tags"][i]
            for key, ids in list((store.get("assigned") or {}).items()):
                if tid in ids:
                    ids.remove(tid)
                    if not ids:
                        del store["assigned"][key]
            _save_tags(store)
            _refresh(); _new()
            self._render_msg_list()

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(fill="x", padx=12, pady=(0, 10))
        for text, colour, cmd in (("Save", C_BTN_NEW, _save),
                                  ("New", C_BTN_STD, _new),
                                  ("Delete", C_BTN_DEL, _delete),
                                  ("Close", C_BTN_STD, top.destroy)):
            tk.Button(btns, text=text, bg=colour, fg=C_BTN_FG,
                      font=("Segoe UI", 9), relief="flat", cursor="hand2",
                      padx=14, pady=4, command=cmd).pack(side="left", padx=4)
        _refresh()

    # ── Follow-ups (DEL 04j) ──────────────────────────────────────────────────
    def _followup_dialog(self, msg):
        """Set (or edit) the reminder for one message."""
        existing = None
        key = _msg_key(msg)
        for it in self._followup_store.get("items", []):
            if it.get("key") == key and (not it.get("done")
                                         or _followup_is_floating(it)):
                existing = it
                break
        FollowUpDialog(self.root, self, msg, existing=existing,
                       on_saved=self._followups_changed)

    def _followups_changed(self):
        if self._current_folder == "Follow-ups":
            self._render_followups()
        else:
            self._render_msg_list()       # also lifts / lets go of floating mail
            try:
                self._reconcile_folder_badge()
                self._repaint_badges()
            except Exception as e:
                log.debug("badge refresh after follow-up change failed: %s", e)

    def _apply_float_flags(self, msgs):
        """Floating mail (DEL 04j, 2026-11-23): a mail whose follow-up has come
        up and is not Done yet is UNREAD and "kept unread" (so opening it does
        not turn it read - same switch as the always-unread senders, local
        only) and carries _float, which the list uses to lift it to the top.
        When the follow-up ends the flags are taken away again. Safe to call
        any number of times."""
        try:
            fk = _followup_float_keys(self._followup_store)
        except Exception:
            return
        for m in msgs or []:
            if m.get("_note_path"):
                continue
            if _msg_key(m) in fk:
                m["_float"] = True
                m["_always_unread"] = True
                m["unread"] = True
            elif m.get("_float"):
                m["_float"] = False
                keep = (m.get("_folder") == "Inbox"
                        and _is_always_unread(self._blocklist_store, m))
                m["_always_unread"] = bool(keep)
                if not keep:
                    m["unread"] = False

    def _followup_resolve(self, item):
        """Done: stop reminding and let the mail go back to its place."""
        _followup_stop(self._followup_store, item.get("id", ""))
        self._flash("Reminder finished — the mail is back to normal")
        self._followups_changed()

    def _followup_resolve_msg(self, msg):
        """Done, from a message (reading pane / right-click)."""
        key = _msg_key(msg)
        n = 0
        for it in list(self._followup_store.get("items", [])):
            if (it.get("key") == key
                    and (not it.get("done") or _followup_is_floating(it))):
                _followup_stop(self._followup_store, it.get("id", ""))
                n += 1
        if n:
            self._flash("Reminder finished — the mail is back to normal")
            self._followups_changed()

    def _render_followups(self):
        """The list of messages you are not finished with."""
        rows = []
        for it in self._followup_store.get("items", []):
            nxt = _parse_iso(it.get("next_at", "") or "")
            final = _followup_is_final(it) and not it.get("done")
            rows.append({
                "id": it.get("id", ""), "thread_id": it.get("id", ""),
                "uid": it.get("uid") or None,
                "account_email": it.get("account", ""),
                "from": it.get("from", ""), "from_name": it.get("from_name", ""),
                "subject": it.get("subject", "(no subject)"),
                "date": nxt.strftime("%Y-%m-%d %H:%M") if nxt else "done",
                "_sortkey": nxt.timestamp() if nxt else 0.0,
                "_dt": it.get("next_at", ""),
                "body": (f"{it.get('note') or 'No note.'}\n\n"
                         f"{_followup_describe(it)}\n\n"
                         f"Originally in: {it.get('folder','')}  "
                         f"({it.get('account','')})\n"
                         f"Set on {(it.get('created') or '')[:16]}"
                         + ("\n\nThe NEXT reminder is the LAST one."
                            if final else "")),
                "unread": False,
                "starred": final,          # the last one stands out in the list
                "priority": "high" if final else "normal",
                "spam": False, "attachments": [], "_attachment_data": {},
                "_html": "", "_folder": "Follow-ups",
                "_followup": it,
            })
        rows.sort(key=lambda m: (m["_sortkey"] == 0.0, m["_sortkey"]))
        self._all_messages  = rows
        self._messages      = rows
        self._selected_msg  = None
        self._expanded_rows = set()
        self._search_active = False
        live = sum(1 for i in self._followup_store.get("items", [])
                   if not i.get("done"))
        self.lbl_folder.configure(text=f"  Follow-ups  ({live} active)")
        self._render_msg_list()
        self._show_reading_pane_empty()
        self._update_title()

    def _followup_tick(self):
        """Fire whatever is due. Called from the always-on ticker."""
        due = _followup_due(self._followup_store)
        if not due:
            return
        changed = False
        lifted = False
        for item in due:
            final = _followup_is_final(item)
            FollowUpReminder(self.root, self, dict(item), final)
            _followup_advance(item)
            changed = True
            if item.get("float") and not item.get("surfaced"):
                item["surfaced"] = _now_iso()        # the mail floats from now
                lifted = True
            if self.cfg.get("notify_sound", False):
                try:
                    import winsound
                    winsound.MessageBeep(winsound.MB_ICONEXCLAMATION)
                except Exception:
                    pass
        if changed:
            _save_followups(self._followup_store)
            if self._current_folder == "Follow-ups":
                self._render_followups()
            elif lifted:
                self._followups_changed()

    def _followup_keep_going(self, item):
        """"Keep reminding me" on the final popup: drop the ending and carry
        on with the same rhythm until stopped by hand."""
        for it in self._followup_store.get("items", []):
            if it.get("id") != item.get("id"):
                continue
            repeat = int(it.get("repeat_min") or 0) or 1440
            it["repeat_min"] = repeat
            it["max_count"]  = 0
            it["until"]      = ""
            it["done"]       = False
            it["next_at"]    = (datetime.now() + timedelta(minutes=repeat)
                                ).isoformat(timespec="seconds")
            break
        _save_followups(self._followup_store)
        self._flash("Still reminding — now until you stop it")
        self._followups_changed()

    def _open_followup_message(self, item):
        """Jump to the message a reminder is about."""
        try:
            self.root.deiconify(); self.root.lift(); self.root.focus_force()
        except Exception:
            pass
        acct   = item.get("account") or self._current_acct
        folder = item.get("folder") or "Inbox"
        if folder in _VIRTUAL_FOLDERS or not folder:
            folder = "Inbox"
        self._select_folder(acct if acct else self._current_acct, folder)
        # After the fetch lands, select the message if it is there.
        key = item.get("key", "")

        def _try_select(tries=12):
            for m in self._messages:
                if _msg_key(m) == key:
                    self._selected_msg = m
                    self._show_message_in_reading_pane(m)
                    return
            if tries > 0:
                self.root.after(400, lambda: _try_select(tries - 1))
        self.root.after(400, _try_select)

    def _snooze_from_pane(self, msg):
        when = _ask_send_time(self.root, self.root, purpose="snooze")
        if when is None:
            return
        self._snooze_message(msg, when)

    # ── Save one message as a PDF ─────────────────────────────────────────────
    def _save_msg_pdf(self, msg):
        from tkinter import filedialog
        default = _safe_name((msg.get("subject") or "message")[:60]) + ".pdf"
        path = filedialog.asksaveasfilename(
            parent=self.root, title="Save message as PDF",
            defaultextension=".pdf", initialfile=default,
            filetypes=[("PDF document", "*.pdf"), ("All files", "*.*")])
        if not path:
            return
        try:
            _write_simple_pdf(path, _message_to_pdf_blocks(msg))
        except Exception as e:
            log.error("PDF export failed: %s", e)
            messagebox.showerror("Save as PDF", f"Could not write the PDF:\n{e}",
                                 parent=self.root)
            return
        self._flash("PDF saved!")
        if messagebox.askyesno("Save as PDF", "PDF saved.\n\nOpen it now?",
                               parent=self.root):
            try:
                if platform.system() == "Windows":
                    open_path(path)
                elif platform.system() == "Darwin":
                    os.system(f'open "{path}"')
                else:
                    os.system(f'xdg-open "{path}"')
            except Exception as e:
                log.warning("Could not open PDF: %s", e)

    def _archive_out_of_inbox(self, msg, quiet=False):
        """Get a conversation out of the way once it is dealt with.

        Two honest modes, because the program will not pretend to move things
        on a server it is not allowed to touch:
          • server changes OFF — hidden from this view and tagged, so you can
            find it again; Gmail is untouched.
          • server changes ON  — a real IMAP move into the folder you named.
        """
        target = (self.cfg.get("archive_folder") or "Minbox").strip()
        tag_id = (self.cfg.get("archive_tag") or "").strip()

        if tag_id:
            have = {t["id"] for t in _tags_of(self._tag_store, msg)}
            if tag_id not in have:
                _tag_toggle(self._tag_store, msg, tag_id)

        # Filters that opted into the "when I archive" trigger (DEL 04z2) run
        # over this message now, while its original folder is still known.
        self._run_filters_on([msg], "archive")

        if (self.cfg.get("allow_server_changes", False)
                and not self._demo_mode and msg.get("uid")):
            account = msg.get("account_email", "")
            pwd = self._secret_for(account)
            if pwd:
                def worker():
                    problem = ""
                    try:
                        problem = _imap_move_message(
                            account, pwd, msg.get("_folder", "Inbox"),
                            msg.get("uid"), target)
                    except Exception as e:
                        problem = str(e)
                        log.error("Archive move failed: %s", e)

                    def done():
                        if problem:
                            messagebox.showwarning("Archive", problem,
                                                   parent=self.root)
                        else:
                            self._set_status(extra=f"moved to {target}")
                        self._refresh_messages()
                    try:
                        self.root.after(0, done)
                    except Exception:
                        pass
                threading.Thread(target=worker, daemon=True).start()
                return

        # Local mode: out of sight here, untouched on Gmail.
        if msg in self._messages:
            self._messages.remove(msg)
        if msg in self._all_messages:
            self._all_messages.remove(msg)
        self._push_undo("hide", "archived out of the inbox", [msg])
        self._selected_msg = None
        self._render_msg_list()
        self._show_reading_pane_empty()
        if not quiet:
            self._set_status(extra=f"archived locally (tagged, not moved)")

    def _archive_folder_dialog(self):
        """Name the folder that "Send & archive" uses."""
        from tkinter import simpledialog
        cur = self.cfg.get("archive_folder") or "Minbox"
        name = simpledialog.askstring(
            "Archive folder",
            "Which folder should “Send & archive” put things in?\n\n"
            "Your own name for it — Minbox, Klart, Handled…\n\n"
            "With Tools → Server changes OFF this is only a local tag; with "
            "it ON the message is really moved there on Gmail (and the "
            "folder is created if it does not exist).",
            parent=self.root, initialvalue=cur)
        if name:
            self.cfg["archive_folder"] = name.strip()
            _save_settings(self.cfg)
            self._flash(f"Archive folder: {name.strip()}")

    def _save_thread_pdf(self, msg):
        """The whole conversation as one PDF, oldest first — which is how you
        would want to read it back, or hand it to someone else."""
        from tkinter import filedialog
        tid = self._effective_tid(msg)
        thread = sorted([m for m in self._messages
                         if self._effective_tid(m) == tid],
                        key=_thread_order)
        if not thread:
            thread = [msg]
        default = _safe_name((msg.get("subject") or "thread")[:50]) + \
            f" ({len(thread)} messages).pdf"
        path = filedialog.asksaveasfilename(
            parent=self.root, title="Save the conversation as PDF",
            defaultextension=".pdf", initialfile=default,
            filetypes=[("PDF document", "*.pdf"), ("All files", "*.*")])
        if not path:
            return
        blocks = [("title", msg.get("subject", "(no subject)")),
                  ("head", f"{len(thread)} messages  ·  exported "
                           f"{datetime.now().strftime('%Y-%m-%d %H:%M')}"),
                  ("body", "=" * _PDF_WRAP)]
        for i, m in enumerate(thread, start=1):
            blocks.append(("head",
                           f"\n[{i}/{len(thread)}]  "
                           f"{m.get('from_name','')} <{m.get('from','')}>\n"
                           f"{m.get('date','')}"))
            if m.get("attachments"):
                blocks.append(("head", "Files: " + ", ".join(m["attachments"])))
            blocks.append(("body", "-" * _PDF_WRAP))
            blocks.append(("body", m.get("body", "")))
        try:
            _write_simple_pdf(path, blocks)
        except Exception as e:
            log.error("Thread PDF failed: %s", e)
            messagebox.showerror("Thread as PDF", f"Could not write:\n{e}",
                                 parent=self.root)
            return
        self._flash(f"{len(thread)} messages saved as one PDF")
        if messagebox.askyesno("Thread as PDF", "Saved.\n\nOpen it now?",
                               parent=self.root):
            self._open_path_file(path)

    def _open_path_file(self, path):
        try:
            if platform.system() == "Windows":
                open_path(path)
            elif platform.system() == "Darwin":
                os.system(f'open "{path}"')
            else:
                os.system(f'xdg-open "{path}"')
        except Exception as e:
            log.warning("Could not open %s: %s", path, e)

    # ── Unsubscribe, with choices ─────────────────────────────────────────────
    def _unsub_menu_label(self) -> str:
        n = len(self._unsub_store.get("queue", []))
        return (f"Unsubscribes waiting  ({n})…" if n
                else "Unsubscribes waiting…")

    def _refresh_unsub_menu(self):
        """Keep the Tools-menu count honest after the queue changes."""
        try:
            self._m_tools.entryconfigure(self._unsub_menu_index,
                                         label=self._unsub_menu_label())
        except Exception:
            pass        # menu not built yet, or already torn down

    # ── DEL 04e2 — what a RULE asked for ─────────────────────────────────────
    def _handle_filter_unsubs(self, stats):
        """Act on the unsubscribes the filter run collected.

        Three gates, in this order, and each one is the reason the next is
        safe to have at all:
          1. Already unsubscribed from this list?  Do nothing. The log is what
             stops a rule firing again on every straggler.
          2. Is there a route at all?  A rule can only unsubscribe from mail
             that carries a way to.
          3. "auto" only ever uses a route the SENDER declared in a header
             (RFC 8058 one-click, or the List-Unsubscribe mailto:). A link
             scraped out of the body is this program's guess, and guesses do
             not get to talk to somebody else's server unattended — those
             drop back to the queue, with the reason recorded."""
        items = stats.get("unsubs") or []
        if not items:
            return
        store   = self._unsub_store
        changed = False
        added   = 0
        for it in items:
            msg  = it.get("msg") or {}
            mode = it.get("mode", "offer")
            rule = it.get("rule", "")
            if _unsub_already_done(store, msg):
                continue
            unsub = _find_unsubscribe(msg)
            if not (unsub.get("mailto") or unsub.get("http")):
                continue
            from_header = unsub.get("source") == "header"
            if mode == "auto" and from_header:
                if unsub.get("one_click") and unsub.get("http"):
                    log.info("rule '%s': one-click unsubscribe from %s",
                             rule, msg.get("from", ""))
                    self._unsub_one_click_ui(msg, unsub["http"], silent=True,
                                             rule=rule)
                    self._activity_log(
                        "unsubscribe", account=msg.get("account_email", ""),
                        sender=msg.get("from", ""),
                        subject=msg.get("subject", ""), rule=rule,
                        detail="one-click (RFC 8058), sent automatically")
                    continue
                if unsub.get("mailto"):
                    account = msg.get("account_email") or ""
                    self.queue_send({
                        "from": account, "to": unsub["mailto"], "cc": "",
                        "subject": unsub["mailto_subject"],
                        "body": "Please unsubscribe this address from your "
                                "list.\n",
                        "attachments": [], "draft_id": "",
                    }, when=None, kind="unsubscribe")
                    self._record_unsubscribe(
                        msg, "e-mail (rule)", url="mailto:" + unsub["mailto"],
                        result="queued in the outbox", rule=rule)
                    self._activity_log(
                        "unsubscribe", account=account,
                        sender=msg.get("from", ""),
                        subject=msg.get("subject", ""), rule=rule,
                        detail=f"unsubscribe e-mail queued to "
                               f"{unsub['mailto']}")
                    continue
            # Everything else waits for you.
            if _unsub_queued(store, msg):
                continue
            why = ""
            if mode == "auto" and not from_header:
                why = ("automatic was asked for, but this message has no "
                       "List-Unsubscribe header — only a link found in the "
                       "text, which is never followed unattended")
            store.setdefault("queue", []).append({
                "key":        _unsub_key(msg),
                "sender":     parseaddr(msg.get("from", ""))[1]
                              or msg.get("from", ""),
                "from_name":  msg.get("from_name", ""),
                "subject":    msg.get("subject", ""),
                "account":    msg.get("account_email", ""),
                "rule":       rule,
                "url":        unsub.get("http", ""),
                "mailto":     unsub.get("mailto", ""),
                "one_click":  bool(unsub.get("one_click")),
                "list_unsub": msg.get("_list_unsub", ""),
                "list_unsub_post": msg.get("_list_unsub_post", ""),
                "why":        why,
                "added":      _now_iso(),
            })
            changed = True
            added  += 1
        if changed:
            _save_unsubs(store)
            self._refresh_unsub_menu()
            n = len(store.get("queue", []))
            self._flash(f"{added} more to unsubscribe from ({n} waiting)")
            log.info("unsubscribe queue: +%d (%d waiting)", added, n)

    # ── DEL 04e2 — unsubscribing, and remembering that you did ───────────────
    def _record_unsubscribe(self, msg, route, url="", result="", rule=""):
        """Write one unsubscribe into the log, and take it off the queue.

        The log is what stops a rule offering the same list over and over: a
        newsletter keeps arriving for days after you leave it, and a rule that
        re-fired on every one of those would be indistinguishable from a rule
        that does not work."""
        store = self._unsub_store
        key = _unsub_key(msg)
        store.setdefault("done", []).append({
            "key":       key,
            "sender":    parseaddr(msg.get("from", ""))[1]
                         or msg.get("from", ""),
            "from_name": msg.get("from_name", ""),
            "subject":   msg.get("subject", ""),
            "account":   msg.get("account_email", ""),
            "route":     route,
            "url":       (url or "")[:400],
            "result":    result,
            "rule":      rule,
            "when":      _now_iso(),
        })
        store["queue"] = [q for q in store.get("queue", [])
                          if q.get("key") != key]
        _save_unsubs(store)
        self._refresh_unsub_menu()
        log.info("unsubscribe recorded: %s via %s (%s)",
                 msg.get("from", ""), route, result or "ok")

    def _unsub_route_options(self, msg, unsub):
        """The ways out of this list, smoothest first.

        Each is (value, label, hint). Only routes this message actually has
        are offered — an option that cannot work is worse than no option."""
        opts = []
        if unsub.get("one_click"):
            opts.append((
                "oneclick", "⚡  One click — no page, no browser",
                "The sender ships the RFC 8058 header, which is them saying "
                "“one request to this address is enough”. F(re)email sends "
                "exactly that request and tells you what came back. Nothing "
                "opens."))
        if unsub.get("http"):
            opts.append((
                "mini", "🪟  Open the page here, in F(re)email",
                "A small built-in view: the page's text and its buttons, no "
                "JavaScript, no images, no cookies kept afterwards. Your real "
                "browser and its logins are not involved."))
            opts.append((
                "browser", "🌐  Open the page in my real browser",
                "The old behaviour. Use it when the page needs JavaScript — "
                "the mini view will tell you when it does."))
        if unsub.get("mailto"):
            opts.append((
                "mail", "✉  Send an unsubscribe e-mail",
                f"An ordinary outgoing message to {unsub['mailto']}, through "
                f"the outbox like anything else you send."))
        return opts

    def _unsubscribe_dialog(self, msg):
        """Unsubscribe from a mailing list — and decide what else should
        happen to this sender at the same time.

        Nothing here happens behind your back: every route says what it will
        do before it does it, a mailto: unsubscribe goes through the outbox
        like any other message you send, and no web page is contacted until
        you pick a route and press Continue."""
        unsub = _find_unsubscribe(msg)
        if not (unsub.get("mailto") or unsub.get("http")):
            messagebox.showinfo(
                "Unsubscribe",
                "No unsubscribe address was found in this message.\n\n"
                "Neither a List-Unsubscribe header, nor an unsubscribe link "
                "in the text, nor a link whose address looks like one.\n\n"
                "“🌐 Links…” on the message shows every link it does have.",
                parent=self.root)
            return

        sender = msg.get("from", "")
        already = _unsub_already_done(self._unsub_store, msg)
        opts = self._unsub_route_options(msg, unsub)

        top = tk.Toplevel(self.root)
        top.title("Unsubscribe")
        top.configure(bg=C_BG3)
        top.transient(self.root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())
        # Height is worked out from the content at the end of this method, not
        # guessed here (Issu 2026-08-30: "Unsubscribepopup behöver bli högre.
        # Det syns nog alla val men inte delen med continue/save i botten").
        # This dialog's height is not fixed — it grows an extra block when the
        # list has already been unsubscribed from, another when the message
        # offers several links, and one route line per way out — so any single
        # number is wrong for some messages.

        # ── The buttons are packed FIRST, anchored to the bottom ─────────
        # Whatever else runs out of room, it cannot be these: Tk gives packed
        # space in packing order, so the last thing packed is the first thing
        # to fall off the edge. They are filled in further down, once _go
        # exists — reserving the space is what matters, not when the children
        # arrive.
        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(side="bottom", fill="x", pady=10)
        tk.Frame(top, bg=C_SEP, height=1).pack(side="bottom", fill="x")

        # …and everything above them scrolls, so even on a short screen every
        # choice can still be reached.
        host = tk.Frame(top, bg=C_BG3)
        host.pack(side="top", fill="both", expand=True)
        _sb = tk.Scrollbar(host, bg=C_BG3, troughcolor=C_BG1)
        _sb.pack(side="right", fill="y")        # before the canvas, or 1px wide
        _cv = tk.Canvas(host, bg=C_BG3, highlightthickness=0)
        _cv.pack(side="left", fill="both", expand=True)
        _sb.configure(command=_cv.yview)
        _cv.configure(yscrollcommand=_sb.set)
        page = tk.Frame(_cv, bg=C_BG3)
        _pw = _cv.create_window((0, 0), window=page, anchor="nw")
        page.bind("<Configure>",
                  lambda e: _cv.configure(scrollregion=_cv.bbox("all")))
        _cv.bind("<Configure>", lambda e: _cv.itemconfig(_pw, width=e.width))
        _bind_mousewheel(page, _cv)

        tk.Label(page, text="✖  Unsubscribe", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 13, "bold")).pack(pady=(14, 2))
        tk.Label(page, text=f"{msg.get('from_name','') or sender}  <{sender}>",
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 9),
                 wraplength=560).pack()

        if already:
            note = tk.Frame(page, bg="#5a4a1a", padx=12, pady=6)
            note.pack(fill="x", padx=20, pady=(8, 0))
            when = (already.get("when", "") or "")[:16].replace("T", " ")
            tk.Label(note,
                     text=f"↺  You already unsubscribed from this list on "
                          f"{when} ({already.get('route','')}).",
                     bg="#5a4a1a", fg="#ffe6a0",
                     font=("Segoe UI", 9, "bold"), anchor="w",
                     justify="left", wraplength=540).pack(fill="x")
            tk.Label(note,
                     text="Some senders take days to stop, and some ignore it "
                          "entirely. Doing it again is harmless — but if this "
                          "list keeps arriving, a rule that trashes it is the "
                          "thing that actually works.",
                     bg="#5a4a1a", fg="#e8dcb8", font=("Segoe UI", 8),
                     anchor="w", justify="left",
                     wraplength=540).pack(fill="x")

        tk.Label(page, text=f"(route found in the {unsub.get('source','')} "
                            f"of the message)",
                 bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8, "italic")).pack(pady=(6, 0))

        # ── Which link, when the message offers more than one ────────────
        v_url = tk.StringVar(value=unsub.get("http", ""))
        cands = [(u, t) for u, t in (unsub.get("candidates") or [])
                 if u.lower().startswith(("http://", "https://"))]
        if unsub.get("http") and not any(
                u == unsub["http"] for u, _t in cands):
            cands.insert(0, (unsub["http"], "from the List-Unsubscribe header"))
        if len(cands) > 1:
            lf = tk.Frame(page, bg=C_BG3, padx=20)
            lf.pack(fill="x", pady=(8, 0))
            tk.Label(lf, text="This message has more than one unsubscribe-"
                              "looking link. Use:",
                     bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "bold"),
                     anchor="w", justify="left",
                     wraplength=560).pack(fill="x")
            for u, t in cands[:6]:
                tk.Radiobutton(
                    lf, text=f"{(t or 'link')[:44]}   —   {u[:64]}"
                             f"{'…' if len(u) > 64 else ''}",
                    value=u, variable=v_url, bg=C_BG3, fg=C_FG,
                    selectcolor=C_BG2, activebackground=C_BG3,
                    activeforeground=C_FG, font=("Segoe UI", 8),
                    highlightthickness=0, anchor="w", justify="left",
                    wraplength=540).pack(fill="x")

        tk.Frame(page, bg=C_SEP, height=1).pack(fill="x", padx=20, pady=8)

        # ── HOW ──────────────────────────────────────────────────────────
        tk.Label(page, text="How:", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 9, "bold"), anchor="w",
                 padx=20).pack(fill="x")
        route = tk.StringVar(value=opts[0][0])
        rbody = tk.Frame(page, bg=C_BG3)
        rbody.pack(fill="x", padx=20)
        for value, label, hint in opts:
            tk.Radiobutton(rbody, text=label, value=value, variable=route,
                           bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                           activebackground=C_BG3, activeforeground=C_FG,
                           font=("Segoe UI", 9, "bold"), anchor="w",
                           highlightthickness=0,
                           relief="flat").pack(fill="x", pady=(6, 0))
            tk.Label(rbody, text=hint, bg=C_BG3, fg=C_FG_DIM,
                     font=("Segoe UI", 8), anchor="w", justify="left",
                     wraplength=520).pack(fill="x", padx=24)

        tk.Frame(page, bg=C_SEP, height=1).pack(fill="x", padx=20, pady=8)

        # ── AND ALSO ─────────────────────────────────────────────────────
        tk.Label(page, text="And also:", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 9, "bold"), anchor="w",
                 padx=20).pack(fill="x")

        # …get rid of the mail itself. ON by default (Issu 2026-08-30: "det
        # behöver ju också vara ett default ON '…and delete the mail', som man
        # antagligen (men inte säkert) vill, efter man klickat unsubscribe").
        # Separate from the four choices below because it is not one of them —
        # you may well want to block the sender AND bin this message. Your
        # answer is remembered, so unticking it once makes it stay unticked.
        # It never erases anything: with server changes on it is a move to the
        # Gmail Trash with an Undo button, and with them off it only hides the
        # message here.
        _server_del = bool(self.cfg.get("allow_server_changes", False)) \
            and not self._demo_mode and bool(msg.get("uid"))
        _self_msg = _is_self_message(msg)
        _is_note  = bool(msg.get("_note_path"))
        v_del = tk.BooleanVar(
            value=bool(self.cfg.get("unsub_delete_after", True))
            and not (_self_msg or _is_note))
        drow = tk.Frame(page, bg=C_BG3)
        drow.pack(fill="x", padx=20, pady=(6, 0))
        cb_del = tk.Checkbutton(
            drow,
            text=("🗑  …and delete this message"
                  + ("  (to the Gmail Trash — with Undo)" if _server_del
                     else "  (hide it here; Server changes is off)")),
            variable=v_del, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
            activebackground=C_BG3, activeforeground=C_FG,
            font=("Segoe UI", 9, "bold"), highlightthickness=0,
            anchor="w", relief="flat")
        cb_del.pack(fill="x")
        if _self_msg or _is_note:
            # The two things this must never touch. A Gmail message you sent
            # to yourself is ONE message wearing both Inbox and Sent, so
            # trashing it takes it out of both; a note is a file on his own
            # disk. Neither is something an unsubscribe gets to remove.
            v_del.set(False)
            cb_del.configure(state="disabled", fg=C_FG_DIM)
            tk.Label(drow,
                     text=("     a message you sent to yourself is never "
                           "deleted by this — on Gmail it is one message "
                           "wearing two labels" if _self_msg else
                           "     a note is a file on your own disk, not mail"),
                     bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 7, "italic"),
                     anchor="w", justify="left",
                     wraplength=520).pack(fill="x")
        else:
            tk.Label(drow,
                     text="     Remembered for next time. Nothing is erased: "
                          + ("the message goes to the Gmail Trash (30 days, "
                             "recoverable) and an Undo button holds it for a "
                             "minute." if _server_del else
                             "it is only hidden from this list — Gmail is "
                             "untouched."),
                     bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 7, "italic"),
                     anchor="w", justify="left",
                     wraplength=520).pack(fill="x")

        tk.Label(page, text="…and about the sender:", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8, "bold"), anchor="w",
                 padx=20).pack(fill="x", pady=(10, 0))
        choice = tk.StringVar(value="only")
        opts2 = [
            ("only",   "Nothing else",
             "Ask the sender to stop. Nothing else changes."),
            ("block",  "Block this sender",
             "Also hide everything from this sender from now on (local "
             "block list — nothing is deleted and Gmail is untouched)."),
            ("spam",   "Mark as spam",
             "Also flag this sender as spam here. Phase 1 is read-only, so "
             "this is local; real Gmail spam reporting comes in Phase 2."),
            ("rule",   "Set up my own rule",
             "Also open the filter editor with this sender filled in, so you "
             "can decide exactly what should happen — including “unsubscribe "
             "from anything else this sender ever sends”."),
        ]
        body = tk.Frame(page, bg=C_BG3)
        body.pack(fill="both", expand=True, padx=20)
        for value, label, hint in opts2:
            tk.Radiobutton(body, text=label, value=value, variable=choice,
                           bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                           activebackground=C_BG3, activeforeground=C_FG,
                           font=("Segoe UI", 9, "bold"), anchor="w",
                           highlightthickness=0,
                           relief="flat").pack(fill="x", pady=(4, 0))
            tk.Label(body, text=hint, bg=C_BG3, fg=C_FG_DIM,
                     font=("Segoe UI", 8), anchor="w", justify="left",
                     wraplength=520).pack(fill="x", padx=24)

        tk.Label(page,
                 text="An unsubscribe link is also a way for a sender to "
                      "confirm that your address is live. For real spam, "
                      "block it instead — never ask a spammer to stop.",
                 bg=C_BG3, fg="#e0b050", font=("Segoe UI", 8, "italic"),
                 anchor="w", justify="left",
                 wraplength=560).pack(fill="x", padx=20, pady=(8, 10))

        def _go():
            action = choice.get()
            r      = route.get()
            picked = v_url.get() or unsub.get("http", "")
            delete = bool(v_del.get())
            if not (_self_msg or _is_note):
                self.cfg["unsub_delete_after"] = delete
                _save_settings(self.cfg)
            top.destroy()
            self._do_unsubscribe(msg, unsub, action, route=r, url=picked,
                                 delete=delete)

        tk.Button(btns, text="Continue", bg=C_BTN_NEW, fg=C_BTN_FG,
                  font=("Segoe UI", 10, "bold"), relief="flat", cursor="hand2",
                  padx=18, pady=5, command=_go).pack(side="left", padx=(24, 5))
        tk.Button(btns, text="Cancel", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 10), relief="flat", cursor="hand2",
                  padx=18, pady=5, command=top.destroy).pack(side="left",
                                                             padx=5)
        top.bind("<Return>", lambda e: _go())

        # ── Now that the content exists, make the window fit it ──────────
        # Measured, not guessed, and clamped to the screen — on a short screen
        # the scroller above takes the strain instead of the buttons falling
        # off the bottom.
        top.update_idletasks()
        need = (page.winfo_reqheight() + btns.winfo_reqheight() + 24)
        # 0.86, not 0.95: winfo_screenheight() is the whole screen, taskbar
        # included, so a window sized to "nearly all of it" has its last inch
        # underneath the taskbar — which is precisely where the buttons are.
        h = max(430, min(need, int(top.winfo_screenheight() * 0.86)))
        _center_over(top, self.root, 640, h)
        top.resizable(False, True)      # width is fixed (the wraplengths
                                        # assume it); height is his to drag

    def _do_unsubscribe(self, msg, unsub, action, route="", url="",
                        delete=False):
        sender = msg.get("from", "")
        done   = []
        url    = url or unsub.get("http", "")
        if not route:
            route = ("mail" if unsub.get("mailto") else
                     "oneclick" if unsub.get("one_click") else "mini")

        # ── 1. The unsubscribe itself ────────────────────────────────────
        if route == "mail" and unsub.get("mailto"):
            account = msg.get("account_email") or (
                self._accounts[1]["email"] if len(self._accounts) > 1 else "")
            if messagebox.askyesno(
                    "Send unsubscribe request",
                    f"Send an unsubscribe e-mail?\n\n"
                    f"To:      {unsub['mailto']}\n"
                    f"From:    {account}\n"
                    f"Subject: {unsub['mailto_subject']}\n\n"
                    f"This is an ordinary outgoing message and goes through "
                    f"the outbox.", parent=self.root):
                self.queue_send({
                    "from": account, "to": unsub["mailto"], "cc": "",
                    "subject": unsub["mailto_subject"],
                    "body": "Please unsubscribe this address from your list.\n",
                    "attachments": [], "draft_id": "",
                }, when=None, kind="unsubscribe")
                self._record_unsubscribe(msg, "e-mail",
                                         url="mailto:" + unsub["mailto"],
                                         result="queued in the outbox")
                done.append("unsubscribe e-mail queued")
        elif route == "oneclick" and url:
            self._unsub_one_click_ui(msg, url)
            done.append("one-click unsubscribe sent")
        elif route == "mini" and url:
            MiniWebWindow(self, url, title="Unsubscribe", msg=msg,
                          prefill_email=msg.get("account_email", ""))
            done.append("page opened here")
        elif route == "browser" and url:
            if messagebox.askyesno(
                    "Open unsubscribe page",
                    f"Open this address in your browser?\n\n{url}\n\n"
                    f"Check that it looks like it belongs to the sender before "
                    f"you continue — an unsubscribe link is also a way to "
                    f"confirm that your address is live.", parent=self.root):
                try:
                    # Opens with the login belonging to the account this
                    # newsletter arrived at (DEL 04o).
                    self._open_url(url, msg=msg)
                    self._record_unsubscribe(msg, "real browser", url=url,
                                             result="page opened")
                    done.append("unsubscribe page opened")
                except Exception as e:
                    log.error("Could not open unsubscribe URL: %s", e)

        # ── 2. Whatever else was chosen ──────────────────────────────────
        if action == "block" and sender:
            self._blocklist_store.setdefault("blocked", []).append(
                {"match": sender, "added": _now_iso(),
                 "reason": "unsubscribe"})
            _save_blocklist(self._blocklist_store)
            done.append("sender blocked locally")
        elif action == "spam" and sender:
            self._blocklist_store.setdefault("spam", []).append(
                {"match": sender, "added": _now_iso(),
                 "reason": "unsubscribe"})
            _save_blocklist(self._blocklist_store)
            done.append("sender marked as spam locally")
        elif action == "rule":
            self._filters_dialog(prefill_from=sender)
            done.append("filter editor opened")

        # ── 3. …and the message itself ───────────────────────────────────
        # Last, so an unsubscribe that needed the message (the mini view holds
        # on to it) has already been started. Deliberately routed through the
        # ordinary delete path, which is where all the safeguards live: it is a
        # move to the Gmail Trash with an Undo button, never an erase, and it
        # falls back to hiding the message locally when Server changes is off.
        if delete and not _is_self_message(msg) and not msg.get("_note_path"):
            try:
                if (self.cfg.get("allow_server_changes", False)
                        and not self._demo_mode and msg.get("uid")):
                    self._delete_on_server(msg)
                    done.append("message → Trash (Undo available)")
                else:
                    self._soft_delete([msg], permanent=False, server=False)
                    done.append("message hidden here")
            except Exception as e:
                log.error("unsubscribe: could not delete the message: %s", e)
                done.append("could not delete the message — see the log")

        if done:
            self._flash("Done: " + ", ".join(done))
        if action in ("block", "spam"):
            self._refresh_messages()

    def _unsub_one_click_ui(self, msg, url, silent=False, rule=""):
        """Fire an RFC 8058 one-click unsubscribe and report what came back.

        Runs on a worker thread: this is a network round-trip to somebody
        else's server and it must never freeze the mail window. `silent` is
        for the rule engine, which reports through the filter log instead of a
        popup."""
        # The worker leaves the answer in a box and the MAIN thread collects
        # it on a timer, for the same reason MiniWebWindow does (see _poll):
        # after() called FROM a worker only works while the main thread sits
        # in mainloop(), and swallowing the RuntimeError it otherwise raises
        # would lose the one report saying whether the unsubscribe worked.
        box = {}

        def _work():
            box["res"] = _unsub_one_click(url)

        def _collect():
            if "res" not in box:
                self.root.after(120, _collect)
                return
            _tell(box["res"])

        def _tell(res):
            ok  = res.get("ok")
            said = (res.get("text") or "").strip().replace("\r", "")
            said = "\n".join([l for l in said.split("\n") if l.strip()][:8])
            self._record_unsubscribe(
                msg, "one-click", url=url, rule=rule,
                result=(f"HTTP {res.get('status', 0)}"
                        + ("" if ok else "  — " + (res.get("error") or "failed"))))
            if silent:
                self._flash("Unsubscribed (one click)" if ok
                            else "One-click unsubscribe failed")
                return
            if ok:
                messagebox.showinfo(
                    "Unsubscribed",
                    f"Sent. The server answered {res.get('status', 0)}.\n\n"
                    + (f"It said:\n\n{said[:600]}\n\n" if said else "")
                    + "Newsletters often keep arriving for a few days — that "
                      "is the sender's queue emptying, not a failure.",
                    parent=self.root)
            else:
                if messagebox.askyesno(
                        "One-click did not work",
                        f"{res.get('error') or 'The server refused it.'}\n\n"
                        f"HTTP {res.get('status', 0)} from\n{url[:120]}\n\n"
                        f"Open the page in the mini view instead?",
                        parent=self.root):
                    MiniWebWindow(self, url, title="Unsubscribe", msg=msg,
                                  prefill_email=msg.get("account_email", ""))

        self._set_status(extra="unsubscribing…")
        threading.Thread(target=_work, daemon=True).start()
        self.root.after(120, _collect)

    # ── The queue: unsubscribes a rule collected for you ─────────────────────
    def _unsub_queue_dialog(self):
        """Everything a rule flagged as "this one has an unsubscribe link".

        A rule set to "offer" never contacts anyone by itself — it only puts
        the list here, so leaving a shop's newsletter is one pass through this
        window instead of hunting through a month of mail for the link."""
        store = self._unsub_store
        top = self._dialog_shell("Unsubscribes waiting", 820, 620)

        tk.Label(top,
                 text="Rules with “offer to unsubscribe” put lists here "
                      "instead of acting on their own. Nothing below has been "
                      "contacted yet.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9), wraplength=760,
                 justify="left", pady=6).pack(fill="x", padx=14)

        wrap = tk.Frame(top, bg=C_BG2)
        wrap.pack(fill="both", expand=True, padx=14, pady=(0, 6))
        sb = tk.Scrollbar(wrap, bg=C_BG3, troughcolor=C_BG1)
        sb.pack(side="right", fill="y")
        canvas = tk.Canvas(wrap, bg=C_BG2, highlightthickness=0)
        canvas.pack(side="left", fill="both", expand=True)
        sb.configure(command=canvas.yview)
        canvas.configure(yscrollcommand=sb.set)
        inner = tk.Frame(canvas, bg=C_BG2)
        win = canvas.create_window((0, 0), window=inner, anchor="nw")
        inner.bind("<Configure>",
                   lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
        canvas.bind("<Configure>",
                    lambda e: canvas.itemconfig(win, width=e.width))
        _bind_mousewheel(inner, canvas)

        def _drop(key):
            store["queue"] = [q for q in store.get("queue", [])
                              if q.get("key") != key]
            _save_unsubs(store)
            self._refresh_unsub_menu()
            _paint()

        def _act(q):
            """Re-open the real dialog for the message this came from."""
            m = self._find_message_by_key(q.get("key"), q)
            if m is None:
                # The mail has been trashed or aged out of the cache; the
                # route was saved with the queue entry, so it still works.
                fake = {"from": q.get("sender", ""),
                        "from_name": q.get("from_name", ""),
                        "subject": q.get("subject", ""),
                        "account_email": q.get("account", ""),
                        "_list_unsub": q.get("list_unsub", ""),
                        "_list_unsub_post": q.get("list_unsub_post", ""),
                        "_html": "", "body": ""}
                m = fake
            self._unsubscribe_dialog(m)
            top.after(400, _paint)

        def _paint():
            for w in inner.winfo_children():
                w.destroy()
            queue = store.get("queue", [])
            if not queue:
                tk.Label(inner, text="Nothing waiting.", bg=C_BG2,
                         fg=C_FG_DIM, font=("Segoe UI", 10),
                         pady=24).pack()
                return
            for q in list(queue):
                row = tk.Frame(inner, bg=C_BG2, padx=10, pady=6)
                row.pack(fill="x")
                tk.Label(row, text=f"{q.get('from_name') or q.get('sender','')}"
                                   f"   <{q.get('sender','')}>",
                         bg=C_BG2, fg=C_FG, font=("Segoe UI", 9, "bold"),
                         anchor="w").pack(fill="x")
                bits = []
                if q.get("one_click"):
                    bits.append("⚡ one-click available")
                if q.get("url"):
                    bits.append("web page")
                if q.get("mailto"):
                    bits.append("e-mail")
                tk.Label(row,
                         text=f"   {q.get('subject','')[:70]}   ·   "
                              f"{', '.join(bits) or 'link in the message'}"
                              f"   ·   flagged by “{q.get('rule','')}”",
                         bg=C_BG2, fg=C_FG_DIM, font=("Segoe UI", 8),
                         anchor="w", justify="left",
                         wraplength=720).pack(fill="x")
                brow = tk.Frame(row, bg=C_BG2)
                brow.pack(fill="x", pady=(3, 0))
                tk.Button(brow, text="✖  Unsubscribe…", bg=C_BTN_NEW,
                          fg=C_BTN_FG, font=("Segoe UI", 8, "bold"),
                          relief="flat", cursor="hand2", padx=10, pady=2,
                          command=lambda x=q: _act(x)).pack(side="left")
                tk.Button(brow, text="Not now — forget it", bg=C_BTN_STD,
                          fg=C_BTN_FG, font=("Segoe UI", 8), relief="flat",
                          cursor="hand2", padx=10, pady=2,
                          command=lambda k=q.get("key"): _drop(k)
                          ).pack(side="left", padx=(6, 0))
                tk.Frame(inner, bg=C_SEP, height=1).pack(fill="x")

        _paint()
        br = tk.Frame(top, bg=C_BG3)
        br.pack(fill="x", pady=10)
        tk.Button(br, text="Clear the whole queue", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=12, pady=4,
                  command=lambda: (store.update({"queue": []}),
                                   _save_unsubs(store),
                                   self._refresh_unsub_menu(), _paint())
                  ).pack(side="left", padx=14)
        tk.Button(br, text="Close", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=16, pady=4, command=top.destroy).pack(side="right",
                                                             padx=14)

    def _find_message_by_key(self, key, q=None):
        """The loaded message an unsubscribe-queue entry came from, if it is
        still in memory. Returns None when it is not — the caller falls back
        to the route saved with the queue entry."""
        if not key:
            return None
        for m in (self._all_messages or []):
            try:
                if _unsub_key(m) == key:
                    return m
            except Exception:
                continue
        return None

    def _unsub_log_dialog(self):
        """Everything already unsubscribed from, newest first."""
        store = self._unsub_store
        top = self._dialog_shell("Unsubscribe log", 820, 600)
        tk.Label(top,
                 text="What has been unsubscribed, when, and how. This list is "
                      "also what stops a rule offering the same list twice.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9), wraplength=760,
                 justify="left", pady=6).pack(fill="x", padx=14)
        wrap = tk.Frame(top, bg=C_BG2)
        wrap.pack(fill="both", expand=True, padx=14, pady=(0, 6))
        sb = tk.Scrollbar(wrap, bg=C_BG3, troughcolor=C_BG1)
        sb.pack(side="right", fill="y")
        lst = tk.Listbox(wrap, bg=C_BG2, fg=C_FG, highlightthickness=0,
                         relief="flat", activestyle="none",
                         font=("Consolas", 9), yscrollcommand=sb.set)
        sb.configure(command=lst.yview)
        lst.pack(side="left", fill="both", expand=True)
        rows = list(reversed(store.get("done", [])))
        if not rows:
            lst.insert("end", "   (nothing yet)")
        for d in rows:
            lst.insert("end",
                       f"  {(d.get('when','') or '')[:16].replace('T',' ')}  "
                       f"{(d.get('sender','') or '')[:38]:38}  "
                       f"{(d.get('route','') or '')[:14]:14}  "
                       f"{(d.get('result','') or '')[:40]}")

        def _forget():
            sel = lst.curselection()
            if not sel or not rows:
                return
            d = rows[sel[0]]
            store["done"] = [x for x in store.get("done", []) if x is not d]
            _save_unsubs(store)
            top.destroy()
            self._unsub_log_dialog()

        br = tk.Frame(top, bg=C_BG3)
        br.pack(fill="x", pady=10)
        b = tk.Button(br, text="Forget the selected line", bg=C_BTN_STD,
                      fg=C_BTN_FG, font=("Segoe UI", 9), relief="flat",
                      cursor="hand2", padx=12, pady=4, command=_forget)
        b.pack(side="left", padx=14)
        add_tooltip(b, "Removes it from the log only. Rules will offer this "
                       "list again — use it when a sender ignored the "
                       "unsubscribe and you want to try another route.")
        tk.Button(br, text="Close", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=16, pady=4, command=top.destroy).pack(side="right",
                                                             padx=14)

    # ==========================================================================
    # DEL 09d — CALENDAR: window, reminder ticker, invitations from mail
    # ==========================================================================

    def _open_calendar(self, focus_date=None):
        """Open the calendar, or bring the already-open one to the front.

        It is a normal window, not a modal dialog — reading mail with the
        calendar next to it is the point."""
        if self._calendar_win is not None:
            try:
                if self._calendar_win.top.winfo_exists():
                    self._calendar_win.top.deiconify()
                    self._calendar_win.top.lift()
                    self._calendar_win.top.focus_force()
                    if focus_date is not None:
                        self._calendar_win.cursor = focus_date
                        self._calendar_win.selected = focus_date
                        self._calendar_win.render()
                    return
            except Exception:
                pass
            self._calendar_win = None
        self._calendar_win = CalendarWindow(self, self.root, self.cfg,
                                            self._calendar_store,
                                            focus_date=focus_date)

    def _new_event_dialog(self):
        EventEditor(self.root, self._calendar_store,
                    on_saved=self._calendar_refreshed)

    def _calendar_refreshed(self):
        """Redraw the calendar window (if open) after the store changed."""
        if self._calendar_win is not None:
            try:
                if self._calendar_win.top.winfo_exists():
                    self._calendar_win.render()
            except Exception:
                self._calendar_win = None

    # ── Reminder ticker ───────────────────────────────────────────────────────
    def _calendar_tick(self):
        """Every half minute: is any reminder due? Cheap — the whole calendar
        is a handful of dicts in memory."""
        if self._cal_after_id is not None:
            try:
                self.root.after_cancel(self._cal_after_id)
            except Exception:
                pass
            self._cal_after_id = None
        try:
            now = datetime.now()

            # 0a. Close the interactive IMAP connection when it has not been
            # used for a while, so the fast lane costs nothing while you are
            # not clicking (Issu 2026-08-08). Cheap and never fatal.
            try:
                _imap_reap_idle()
            except Exception as e:
                log.debug("idle connection reap failed: %s", e)

            # 0. Snoozed MAIL that is due again.
            #
            # This lives here, in the ticker that always runs, and not in the
            # auto-check poll: auto-check is Off by default, and a snoozed
            # message whose time has come must reappear whether or not you
            # have asked the program to look for new mail.
            self._check_snooze_due()

            # 0b. Follow-up reminders ("I am not finished with this mail").
            self._followup_tick()

            # 0c. Dated folders that are due to be created (DEL 04l).
            self._folderplan_tick()

            # 0d. Folders that age their own mail (DEL 04r). Same ticker for
            # the same reason as the snooze check above: it must keep its
            # promise whether or not auto-check is on. It looks at one rule per
            # tick and only every quarter of an hour, so this is almost always
            # an immediate no.
            self._folderage_tick()

            # 1. Reminders that were snoozed and are due again.
            still = []
            for fire_at, ev, occ, mins, key in self._reminder_snoozes:
                if fire_at <= now:
                    self._show_reminder(ev, occ, mins, key)
                else:
                    still.append((fire_at, ev, occ, mins, key))
            self._reminder_snoozes = still

            # 2. Fresh reminders from the calendar itself.
            for ev, occ, mins, key in _due_reminders(self._calendar_store):
                _mark_reminder_fired(self._calendar_store, key)
                self._show_reminder(ev, occ, mins, key)
        except Exception as e:
            log.error("Calendar tick failed: %s", e)
        finally:
            try:
                self._cal_after_id = self.root.after(30_000, self._calendar_tick)
            except Exception:
                pass

    def _show_reminder(self, ev, occ, mins, key):
        # Never stack the same reminder twice — a snoozed popup that is still
        # on screen should not be joined by a copy of itself.
        for p in list(self._open_reminders):
            if p.key == key and p.win.winfo_exists():
                return
            if not p.win.winfo_exists():
                self._open_reminders.remove(p)
        popup = ReminderPopup(self.root, self, ev, occ, mins, key)
        self._open_reminders.append(popup)
        # Sound + a taskbar flash, scaled by the event's alert style and how
        # close it is (DEL 04f2/04f3). This is what was missing before — a
        # reminder that neither made a sound nor flashed.
        self._alert_now(ev.get("alert", "sound"), mins, popup)

    def _beep_once(self):
        try:
            import winsound
            winsound.MessageBeep(winsound.MB_ICONEXCLAMATION)
        except Exception:
            try:
                self.root.bell()
            except Exception:
                pass

    def _alert_now(self, alert, mins, popup=None):
        """Make a reminder noticeable: a taskbar flash plus 0..N beeps. For an
        'insistent' alert the burst grows the closer the event is, and the beeps
        keep coming while the popup is still on screen (dismiss stops them)."""
        # A global mute still wins, so someone can silence everything at once.
        if self.cfg.get("reminder_sound", True) is False:
            beeps = 0
        else:
            beeps = _alert_beeps(alert, mins)
        if alert != "silent":
            try:
                self._flash_taskbar()
            except Exception:
                pass
        for i in range(beeps):
            def _b():
                if popup is None or popup.win.winfo_exists():
                    self._beep_once()
            self.root.after(i * 1400, _b)

    # ── Quick timers (DEL 04f3) ───────────────────────────────────────────────
    def _arm_all_timers(self):
        """Re-arm every saved timer on start-up. One whose time already passed
        while the program was closed fires right away (once), so an oven timer
        is never silently lost."""
        for t in list(self._timers_store.get("timers", [])):
            self._arm_timer(t)

    def _arm_timer(self, t):
        fire = _parse_iso(t.get("fire_at", "") or "")
        if fire is None:
            return
        delay_ms = int((fire - datetime.now()).total_seconds() * 1000)
        delay_ms = max(0, delay_ms)
        tid = t.get("id", "")
        old = self._timer_after_ids.pop(tid, None)
        if old is not None:
            try:
                self.root.after_cancel(old)
            except Exception:
                pass
        self._timer_after_ids[tid] = self.root.after(
            delay_ms, lambda tt=t: self._fire_timer(tt))

    def _fire_timer(self, t):
        """A quick timer has run out: show an insistent reminder popup + sound,
        then drop it from the saved list."""
        self._timer_after_ids.pop(t.get("id", ""), None)
        # Remove from the store first, so it cannot double-fire.
        self._timers_store["timers"] = [
            x for x in self._timers_store.get("timers", [])
            if x.get("id") != t.get("id")]
        _save_timers(self._timers_store)
        label = t.get("label") or "Timer"
        now = datetime.now()
        pseudo = {"title": f"⏱ {label}", "start": now.isoformat(timespec="seconds"),
                  "all_day": False, "color": "#ff6b6b", "alert": "insistent",
                  "location": ""}
        # mins=0 → the loudest step of an insistent alert.
        self._show_reminder(pseudo, now, 0, f"timer|{t.get('id','')}")

    def _cancel_timer(self, tid):
        old = self._timer_after_ids.pop(tid, None)
        if old is not None:
            try:
                self.root.after_cancel(old)
            except Exception:
                pass
        self._timers_store["timers"] = [
            x for x in self._timers_store.get("timers", [])
            if x.get("id") != tid]
        _save_timers(self._timers_store)

    def _start_timer(self, minutes, label):
        t = {"id": _new_id(), "label": label.strip() or "Timer",
             "fire_at": (datetime.now()
                         + timedelta(minutes=minutes)).isoformat(
                             timespec="seconds")}
        self._timers_store.setdefault("timers", []).append(t)
        _save_timers(self._timers_store)
        self._arm_timer(t)
        return t

    def _quick_timer_dialog(self):
        """Set a countdown ("stand up", "oven off", …). Survives a restart and
        fires an insistent reminder when it runs out (Issu's 'kortlarm')."""
        top = self._dialog_shell("Quick timer", 460, 340)
        tk.Label(top, text="Count down, then remind me — e.g. stand up, "
                           "stretch, take the food out of the oven.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 wraplength=420, justify="left", pady=4).pack(fill="x", padx=12)

        form = tk.Frame(top, bg=C_BG3); form.pack(fill="x", padx=12, pady=(4, 0))
        tk.Label(form, text="In (minutes):", bg=C_BG3, fg=C_FG_DIM, width=12,
                 anchor="e", font=("Segoe UI", 9)).pack(side="left")
        e_min = tk.Entry(form, bg=C_BG2, fg=C_FG, relief="flat", width=7,
                         insertbackground=C_ACCENT, font=("Segoe UI", 10),
                         insertofftime=0, insertontime=9999999)
        no_blink(e_min)
        e_min.insert(0, "10")
        e_min.pack(side="left", ipady=3)
        # One-click common durations.
        quick = tk.Frame(top, bg=C_BG3); quick.pack(fill="x", padx=12, pady=4)
        tk.Label(quick, text="            ", bg=C_BG3).pack(side="left")
        for label, mins in (("5m", 5), ("10m", 10), ("20m", 20), ("30m", 30),
                            ("1h", 60), ("2h", 120)):
            tk.Button(quick, text=label, bg=C_BG2, fg=C_FG_DIM, relief="flat",
                      cursor="hand2", font=("Segoe UI", 8), padx=6, pady=1,
                      command=lambda m=mins: (e_min.delete(0, "end"),
                                              e_min.insert(0, str(m)))
                      ).pack(side="left", padx=2)

        lrow = tk.Frame(top, bg=C_BG3); lrow.pack(fill="x", padx=12, pady=(6, 0))
        tk.Label(lrow, text="Label:", bg=C_BG3, fg=C_FG_DIM, width=12,
                 anchor="e", font=("Segoe UI", 9)).pack(side="left")
        e_lbl = tk.Entry(lrow, bg=C_BG2, fg=C_FG, relief="flat",
                         insertbackground=C_ACCENT, font=("Segoe UI", 10),
                         insertofftime=0, insertontime=9999999)
        no_blink(e_lbl)
        e_lbl.insert(0, "Stand up & stretch")
        e_lbl.pack(side="left", fill="x", expand=True, ipady=3)

        # Live list of running timers, each with a Cancel.
        listwrap = tk.Frame(top, bg=C_BG3)
        listwrap.pack(fill="both", expand=True, padx=12, pady=8)

        def _refresh_list():
            for w in listwrap.winfo_children():
                w.destroy()
            running = sorted(self._timers_store.get("timers", []),
                             key=lambda x: x.get("fire_at", ""))
            if not running:
                tk.Label(listwrap, text="(no timers running)", bg=C_BG3,
                         fg=C_FG_DIM, font=("Segoe UI", 8, "italic")).pack(
                             anchor="w")
                return
            for t in running:
                fire = _parse_iso(t.get("fire_at", "") or "")
                left = ""
                if fire:
                    secs = int((fire - datetime.now()).total_seconds())
                    left = (f"{secs // 60} min" if secs >= 60
                            else f"{max(0, secs)} s")
                row = tk.Frame(listwrap, bg=C_BG3); row.pack(fill="x", pady=1)
                tk.Label(row, text=f"⏱ {t.get('label','')}  —  {left} left",
                         bg=C_BG3, fg=C_FG, font=("Segoe UI", 9),
                         anchor="w").pack(side="left", fill="x", expand=True)
                tk.Button(row, text="Cancel", bg=C_BTN_DEL, fg=C_BTN_FG,
                          relief="flat", cursor="hand2", font=("Segoe UI", 8),
                          padx=8, pady=1,
                          command=lambda i=t.get("id"): (self._cancel_timer(i),
                                                         _refresh_list())
                          ).pack(side="right")

        def _start(_e=None):
            raw = e_min.get().strip().replace(",", ".")
            try:
                minutes = float(raw)
            except ValueError:
                messagebox.showwarning("Timer", "Minutes must be a number.",
                                       parent=top)
                return
            if minutes <= 0:
                messagebox.showwarning("Timer", "Give it more than 0 minutes.",
                                       parent=top)
                return
            self._start_timer(minutes, e_lbl.get())
            self._flash(f"Timer set for {int(round(minutes))} min")
            _refresh_list()

        btns = tk.Frame(top, bg=C_BG3); btns.pack(fill="x", padx=12, pady=(0, 10))
        tk.Button(btns, text="Start timer", bg=C_BTN_NEW, fg=C_BTN_FG,
                  font=("Segoe UI", 9, "bold"), relief="flat", cursor="hand2",
                  padx=14, pady=4, command=_start).pack(side="left", padx=4)
        tk.Button(btns, text="Close", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=14, pady=4, command=top.destroy).pack(side="right", padx=4)
        top.bind("<Return>", _start)
        e_min.focus_set()
        _refresh_list()

    def _snooze_reminder(self, popup, minutes):
        """Re-arm a reminder N minutes from now. The "fired" flag stays set so
        the normal engine does not also bring it back on its own."""
        self._reminder_snoozes.append(
            (datetime.now() + timedelta(minutes=minutes),
             popup.ev, popup.occ, 0, popup.key))
        if popup in self._open_reminders:
            self._open_reminders.remove(popup)
        # "snoozed 1440 min" is not a sentence anyone says (DEL 04f3).
        self._flash(f"Reminder snoozed — back in {_snooze_label(minutes)}")

    def _dismiss_reminder(self, popup):
        if popup in self._open_reminders:
            self._open_reminders.remove(popup)

    # ── Meeting invitations that arrive by mail ───────────────────────────────
    def _add_message_to_calendar(self, msg):
        """Import the .ics carried by a message, or — when there is none —
        open the editor prefilled from the message itself, which is how you
        turn "let's meet Thursday 14:00" into an actual entry."""
        ics = _find_ics_in_message(msg)
        if ics:
            try:
                events = _ics_parse(ics)
            except Exception as e:
                log.error("Invitation parse failed: %s", e)
                events = []
            if events:
                if len(events) == 1:
                    # One invitation: show it in the editor so the reminder
                    # and colour can be set before it is saved.
                    ev = events[0]
                    EventEditor(self.root, self._calendar_store, event=None,
                                prefill={"title": ev.get("title", ""),
                                         "location": ev.get("location", ""),
                                         "description": ev.get("description", ""),
                                         "start": ev.get("start", "")},
                                on_saved=self._calendar_refreshed)
                    return
                added = _merge_events(self._calendar_store, events)
                self._calendar_refreshed()
                messagebox.showinfo(
                    "Add to calendar",
                    f"{added} of {len(events)} event(s) added to your "
                    f"calendar.", parent=self.root)
                return
        # No usable invitation — start from the message's subject and date.
        dt = _parse_msg_dt(msg.get("_dt", "")) or datetime.now()
        EventEditor(self.root, self._calendar_store,
                    prefill={"title": msg.get("subject", ""),
                             "description":
                                 f"From: {msg.get('from_name','')} "
                                 f"<{msg.get('from','')}>\n\n"
                                 f"{(msg.get('body','') or '')[:400]}",
                             "start": dt.replace(minute=0, second=0,
                                                 microsecond=0
                                                 ).isoformat(timespec="seconds")},
                    on_saved=self._calendar_refreshed)

    # ==========================================================================
    # DEL 09c — DIALOGS: signatures, templates, filters, outbox, settings,
    #           backup, default mail client
    # ==========================================================================

    def _body_word_picker(self, parent, msg, add_cond_row):
        """The "Body has" word picker (DEL 04z2).

        Shows the full text of a real message so you can highlight the exact
        words you want a Body condition to look for — no typing from memory.
        Select any run of text (or double-click a single word), pick the field
        and operator, and it becomes a new condition row in the filter editor.

        add_cond_row is the filter editor's own _add_cond_row(field, op, value),
        so the chosen text lands as a live, editable row."""
        body = (msg.get("body", "") or "").strip()
        subj = (msg.get("subject", "") or "").strip()
        if not body:
            body = "(this message has no plain-text body to pick from)"

        win = tk.Toplevel(parent)
        win.title("Pick words from the message")
        win.configure(bg=C_BG3)
        _center_over(win, parent, 620, 540)
        win.transient(parent)
        win.grab_set()
        win.focus_force()
        win.bind("<Escape>", lambda e: win.destroy())

        tk.Label(win, text="Highlight the words to match, then choose where",
                 bg=C_BG1, fg=C_ACCENT, font=("Segoe UI", 11, "bold"),
                 pady=8).pack(fill="x")
        if subj:
            tk.Label(win, text=f"Subject:  {subj[:80]}", bg=C_BG3, fg=C_FG_DIM,
                     font=("Segoe UI", 8, "italic"), anchor="w",
                     padx=12).pack(fill="x")

        # Body text — read-only-ish (selection still works), no blink.
        body_frame = tk.Frame(win, bg=C_BG3)
        body_frame.pack(fill="both", expand=True, padx=12, pady=6)
        sb = tk.Scrollbar(body_frame, bg=C_BG3, troughcolor=C_BG1)
        sb.pack(side="right", fill="y")
        txt = tk.Text(body_frame, bg=C_BG2, fg=C_FG, relief="flat", wrap="word",
                      font=("Segoe UI", 10), yscrollcommand=sb.set,
                      insertofftime=0, insertontime=9999999)
        no_blink(txt)
        sb.configure(command=txt.yview)
        txt.pack(side="left", fill="both", expand=True)
        txt.insert("1.0", body)
        _bind_mousewheel(txt, None)
        # Double-click selects the word (Tk default); drag selects a run. Keep
        # the widget editable so selection/copy behave normally, but swallow
        # actual typing so the text can't be changed. Ctrl-combinations
        # (Ctrl+C copy, Ctrl+A select-all) and navigation keys pass through.
        def _readonly(e):
            if e.state & 0x4:                    # Control held → allow (copy etc.)
                return None
            if e.keysym in ("Up", "Down", "Left", "Right", "Prior", "Next",
                            "Home", "End", "Shift_L", "Shift_R",
                            "Control_L", "Control_R"):
                return None
            return "break"
        txt.bind("<Key>", _readonly)

        # Field + operator for the condition we will create.
        _FIELD_BY_LABEL = {v: k for k, v in _FILTER_FIELD_LABELS.items()}
        _OP_BY_LABEL    = {v: k for k, v in _FILTER_OP_LABELS.items()}
        ctl = tk.Frame(win, bg=C_BG3); ctl.pack(fill="x", padx=12, pady=(0, 4))
        tk.Label(ctl, text="Add as:", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left")
        fv = tk.StringVar(value=_FILTER_FIELD_LABELS["body"])
        fm = tk.OptionMenu(ctl, fv, *[_FILTER_FIELD_LABELS[f]
                                      for f in _FILTER_FIELDS])
        fm.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                     activeforeground=C_FG, highlightthickness=0, relief="flat",
                     font=("Segoe UI", 8), width=8, anchor="w")
        fm["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                             activeforeground=C_FG)
        fm.pack(side="left", padx=4)
        ov = tk.StringVar(value=_FILTER_OP_LABELS["contains"])
        om = tk.OptionMenu(ctl, ov, *[_FILTER_OP_LABELS[o] for o in _FILTER_OPS])
        om.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                     activeforeground=C_FG, highlightthickness=0, relief="flat",
                     font=("Segoe UI", 8), width=11, anchor="w")
        om["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                             activeforeground=C_FG)
        om.pack(side="left", padx=4)

        # Which SECTION the picked words become a row in. Picking two subject
        # variants out of two messages and putting both in the either/or
        # section is exactly the workflow this exists for (Issu 2026-08-03),
        # so it starts on his saved default and is one click to change.
        gv = tk.StringVar(value=_FILTER_MODE_BY_NUM.get(
            str(self.cfg.get("filter_default_section", "1")), "all"))
        if gv.get() == "every":
            gv.set("all")
        tk.Label(ctl, text="  into:", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(side="left")
        for val, txt_ in (("all", "1 · MUST"), ("any", "2 · either/or")):
            tk.Radiobutton(ctl, text=txt_, value=val, variable=gv,
                           bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                           activebackground=C_BG3, activeforeground=C_FG,
                           font=("Segoe UI", 8),
                           highlightthickness=0).pack(side="left", padx=2)

        def _use(close):
            try:
                sel = txt.get("sel.first", "sel.last")
            except tk.TclError:
                sel = ""
            sel = " ".join(sel.split()).strip()      # collapse newlines/spaces
            if not sel:
                messagebox.showinfo(
                    "Nothing selected",
                    "Highlight some words in the message first "
                    "(or double-click a single word).", parent=win)
                return
            add_cond_row(_FIELD_BY_LABEL.get(fv.get(), "body"),
                         _OP_BY_LABEL.get(ov.get(), "contains"), sel,
                         gv.get())
            self._flash(f"Added: {sel[:40]}")
            if close:
                win.destroy()

        btns = tk.Frame(win, bg=C_BG3); btns.pack(fill="x", padx=12, pady=(0, 10))
        for text, colour, cmd in (
                ("Add condition", C_BTN_NEW, lambda: _use(False)),
                ("Add & close", C_BTN_STD, lambda: _use(True)),
                ("Close", C_BTN_STD, win.destroy)):
            tk.Button(btns, text=text, bg=colour, fg=C_BTN_FG,
                      font=("Segoe UI", 9), relief="flat", cursor="hand2",
                      padx=12, pady=4, command=cmd).pack(side="left", padx=4)
        tk.Label(win, text="Tip: add several conditions from one message — "
                           "each highlight becomes its own row.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 7, "italic"),
                 pady=2).pack(fill="x")

    def _dialog_shell(self, title, width, height):
        """Every dialog in this section is built the same way: grab_set(),
        focus_force() and an <Escape> bind, in that order (house rule)."""
        top = tk.Toplevel(self.root)
        top.title(title)
        top.configure(bg=C_BG3)
        _center_over(top, self.root, width, height)
        top.transient(self.root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())
        tk.Label(top, text=title, bg=C_BG1, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold"), pady=8).pack(fill="x")
        return top

    def _listbox(self, parent, width=26):
        lb = tk.Listbox(parent, bg=C_BG2, fg=C_FG, width=width,
                        selectbackground=C_MSG_SEL, selectforeground=C_FG_UNRD,
                        highlightthickness=0, relief="flat", activestyle="none",
                        font=("Segoe UI", 9), exportselection=False)
        return lb

    def _labelled_entry(self, parent, label, width=10):
        row = tk.Frame(parent, bg=C_BG3)
        row.pack(fill="x", pady=3)
        tk.Label(row, text=label, bg=C_BG3, fg=C_FG_DIM, width=width,
                 anchor="e", font=("Segoe UI", 9)).pack(side="left")
        e = tk.Entry(row, bg=C_BG2, fg=C_FG, relief="flat",
                     insertbackground=C_ACCENT, font=("Segoe UI", 10),
                     insertofftime=0, insertontime=9999999)
        no_blink(e)
        e.pack(side="left", fill="x", expand=True, ipady=3, padx=(0, 4))
        return e

    # ── Signatures ────────────────────────────────────────────────────────────
    def _signatures_dialog(self):
        """Named signatures + which account uses which.

        The whole point of naming them is sharing: two accounts pointing at
        "Private" both change when "Private" is edited."""
        top = self._dialog_shell("Signatures", 720, 520)
        store = self._signature_store

        body = tk.Frame(top, bg=C_BG3)
        body.pack(fill="both", expand=True, padx=12, pady=8)

        # Left: the list of signatures
        left = tk.Frame(body, bg=C_BG3)
        left.pack(side="left", fill="y")
        tk.Label(left, text="Signatures", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9, "bold")).pack(anchor="w")
        lb = self._listbox(left, width=24)
        lb.pack(fill="y", expand=True, pady=4)

        # Right: name + text of the selected one
        right = tk.Frame(body, bg=C_BG3)
        right.pack(side="left", fill="both", expand=True, padx=(12, 0))
        e_name = self._labelled_entry(right, "Name:", width=8)
        tk.Label(right, text="Text (this is appended after a \"-- \" line):",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8),
                 anchor="w").pack(fill="x", pady=(6, 2))
        t_sig = tk.Text(right, bg=C_BG2, fg=C_FG, relief="flat", height=8,
                        wrap="word", font=("Segoe UI", 10), padx=8, pady=6,
                        insertbackground=C_ACCENT,
                        insertofftime=0, insertontime=9999999)
        no_blink(t_sig)
        t_sig.pack(fill="both", expand=True)

        def _refresh_list(select=None):
            lb.delete(0, "end")
            for s in store.get("signatures", []):
                users = [a for a, n in (store.get("assign") or {}).items()
                         if n == s.get("name")]
                suffix = f"   ({len(users)} account{'s' if len(users) != 1 else ''})"
                lb.insert("end", (s.get("name") or "(unnamed)") + suffix)
            if select is not None and 0 <= select < lb.size():
                lb.selection_set(select)
                lb.activate(select)

        def _selected_index():
            cur = lb.curselection()
            return cur[0] if cur else -1

        def _load_selected(event=None):
            i = _selected_index()
            if i < 0:
                return
            s = store["signatures"][i]
            e_name.delete(0, "end"); e_name.insert(0, s.get("name", ""))
            t_sig.delete("1.0", "end"); t_sig.insert("1.0", s.get("text", ""))

        lb.bind("<<ListboxSelect>>", _load_selected)

        def _save():
            name = e_name.get().strip()
            text = t_sig.get("1.0", "end-1c")
            if not name:
                messagebox.showwarning("Signature",
                                       "Give the signature a name first.",
                                       parent=top)
                return
            i = _selected_index()
            if i >= 0:
                old = store["signatures"][i].get("name", "")
                store["signatures"][i] = {"name": name, "text": text}
                # Renaming must follow through to every account using it —
                # otherwise the assignment silently points at nothing.
                if old and old != name:
                    for acct, n in list((store.get("assign") or {}).items()):
                        if n == old:
                            store["assign"][acct] = name
            else:
                store.setdefault("signatures", []).append({"name": name,
                                                           "text": text})
            _save_signatures(store)
            _refresh_list()
            self._flash("Signature saved")

        def _new():
            lb.selection_clear(0, "end")
            e_name.delete(0, "end")
            t_sig.delete("1.0", "end")
            e_name.focus_set()

        def _delete():
            i = _selected_index()
            if i < 0:
                return
            name = store["signatures"][i].get("name", "")
            if not messagebox.askyesno("Delete signature",
                                       f"Delete “{name}”?", parent=top):
                return
            del store["signatures"][i]
            for acct, n in list((store.get("assign") or {}).items()):
                if n == name:
                    del store["assign"][acct]
            _save_signatures(store)
            _refresh_list()
            _new()

        # Assignment table — one row per real account
        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x", padx=12, pady=(4, 0))
        assign_fr = tk.Frame(top, bg=C_BG3)
        assign_fr.pack(fill="x", padx=12, pady=6)
        tk.Label(assign_fr, text="Which signature does each account use?",
                 bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9, "bold"), anchor="w").pack(fill="x")

        def _rebuild_assign():
            for w in assign_fr.winfo_children()[1:]:
                w.destroy()
            names = ["(none)"] + [s.get("name", "")
                                  for s in store.get("signatures", [])]
            for a in self._accounts:
                if a.get("virtual"):
                    continue
                row = tk.Frame(assign_fr, bg=C_BG3)
                row.pack(fill="x", pady=1)
                tk.Label(row, text=a["email"], bg=C_BG3, fg=C_FG,
                         font=("Segoe UI", 9), width=32,
                         anchor="w").pack(side="left")
                var = tk.StringVar(
                    value=(store.get("assign") or {}).get(a["email"], "(none)")
                    or "(none)")

                def _set(*_args, email=a["email"], v=var):
                    val = v.get()
                    store.setdefault("assign", {})
                    if val == "(none)":
                        store["assign"].pop(email, None)
                    else:
                        store["assign"][email] = val
                    _save_signatures(store)
                    _refresh_list()

                var.trace_add("write", _set)
                om = tk.OptionMenu(row, var, *names)
                om.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                             activeforeground=C_FG, highlightthickness=0,
                             relief="flat", font=("Segoe UI", 9), anchor="w")
                om["menu"].configure(bg=C_BG2, fg=C_FG,
                                     activebackground=C_BG4,
                                     activeforeground=C_FG)
                om.pack(side="left", fill="x", expand=True)

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(fill="x", padx=12, pady=(0, 10))
        for text, colour, cmd in (("Save", C_BTN_NEW, lambda: (_save(),
                                                               _rebuild_assign())),
                                  ("New", C_BTN_STD, _new),
                                  ("Delete", C_BTN_DEL, lambda: (_delete(),
                                                                 _rebuild_assign())),
                                  ("Close", C_BTN_STD, top.destroy)):
            tk.Button(btns, text=text, bg=colour, fg=C_BTN_FG,
                      font=("Segoe UI", 9), relief="flat", cursor="hand2",
                      padx=14, pady=4, command=cmd).pack(side="left", padx=4)

        _refresh_list()
        _rebuild_assign()

    # ── Templates ─────────────────────────────────────────────────────────────
    def _templates_dialog(self):
        top = self._dialog_shell("Templates", 700, 480)
        store = self._template_store

        body = tk.Frame(top, bg=C_BG3)
        body.pack(fill="both", expand=True, padx=12, pady=8)
        left = tk.Frame(body, bg=C_BG3)
        left.pack(side="left", fill="y")
        tk.Label(left, text="Templates", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9, "bold")).pack(anchor="w")
        lb = self._listbox(left, width=24)
        lb.pack(fill="y", expand=True, pady=4)

        right = tk.Frame(body, bg=C_BG3)
        right.pack(side="left", fill="both", expand=True, padx=(12, 0))
        e_name = self._labelled_entry(right, "Name:", width=8)
        e_subj = self._labelled_entry(right, "Subject:", width=8)
        tk.Label(right,
                 text="Body — tokens: {sender} {sender_email} {account} "
                      "{subject} {YYYY-MM-DD}",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8),
                 anchor="w").pack(fill="x", pady=(6, 2))
        t_body = tk.Text(right, bg=C_BG2, fg=C_FG, relief="flat", height=8,
                         wrap="word", font=("Segoe UI", 10), padx=8, pady=6,
                         insertbackground=C_ACCENT,
                         insertofftime=0, insertontime=9999999)
        no_blink(t_body)
        t_body.pack(fill="both", expand=True)

        def _refresh():
            lb.delete(0, "end")
            for t in store.get("templates", []):
                lb.insert("end", t.get("name", "(unnamed)"))

        def _idx():
            cur = lb.curselection()
            return cur[0] if cur else -1

        def _load(event=None):
            i = _idx()
            if i < 0:
                return
            t = store["templates"][i]
            for e, key in ((e_name, "name"), (e_subj, "subject")):
                e.delete(0, "end"); e.insert(0, t.get(key, ""))
            t_body.delete("1.0", "end"); t_body.insert("1.0", t.get("body", ""))

        lb.bind("<<ListboxSelect>>", _load)

        def _save():
            name = e_name.get().strip()
            if not name:
                messagebox.showwarning("Template", "Give the template a name.",
                                       parent=top)
                return
            rec = {"name": name, "subject": e_subj.get().strip(),
                   "body": t_body.get("1.0", "end-1c")}
            i = _idx()
            if i >= 0:
                store["templates"][i] = rec
            else:
                store.setdefault("templates", []).append(rec)
            _save_templates(store)
            _refresh()
            self._flash("Template saved")

        def _new():
            lb.selection_clear(0, "end")
            for e in (e_name, e_subj):
                e.delete(0, "end")
            t_body.delete("1.0", "end")
            e_name.focus_set()

        def _delete():
            i = _idx()
            if i < 0:
                return
            if messagebox.askyesno("Delete template",
                                   f"Delete “{store['templates'][i].get('name','')}”?",
                                   parent=top):
                del store["templates"][i]
                _save_templates(store)
                _refresh(); _new()

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(fill="x", padx=12, pady=(0, 10))
        for text, colour, cmd in (("Save", C_BTN_NEW, _save),
                                  ("New", C_BTN_STD, _new),
                                  ("Delete", C_BTN_DEL, _delete),
                                  ("Close", C_BTN_STD, top.destroy)):
            tk.Button(btns, text=text, bg=colour, fg=C_BTN_FG,
                      font=("Segoe UI", 9), relief="flat", cursor="hand2",
                      padx=14, pady=4, command=cmd).pack(side="left", padx=4)
        _refresh()

    def _date_token_row(self, parent, entry, sample="kvitto.pdf"):
        """The "put a date in the filename" row: a format dropdown, a
        before/after choice, and a live preview of the resulting filename.

        Issu 2026-09-01, after typing "[YYYY-MM]" and getting the letters
        back: "man väljer vilket format som man vill ha, OM man vill ha
        datum… bara bestämma om det ska vara före eller efter". So the token
        is never typed by hand any more — it is chosen, written into the
        prefix field for you, and the preview under it shows exactly what a
        saved file will be called. Typing tokens by hand still works (and now
        tolerates [ ] and ( ) too), and the row follows along.

        Shared by the full auto-save rule editor and the quick per-sender
        rule, so the two cannot drift apart."""
        row = tk.Frame(parent, bg=C_BG3)
        row.pack(fill="x", pady=(2, 0))
        tk.Label(row, text="Date in the name:", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(side="left", padx=(0, 4))

        labels = [lab for _t, lab in _DATE_TOKEN_CHOICES]
        by_label = {lab: tok for tok, lab in _DATE_TOKEN_CHOICES}
        v_fmt = tk.StringVar(value=labels[0])
        om = tk.OptionMenu(row, v_fmt, *labels)
        om.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                     activeforeground=C_FG, highlightthickness=0,
                     relief="flat", font=("Consolas", 8), anchor="w")
        om["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                             activeforeground=C_FG, font=("Consolas", 8))
        om.pack(side="left")

        v_where = tk.StringVar(value="after")
        for val, cap in (("before", "first"), ("after", "last")):
            tk.Radiobutton(row, text=cap, value=val, variable=v_where,
                           bg=C_BG3, fg=C_FG_DIM, selectcolor=C_BG2,
                           activebackground=C_BG3, activeforeground=C_FG,
                           font=("Segoe UI", 8), highlightthickness=0,
                           bd=0).pack(side="left", padx=2)

        prev = tk.Label(parent, text="", bg=C_BG3, fg=C_ACCENT,
                        font=("Consolas", 8), anchor="w", justify="left")
        prev.pack(fill="x")

        # A stand-in message so the preview shows real values, not tokens.
        ctx = {"_dt": _now_iso(), "from_name": "Sender",
               "from": "sender@example.com",
               "account_email": (self._current_acct or ""), "subject": "Subject"}
        guard = {"busy": False}

        def _show_preview():
            try:
                name = _safe_name(_expand_prefix(entry.get(), ctx) + sample)
                prev.configure(
                    text=f"    A file would be saved as:  {name}",
                    fg=(C_ACCENT if name != sample else C_FG_DIM))
            except Exception:
                prev.configure(text="")

        def _apply(*_a):
            """Dropdown / radio changed → rewrite the prefix field."""
            if guard["busy"]:
                return
            guard["busy"] = True
            try:
                new = _set_date_token(entry.get(), by_label[v_fmt.get()],
                                      v_where.get())
                entry.delete(0, "end")
                entry.insert(0, new)
            finally:
                guard["busy"] = False
            _show_preview()

        def _sync_from_entry(*_a):
            """Typed by hand → move the dropdown to match, and re-preview.
            Guarded so our own rewrite does not bounce back."""
            if guard["busy"]:
                return
            txt = entry.get()
            tok = _prefix_date_token(txt)
            guard["busy"] = True
            try:
                for t, lab in _DATE_TOKEN_CHOICES:
                    if t == tok:
                        v_fmt.set(lab)
                        break
                if tok:
                    v_where.set("before" if txt.strip().startswith(tok)
                                else "after")
            finally:
                guard["busy"] = False
            _show_preview()

        v_fmt.trace_add("write", _apply)
        v_where.trace_add("write", _apply)
        entry.bind("<KeyRelease>", _sync_from_entry, add="+")
        _sync_from_entry()
        return row

    def _snippets_dialog(self, on_close=None):
        """Where the "often-used text" is typed in and given to the buttons
        (DEL 04d2, Issu 2026-09-01).

        One list of texts; the two one-click buttons in the compose window are
        pointers into it, set with the two ● toggles under the text box. That
        is why a snippet can sit on a button AND still be in the ▾ list — and
        why renaming one never breaks its button.

        `on_close` re-labels the buttons of the compose window that opened
        this, so an edit shows up without reopening the mail."""
        top = self._dialog_shell("Often-used text", 720, 560)
        store = self._snippet_store
        store.setdefault("snippets", [])

        tk.Label(top,
                 text="Short texts you drop into a mail with one click — your "
                      "address, payment details, a sign-off. Not the same as a "
                      "Template: a template starts a whole message (it fills "
                      "the Subject too), a snippet goes in at the cursor of "
                      "something you are already writing.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 wraplength=680, justify="left", pady=4).pack(fill="x", padx=12)

        body = tk.Frame(top, bg=C_BG3)
        body.pack(fill="both", expand=True, padx=12, pady=8)
        left = tk.Frame(body, bg=C_BG3)
        left.pack(side="left", fill="y")
        tk.Label(left, text="Saved texts", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9, "bold")).pack(anchor="w")
        lb = self._listbox(left, width=26)
        lb.pack(fill="y", expand=True, pady=4)

        right = tk.Frame(body, bg=C_BG3)
        right.pack(side="left", fill="both", expand=True, padx=(12, 0))
        e_name = self._labelled_entry(right, "Name:", width=8)
        tk.Label(right,
                 text="The text — put in exactly as typed here, newlines and "
                      "all, at wherever the cursor is in the mail.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8),
                 anchor="w", justify="left", wraplength=430).pack(fill="x",
                                                                  pady=(6, 2))
        t_text = tk.Text(right, bg=C_BG2, fg=C_FG, relief="flat", height=9,
                         wrap="word", font=("Segoe UI", 10), padx=8, pady=6,
                         insertbackground=C_ACCENT,
                         insertofftime=0, insertontime=9999999)
        no_blink(t_text)
        t_text.pack(fill="both", expand=True)

        # ── Don't let it run into the word next to it ────────────────────────
        space_var = tk.BooleanVar(value=True)
        tk.Checkbutton(right,
                       text="Add a space if it would run into the word next "
                            "to it  (…tillissusbarn@ → …till issusbarn@)",
                       variable=space_var, bg=C_BG3, fg=C_FG_DIM,
                       selectcolor=C_BG2, activebackground=C_BG3,
                       activeforeground=C_FG, font=("Segoe UI", 8),
                       anchor="w", justify="left", highlightthickness=0,
                       bd=0).pack(fill="x", pady=(6, 0))

        # ── Which of the two one-click buttons this text sits on ─────────────
        slot_row = tk.Frame(right, bg=C_BG3)
        slot_row.pack(fill="x", pady=(6, 0))
        tk.Label(slot_row, text="One-click button:", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(side="left")
        slot_var = tk.StringVar(value="")
        for val, cap in (("", "none"), ("slot1", "button 1"),
                         ("slot2", "button 2")):
            tk.Radiobutton(slot_row, text=cap, value=val, variable=slot_var,
                           bg=C_BG3, fg=C_FG_DIM, selectcolor=C_BG2,
                           activebackground=C_BG3, activeforeground=C_FG,
                           font=("Segoe UI", 8), highlightthickness=0,
                           bd=0).pack(side="left", padx=4)

        def _cur_slot(sid):
            """Which button (if any) this snippet is currently on."""
            for slot in ("slot1", "slot2"):
                if sid and store.get(slot) == sid:
                    return slot
            return ""

        def _refresh():
            lb.delete(0, "end")
            for s in store.get("snippets", []):
                mark = {"slot1": " ①", "slot2": " ②"}.get(
                    _cur_slot(s.get("id")), "")
                lb.insert("end", (s.get("name") or "(unnamed)") + mark)

        def _idx():
            cur = lb.curselection()
            return cur[0] if cur else -1

        def _load(event=None):
            i = _idx()
            if i < 0:
                return
            s = store["snippets"][i]
            e_name.delete(0, "end"); e_name.insert(0, s.get("name", ""))
            t_text.delete("1.0", "end"); t_text.insert("1.0", s.get("text", ""))
            space_var.set(bool(s.get("space", True)))
            slot_var.set(_cur_slot(s.get("id")))

        lb.bind("<<ListboxSelect>>", _load)

        def _save():
            name = e_name.get().strip()
            text = t_text.get("1.0", "end-1c")
            if not name:
                messagebox.showwarning("Often-used text",
                                       "Give it a name — that is what the "
                                       "button and the ▾ list will say.",
                                       parent=top)
                return
            if not text.strip():
                messagebox.showwarning("Often-used text",
                                       "There is no text to insert yet.",
                                       parent=top)
                return
            i = _idx()
            if i >= 0:
                sid = store["snippets"][i].get("id") or _new_id()
                store["snippets"][i] = {"id": sid, "name": name, "text": text,
                                        "space": bool(space_var.get())}
            else:
                sid = _new_id()
                store["snippets"].append({"id": sid, "name": name,
                                          "text": text,
                                          "space": bool(space_var.get())})
            # Apply the button choice. A button holds ONE text, so assigning
            # this one to button 1 takes whatever was there off it; choosing
            # "none" only clears the button this snippet is actually on, never
            # somebody else's.
            want = slot_var.get()
            for slot in ("slot1", "slot2"):
                if store.get(slot) == sid and slot != want:
                    store[slot] = ""
            if want:
                store[want] = sid
            _save_snippets(store)
            _refresh()
            self._flash("Often-used text saved")
            if on_close:
                try: on_close()
                except Exception: pass

        def _new():
            lb.selection_clear(0, "end")
            e_name.delete(0, "end")
            t_text.delete("1.0", "end")
            space_var.set(True)
            slot_var.set("")
            e_name.focus_set()

        def _delete():
            i = _idx()
            if i < 0:
                return
            rec = store["snippets"][i]
            if messagebox.askyesno("Delete",
                                   f"Delete “{rec.get('name','')}”?",
                                   parent=top):
                sid = rec.get("id")
                for slot in ("slot1", "slot2"):
                    if store.get(slot) == sid:
                        store[slot] = ""      # never leave a button pointing
                                              # at something that is gone
                del store["snippets"][i]
                _save_snippets(store)
                _refresh(); _new()
                if on_close:
                    try: on_close()
                    except Exception: pass

        def _close():
            if on_close:
                try: on_close()
                except Exception: pass
            top.destroy()

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(fill="x", padx=12, pady=(0, 10))
        for text, colour, cmd in (("Save", C_BTN_NEW, _save),
                                  ("New", C_BTN_STD, _new),
                                  ("Delete", C_BTN_DEL, _delete),
                                  ("Close", C_BTN_STD, _close)):
            tk.Button(btns, text=text, bg=colour, fg=C_BTN_FG,
                      font=("Segoe UI", 9), relief="flat", cursor="hand2",
                      padx=14, pady=4, command=cmd).pack(side="left", padx=4)
        _refresh()
        if not store.get("snippets"):
            _new()

    def _filter_log_dialog(self):
        """Show what the filters have done this session (DEL 04x). Newest first.
        The same lines are also written to Freemail.log for a lasting record."""
        top = self._dialog_shell("Filter log", 760, 480)
        tk.Label(top,
                 text="What your filters have done — newest first. Also written "
                      "to Freemail.log. Deduped: the same rule acting on the "
                      "same message is listed once.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 wraplength=720, justify="left", pady=4).pack(fill="x")

        frame = tk.Frame(top, bg=C_BG3)
        frame.pack(fill="both", expand=True, padx=12, pady=6)
        sb = tk.Scrollbar(frame, bg=C_BG3, troughcolor=C_BG1)
        sb.pack(side="right", fill="y")
        txt = tk.Text(frame, bg=C_BG2, fg=C_FG, relief="flat", wrap="none",
                      font=("Consolas", 9), padx=8, pady=6,
                      yscrollcommand=sb.set,
                      insertofftime=0, insertontime=9999999)
        no_blink(txt)
        sb.configure(command=txt.yview)
        txt.pack(fill="both", expand=True)

        if not self._filter_log:
            txt.insert("end", "  (no filter activity yet this session)")
        else:
            for ev in reversed(self._filter_log):
                txt.insert("end",
                           f"{ev.get('when','')}  [{ev.get('fname','')}]  "
                           f"{ev.get('actions','')}\n"
                           f"        {ev.get('subject','')[:70]}   "
                           f"— {ev.get('sender','')}   ({ev.get('folder','')})\n")
        txt.configure(state="disabled")

        def _clear():
            self._filter_log = []
            # .clear(), not a fresh set() — replacing it would swap the
            # bounded set for a plain one and quietly undo the cap.
            self._filter_log_seen.clear()
            txt.configure(state="normal")
            txt.delete("1.0", "end")
            txt.insert("end", "  (cleared)")
            txt.configure(state="disabled")

        br = tk.Frame(top, bg=C_BG3)
        br.pack(fill="x", padx=12, pady=(0, 10))
        for text, colour, cmd in (("Clear", C_BTN_DEL, _clear),
                                  ("Close", C_BTN_STD, top.destroy)):
            tk.Button(br, text=text, bg=colour, fg=C_BTN_FG,
                      font=("Segoe UI", 9), relief="flat", cursor="hand2",
                      padx=12, pady=4, command=cmd).pack(side="left", padx=4)

    # ── Activity log window (Issu 2026-08-08) ────────────────────────────────
    def _activity_log_dialog(self):
        """"What happened lately?" in one short list, kept across restarts.

        The Filter log next door only covers THIS session, which is no use for
        the case that prompted this: the phone says "you have mail", and by the
        time the program is opened a rule has already moved or binned it. Every
        line here says which account it arrived in, who it was from, which rule
        fired and what the rule did — so a message that "disappeared" can
        always be accounted for.

        Reads as one line per event, newest first, no scrolling needed for the
        common case."""
        top = self._dialog_shell("Activity log", 860, 560)
        tk.Label(top,
                 text="Everything that has happened to your mail — newest "
                      "first, and kept when you close the program. Filters "
                      "that moved, read or binned a message are listed here "
                      "with the rule that did it, so nothing ever just "
                      "\"disappears\".",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 wraplength=820, justify="left", pady=4).pack(fill="x")

        # ── Filter row: show everything, or only one kind of event ───────────
        fr = tk.Frame(top, bg=C_BG3)
        fr.pack(fill="x", padx=12, pady=(2, 0))
        tk.Label(fr, text="Show:", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left")
        kind_var = tk.StringVar(value="Everything")
        # "move-try" is the request, "moved" what actually went, "move-failed"
        # what did not and why — the three together are Issu's "har den med
        # (försök till) MOVE?" (DEL 09l). "Moves (all three)" is a convenience
        # scope, because those three lines belong to one story.
        kinds = ["Everything", "Moves (all three)", "move-try", "moved",
                 "move-failed", "filtered", "sent", "deleted"]
        om = tk.OptionMenu(fr, kind_var, *kinds)
        om.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                     activeforeground=C_FG, highlightthickness=0,
                     relief="flat", font=("Segoe UI", 9), width=16)
        om["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                             activeforeground=C_FG, font=("Segoe UI", 9))
        om.pack(side="left", padx=6)

        tk.Label(fr, text="Find:", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left", padx=(12, 0))
        e_find = tk.Entry(fr, bg=C_BG2, fg=C_FG, relief="flat",
                          insertbackground=C_ACCENT, font=("Segoe UI", 9),
                          insertofftime=0, insertontime=9999999)
        no_blink(e_find)
        e_find.pack(side="left", fill="x", expand=True, padx=6, ipady=2)

        frame = tk.Frame(top, bg=C_BG3)
        frame.pack(fill="both", expand=True, padx=12, pady=6)
        sb = tk.Scrollbar(frame, bg=C_BG3, troughcolor=C_BG1)
        sb.pack(side="right", fill="y")
        txt = tk.Text(frame, bg=C_BG2, fg=C_FG, relief="flat", wrap="word",
                      font=("Consolas", 9), padx=8, pady=6,
                      yscrollcommand=sb.set,
                      insertofftime=0, insertontime=9999999)
        no_blink(txt)
        sb.configure(command=txt.yview)
        txt.pack(fill="both", expand=True)
        _bind_mousewheel(txt, txt)

        # Colour per kind, so the eye finds the interesting lines at once.
        txt.tag_configure("filtered", foreground="#8ad6ff")
        txt.tag_configure("sent",     foreground="#a8e6a8")
        txt.tag_configure("deleted",  foreground="#ff9c9c")
        txt.tag_configure("moved",    foreground="#ffd08a")
        txt.tag_configure("move-try", foreground="#c9b184")
        # A move that did NOT happen must not read like one that did.
        txt.tag_configure("move-failed", foreground="#ff7a7a")
        txt.tag_configure("dim",      foreground=C_FG_DIM)

        _MOVE_KINDS = ("move-try", "moved", "move-failed")

        def _render(*_a):
            want = kind_var.get()
            needle = e_find.get().strip().lower()
            txt.configure(state="normal")
            txt.delete("1.0", "end")
            entries = list(reversed(self._activity_store.get("entries", [])))
            shown = 0
            for ev in entries:
                kind = ev.get("kind", "")
                if want == "Moves (all three)":
                    if kind not in _MOVE_KINDS:
                        continue
                elif want != "Everything" and kind != want:
                    continue
                blob = " ".join(str(ev.get(k, "")) for k in
                                ("account", "sender", "subject", "rule",
                                 "detail")).lower()
                if needle and needle not in blob:
                    continue
                when = (ev.get("when", "") or "")[:16].replace("T", "  ")
                who  = ev.get("sender", "") or "—"
                acct = ev.get("account", "")
                rule = ev.get("rule", "")
                head = f"{when}   {kind.upper()}"
                if acct:
                    head += f"   →  {acct}"
                txt.insert("end", head + "\n", kind or "dim")
                line2 = f"        From {who}"
                if rule:
                    line2 += f'   ·   rule "{rule}"'
                txt.insert("end", line2 + "\n", "dim")
                if ev.get("subject"):
                    txt.insert("end", f"        “{ev['subject'][:80]}”\n", "dim")
                if ev.get("detail"):
                    txt.insert("end", f"        {ev['detail']}\n", "dim")
                txt.insert("end", "\n")
                shown += 1
            if not shown:
                txt.insert("end", "  (nothing logged yet — this fills up as "
                                  "mail arrives and your rules act on it)")
            txt.configure(state="disabled")

        kind_var.trace_add("write", _render)
        e_find.bind("<KeyRelease>", _render)
        e_find.bind("<Return>", _render)

        def _clear():
            if not messagebox.askyesno(
                    "Clear the activity log",
                    "Throw away the whole history?\n\nIt only records what has "
                    "already happened — no mail is touched.", parent=top):
                return
            self._activity_store = {"entries": []}
            _save_activity(self._activity_store)
            _render()

        br = tk.Frame(top, bg=C_BG3)
        br.pack(fill="x", padx=12, pady=(0, 10))
        for text, colour, cmd in (("Close", C_BTN_STD, top.destroy),
                                  ("Refresh", C_BTN_STD, _render),
                                  ("Clear", C_BTN_DEL, _clear)):
            tk.Button(br, text=text, bg=colour, fg=C_BTN_FG,
                      font=("Segoe UI", 9), relief="flat", cursor="hand2",
                      padx=12, pady=4, command=cmd).pack(side="left", padx=4)
        _render()

    # ── Drafts that are no longer needed (Issu 2026-08-08) ──────────────────
    def _tidy_drafts_dialog(self):
        """Which unsent drafts have, in fact, already been sent?

        A draft finished on the phone, or written before a send this program
        did not mark, sits here for ever looking like unfinished work. This
        reads your Sent folder and pairs them up — conservatively, because
        deleting the wrong one loses writing you cannot get back. Nothing is
        deleted without you ticking it."""
        drafts = [d for d in _list_drafts()
                  if not d.get("sent") and not d.get("queued")]
        if not drafts:
            messagebox.showinfo("Tidy drafts",
                                "You have no unsent drafts.", parent=self.root)
            return
        top = self._dialog_shell("Tidy drafts", 820, 600)
        tk.Label(top, text="🧹  Drafts you may not need any more",
                 bg=C_BG3, fg=C_ACCENT, font=("Segoe UI", 12, "bold"),
                 pady=(8)).pack()
        status = tk.Label(top, text=f"{len(drafts)} unsent draft(s). Reading "
                                    f"your Sent folder…",
                          bg=C_BG3, fg=C_FG_DIM,
                          font=("Segoe UI", 9, "italic"))
        status.pack()

        body = tk.Frame(top, bg=C_BG2)
        body.pack(fill="both", expand=True, padx=14, pady=8)
        sb = tk.Scrollbar(body, bg=C_BG3, troughcolor=C_BG1)
        sb.pack(side="right", fill="y")
        canvas = tk.Canvas(body, bg=C_BG2, highlightthickness=0,
                           yscrollcommand=sb.set)
        canvas.pack(fill="both", expand=True)
        sb.configure(command=canvas.yview)
        inner = tk.Frame(canvas, bg=C_BG2)
        cw = canvas.create_window((0, 0), window=inner, anchor="nw")
        inner.bind("<Configure>",
                   lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
        canvas.bind("<Configure>",
                    lambda e: canvas.itemconfig(cw, width=e.width))
        _bind_mousewheel(inner, canvas)

        picks = {}

        def show(matches):
            for w in inner.winfo_children():
                w.destroy()
            picks.clear()
            n = len(matches)
            status.configure(
                text=(f"{n} of {len(drafts)} draft(s) look like they have "
                      f"already been sent." if n else
                      f"None of your {len(drafts)} draft(s) appears to have "
                      f"been sent — nothing to tidy."),
                fg=(C_ACCENT if n else C_FG_DIM))
            for d, info in matches:
                row = tk.Frame(inner, bg=C_BG3, padx=10, pady=6)
                row.pack(fill="x", padx=8, pady=3)
                v = tk.BooleanVar(value=True)
                picks[d.get("id", "")] = (v, d)
                tk.Checkbutton(
                    row, text=f"{d.get('subject') or '(no subject)'}",
                    variable=v, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                    activebackground=C_BG3, activeforeground=C_FG,
                    font=("Segoe UI", 10, "bold"), highlightthickness=0,
                    anchor="w").pack(fill="x")
                tk.Label(row, text=f"      draft to {d.get('to','')}  ·  "
                                   f"saved {(d.get('saved','') or '')[:16].replace('T',' ')}",
                         bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8),
                         anchor="w").pack(fill="x")
                tk.Label(row, text=f"      ✓ already sent: {info['why']}",
                         bg=C_BG3, fg="#a8e6a8", font=("Segoe UI", 8),
                         anchor="w", justify="left",
                         wraplength=700).pack(fill="x")

        def scan():
            sent = []
            if not self._demo_mode:
                for a in self._accounts:
                    if a.get("virtual"):
                        continue
                    pwd = self._secret_for(a["email"])
                    if not pwd:
                        continue
                    try:
                        sent.extend(_fetch_folder_smart(
                            a["email"], pwd, "Sent", limit=200,
                            use_cache=self.cfg.get("cache_enabled", True),
                            interactive=True))
                    except Exception as e:
                        log.warning("Tidy drafts: could not read Sent for "
                                    "%s: %s", a["email"], e)
            matches = []
            for d in drafts:
                info = _draft_looks_sent(d, sent)
                if info:
                    matches.append((d, info))

            def done():
                try:
                    if top.winfo_exists():
                        show(matches)
                except Exception:
                    pass
            try:
                self.root.after(0, done)
            except Exception:
                pass

        threading.Thread(target=scan, daemon=True).start()

        def delete_ticked():
            chosen = [(d) for _k, (v, d) in picks.items() if v.get()]
            if not chosen:
                return
            names = "\n".join(f"  • {d.get('subject') or '(no subject)'}"
                              for d in chosen[:8])
            if not messagebox.askyesno(
                    "Tidy drafts",
                    f"Delete {len(chosen)} draft(s)?\n\n{names}"
                    + ("\n  …" if len(chosen) > 8 else "")
                    + "\n\nThe sent messages are untouched — this only removes "
                      "the half-written copies on this computer. The text in "
                      "them is gone for good.",
                    parent=top, default="no"):
                return
            for d in chosen:
                _delete_draft(d.get("id", ""))
            self._activity_log("deleted",
                               detail=f"tidied away {len(chosen)} draft(s) "
                                      f"whose message had already been sent")
            self._flash(f"{len(chosen)} draft(s) removed")
            top.destroy()

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(fill="x", padx=14, pady=(0, 12))
        tk.Button(btns, text="🗑  Delete the ticked drafts", bg=C_BTN_DEL,
                  fg=C_BTN_FG, font=("Segoe UI", 9, "bold"), relief="flat",
                  cursor="hand2", padx=12, pady=4,
                  command=delete_ticked).pack(side="left", padx=4)
        tk.Button(btns, text="Close", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=12, pady=4, command=top.destroy).pack(side="left", padx=4)

    # ── Export / restore a mailbox (Issu 2026-08-08) ────────────────────────
    def _export_mail_dialog(self):
        """Write the mail you choose to one .zip you can put anywhere."""
        from tkinter import filedialog
        loaded = list(self._messages)
        if not loaded:
            messagebox.showinfo(
                "Export mail",
                "Open the folder you want to export first — this exports the "
                "messages loaded in the list (use “Load older messages” to "
                "reach further back).", parent=self.root)
            return
        with_body = [m for m in loaded
                     if m.get("_raw") or _cached_raw_for(m)]
        missing = len(loaded) - len(with_body)
        if not with_body:
            messagebox.showinfo(
                "Export mail",
                "None of these messages has been downloaded in full yet, so "
                "there is nothing to write. Open a few (or let the read-ahead "
                "catch up) and try again.", parent=self.root)
            return
        if not messagebox.askyesno(
                "Export mail",
                f"Write {len(with_body)} message(s) to a file?\n"
                + (f"\n{missing} of the {len(loaded)} loaded have not been "
                   f"downloaded in full yet and will be left out.\n" if missing
                   else "")
                + "\nEach message is saved exactly as it arrived, together "
                  "with its date, its read/starred state and every label it "
                  "carries — so a restore puts it back the way it was.\n\n"
                  "What canNOT be preserved is Gmail's own grouping into "
                  "conversations: a restored message may sit in a thread of "
                  "its own. Nothing is lost, it may just be grouped "
                  "differently.",
                parent=self.root, default="yes"):
            return
        folder = _safe_name(self._folder_display_name(self._current_folder))
        default = f"freemail-{folder}-{datetime.now():%Y-%m-%d}.zip"
        path = filedialog.asksaveasfilename(
            parent=self.root, title="Export mail to…",
            defaultextension=".zip", initialfile=default,
            filetypes=[("F(re)email export", "*.zip"), ("All files", "*.*")])
        if not path:
            return
        self._flash(f"Writing {len(with_body)} message(s)…")

        def worker():
            try:
                r = _export_messages_zip(path, with_body)
            except Exception as e:
                log.error("Export failed: %s", e)
                r = {"error": str(e)}

            def done():
                if r.get("error"):
                    messagebox.showerror("Export mail", r["error"],
                                         parent=self.root)
                    return
                self._activity_log(
                    "export",
                    detail=f"exported {r['written']} message(s) to "
                           f"{os.path.basename(path)}")
                messagebox.showinfo(
                    "Export mail",
                    f"{r['written']} message(s) written.\n\n"
                    f"{os.path.basename(path)}  "
                    f"({r['bytes']/1024/1024:.1f} MB)\n\n"
                    f"Keep this file somewhere else — another disk, a stick, "
                    f"anywhere. “Restore mail from a file…” puts it back, and "
                    f"skips anything already on Gmail, so it is safe to run "
                    f"twice.", parent=self.root)
            try:
                self.root.after(0, done)
            except Exception:
                pass

        threading.Thread(target=worker, daemon=True).start()

    def _restore_mail_dialog(self):
        """Put an export back — safely, and without ever duplicating."""
        from tkinter import filedialog
        path = filedialog.askopenfilename(
            parent=self.root, title="Restore mail from…",
            filetypes=[("F(re)email export", "*.zip"), ("All files", "*.*")])
        if not path:
            return
        man = _read_export_manifest(path)
        msgs = man.get("messages") or []
        if not msgs:
            messagebox.showerror(
                "Restore mail",
                "That does not look like a F(re)email export — no manifest "
                "inside.", parent=self.root)
            return

        reals = [a for a in self._accounts if not a.get("virtual")]
        if not reals:
            messagebox.showinfo("Restore mail", "No account is set up.",
                                parent=self.root)
            return
        was = sorted({m.get("account", "") for m in msgs if m.get("account")})

        top = self._dialog_shell("Restore mail", 660, 560)
        tk.Label(top, text="↩  Restore mail from a file", bg=C_BG3,
                 fg=C_ACCENT, font=("Segoe UI", 12, "bold"),
                 pady=(8)).pack()
        tk.Label(top,
                 text=f"{os.path.basename(path)}\n"
                      f"{len(msgs)} message(s), exported "
                      f"{(man.get('created','') or '')[:16].replace('T',' ')}"
                      + (f"\noriginally from: {', '.join(was)}" if was else ""),
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 9),
                 justify="center").pack(pady=(0, 6))

        f = tk.Frame(top, bg=C_BG3)
        f.pack(fill="both", expand=True, padx=18)
        tk.Label(f, text="Put it back into:", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9), anchor="w").pack(fill="x")
        v_acct = tk.StringVar(value=(was[0] if was and any(
            a["email"] == was[0] for a in reals) else reals[0]["email"]))
        om = tk.OptionMenu(f, v_acct, *[a["email"] for a in reals])
        om.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                     activeforeground=C_FG, highlightthickness=0,
                     relief="flat", font=("Segoe UI", 10), anchor="w")
        om["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                             activeforeground=C_FG)
        om.pack(fill="x", pady=(2, 10))

        v_only = tk.BooleanVar(value=True)
        cb = tk.Checkbutton(
            f, text="Only put back what is MISSING  (strongly recommended)",
            variable=v_only, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
            activebackground=C_BG3, activeforeground=C_FG,
            font=("Segoe UI", 10, "bold"), highlightthickness=0, anchor="w")
        cb.pack(fill="x")
        tk.Label(f, text="Each message is looked up on the server by its own "
                         "Message-ID first. Anything still there is left "
                         "completely alone — so nothing is ever duplicated, "
                         "and running this twice, or restoring an old backup "
                         "over a mailbox you have kept using, changes only "
                         "what is genuinely gone.\n\n"
                         "Turn it off only if you deliberately want a second "
                         "copy of everything.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w",
                 justify="left", wraplength=580).pack(fill="x", padx=22,
                                                      pady=(0, 8))

        out = tk.Label(f, text="", bg=C_BG2, fg=C_ACCENT,
                       font=("Consolas", 9), anchor="w", justify="left",
                       padx=10, pady=8, wraplength=580)
        out.pack(fill="x", pady=(4, 0))

        state = {"busy": False}

        def run(dry):
            if state["busy"]:
                return
            acct = v_acct.get()
            pwd = self._secret_for(acct)
            if not pwd:
                messagebox.showwarning("Restore mail",
                                       "No stored password for that account.",
                                       parent=top)
                return
            if not dry and not messagebox.askyesno(
                    "Restore mail",
                    f"Upload the missing messages into {acct}?\n\n"
                    f"This ADDS mail. Nothing on Gmail is moved, changed or "
                    f"deleted.", parent=top, default="yes"):
                return
            state["busy"] = True
            only = bool(v_only.get())
            out.configure(text="Working…  (asking the server what it already "
                               "has)")

            def worker():
                r = _restore_messages_zip(path, acct, pwd, only_missing=only,
                                          dry_run=dry)

                def done():
                    state["busy"] = False
                    txt = (f"{'Would restore' if dry else 'Restored'}: "
                           f"{r['restored']}\n"
                           f"Already on Gmail, left alone: {r['already_there']}\n"
                           f"Failed: {r['failed']}   (of {r['total']})")
                    if r["problems"]:
                        txt += "\n\n" + "\n".join(r["problems"][:4])
                    out.configure(text=txt)
                    if not dry:
                        self._activity_log(
                            "restore", account=acct,
                            detail=f"restored {r['restored']} message(s) from "
                                   f"{os.path.basename(path)}, "
                                   f"{r['already_there']} already there")
                        self._refresh_folder_tree()
                try:
                    self.root.after(0, done)
                except Exception:
                    pass

            threading.Thread(target=worker, daemon=True).start()

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(fill="x", padx=18, pady=12)
        b1 = tk.Button(btns, text="🔍  Check first (changes nothing)",
                       bg=C_BTN_STD, fg=C_BTN_FG, font=("Segoe UI", 9),
                       relief="flat", cursor="hand2", padx=12, pady=4,
                       command=lambda: run(True))
        b1.pack(side="left", padx=4)
        add_tooltip(b1, "Asks the server which of these messages it already "
                        "has, and tells you what a real restore would do. "
                        "Uploads nothing.")
        tk.Button(btns, text="↩  Restore", bg=C_BTN_NEW, fg=C_BTN_FG,
                  font=("Segoe UI", 9, "bold"), relief="flat", cursor="hand2",
                  padx=14, pady=4, command=lambda: run(False)).pack(side="left",
                                                                    padx=4)
        tk.Button(btns, text="Close", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=12, pady=4, command=top.destroy).pack(side="left", padx=4)

    # ── What is using disk? (Issu 2026-08-08) ───────────────────────────────
    def _storage_dialog(self):
        """Where this program's disk space has gone, and how to get it back.

        Measured on his machine: the message cache had reached 42 MB across
        776 files and the Deleted archive 26 MB across 1412, neither with any
        ceiling. Nothing anywhere said so. Both are safe to trim — the cache
        is a copy of what is on Gmail and refills itself, and the Deleted
        archive is the local safety copy of mail already deleted, kept for
        `deleted_keep_days`."""
        top = self._dialog_shell("Storage", 700, 560)
        tk.Label(top, text="💾  What is using disk?", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold"), pady=(8)).pack()
        tk.Label(top, text=_FM_DIR, bg=C_BG3, fg=C_FG_DIM,
                 font=("Consolas", 8), wraplength=640).pack()

        frame = tk.Frame(top, bg=C_BG3)
        frame.pack(fill="both", expand=True, padx=14, pady=8)
        txt = tk.Text(frame, bg=C_BG2, fg=C_FG, relief="flat", wrap="word",
                      font=("Consolas", 9), padx=10, pady=8,
                      insertofftime=0, insertontime=9999999)
        no_blink(txt)
        txt.pack(fill="both", expand=True)
        txt.tag_configure("big", foreground="#ffd08a")
        txt.tag_configure("dim", foreground=C_FG_DIM)

        def measure(path):
            total = n = 0
            for r, _d, fs in os.walk(path):
                for f in fs:
                    try:
                        total += os.path.getsize(os.path.join(r, f))
                        n += 1
                    except OSError:
                        pass
            return total, n

        def render():
            txt.configure(state="normal")
            txt.delete("1.0", "end")
            rows = []
            for label, sub, note in (
                    ("Message cache", "Cache",
                     "offline copies of your mail — refills itself from Gmail"),
                    ("Deleted archive", "Deleted",
                     "local copies of mail deleted through this program"),
                    ("Backups", "Backups", "settings/rule backups"),
                    ("Outbox files", "Outbox", "attachments of queued mail"),
                    ("Drafts", "Drafts", "unsent messages"),
                    ("Accounts & rules", "Accounts",
                     "settings, filters, contacts — tiny, never prune"),
            ):
                p = os.path.join(_FM_DIR, sub)
                if not os.path.isdir(p):
                    continue
                size, n = measure(p)
                rows.append((label, size, n, note))
            grand = sum(r[1] for r in rows)
            for label, size, n, note in sorted(rows, key=lambda r: -r[1]):
                mb = size / 1024 / 1024
                txt.insert("end", f"  {label:<18}{mb:>8.1f} MB  {n:>5} files\n",
                           "big" if mb > 20 else None)
                txt.insert("end", f"      {note}\n", "dim")
            txt.insert("end", f"\n  {'TOTAL':<18}{grand/1024/1024:>8.1f} MB\n")
            txt.insert("end",
                       "\n  The cache and the Deleted archive are the only two "
                       "that grow without limit. Trimming the cache costs "
                       "nothing but a little slowness the next time you open "
                       "an old folder — the mail itself is on Gmail. The "
                       "Deleted archive holds YOUR only copy of anything you "
                       "erased from the Trash, so it is trimmed by age, never "
                       "wholesale.\n", "dim")
            txt.configure(state="disabled")

        def trim_cache():
            days = _ask_line(top, "Trim the cache",
                             "Delete cached message files not opened for how "
                             "many days?\n\n(The mail stays on Gmail — this "
                             "only clears local copies. 0 = clear it all.)",
                             "30", ok="Trim")
            if days is None:
                return
            try:
                days = max(0, int(days))
            except ValueError:
                return
            cutoff = time.time() - days * 86400
            gone = freed = 0
            for r, _d, fs in os.walk(os.path.join(_FM_DIR, "Cache")):
                for f in fs:
                    if not (f.endswith(".eml") or f.endswith(".hdr")):
                        continue
                    p = os.path.join(r, f)
                    try:
                        if days and os.path.getmtime(p) > cutoff:
                            continue
                        sz = os.path.getsize(p)
                        os.remove(p)
                        gone += 1
                        freed += sz
                    except OSError:
                        pass
            log.info("Cache trim: removed %d file(s), %.1f MB", gone,
                     freed / 1024 / 1024)
            self._flash(f"Freed {freed/1024/1024:.1f} MB from the cache")
            render()

        def trim_deleted():
            cur = int(self.cfg.get("deleted_keep_days", 30) or 30)
            days = _ask_line(top, "Trim the Deleted archive",
                             f"Keep local copies of deleted mail for how many "
                             f"days?\n\nCurrently {cur}. These are YOUR only "
                             f"copy of anything erased from the Trash — "
                             f"anything older is removed for good.",
                             str(cur), ok="Apply")
            if days is None:
                return
            try:
                days = max(1, int(days))
            except ValueError:
                return
            self.cfg["deleted_keep_days"] = days
            _save_settings(self.cfg)
            try:
                gone = _deleted_prune(days)
                self._flash(f"Removed {gone} expired copy/copies")
            except Exception as e:
                log.warning("Deleted prune failed: %s", e)
            render()

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(fill="x", padx=14, pady=(0, 12))
        for text, colour, cmd in (
                ("Close", C_BTN_STD, top.destroy),
                ("Refresh", C_BTN_STD, render),
                ("🧹 Trim the cache…", "#8a5a2a", trim_cache),
                ("🧹 Trim the Deleted archive…", "#8a5a2a", trim_deleted)):
            tk.Button(btns, text=text, bg=colour, fg=C_BTN_FG,
                      font=("Segoe UI", 9), relief="flat", cursor="hand2",
                      padx=10, pady=4, command=cmd).pack(side="left", padx=4)
        render()

    # ── Rule health (Issu 2026-08-08) ───────────────────────────────────────
    def _rule_health_dialog(self):
        """How much is each rule actually doing — and why isn't that one?

        Counting Issu's own log showed the thing nothing on screen told him:
        a couple of rules do nearly all the work, one had never matched
        anything at all, and his carrier rules match plenty HISTORICALLY while
        catching none of the shipping mail sitting in his inboxes today,
        because each carries a subject phrase the carriers stopped using.

        So this window shows three things per rule: how often it has fired,
        when it last fired, and — for a rule that is not catching the mail in
        front of you — WHICH condition row is saying no, with an offer to drop
        it. Nothing changes without a confirmation naming the row."""
        top = self._dialog_shell("Rule health", 900, 660)
        tk.Label(top, text="🩺  Rule health", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold"), pady=(8)).pack()
        tk.Label(top,
                 text="How much each rule is really doing. “Blocking” is worked "
                      "out against the mail loaded in the window behind this "
                      "one — open the folder you expect a rule to catch, then "
                      "come back here.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 wraplength=840, justify="left").pack(padx=16)

        frame = tk.Frame(top, bg=C_BG3)
        frame.pack(fill="both", expand=True, padx=14, pady=8)
        sb = tk.Scrollbar(frame, bg=C_BG3, troughcolor=C_BG1)
        sb.pack(side="right", fill="y")
        txt = tk.Text(frame, bg=C_BG2, fg=C_FG, relief="flat", wrap="word",
                      font=("Segoe UI", 9), padx=10, pady=8,
                      yscrollcommand=sb.set,
                      insertofftime=0, insertontime=9999999)
        no_blink(txt)
        sb.configure(command=txt.yview)
        txt.pack(fill="both", expand=True)
        _bind_mousewheel(txt, txt)
        txt.tag_configure("name", foreground=C_ACCENT,
                          font=("Segoe UI", 10, "bold"))
        txt.tag_configure("dead", foreground="#ff9c9c",
                          font=("Segoe UI", 10, "bold"))
        txt.tag_configure("warn", foreground="#ffd08a")
        txt.tag_configure("good", foreground="#a8e6a8")
        txt.tag_configure("dim",  foreground=C_FG_DIM)

        # The mail this is judged against: whatever is loaded behind us.
        sample = list(self._messages)
        self._rh_fixable = {}     # button index -> (rule, condition index)

        def render():
            txt.configure(state="normal")
            txt.delete("1.0", "end")
            rules = self._filter_store.get("filters", [])
            if not rules:
                txt.insert("end", "  You have no rules yet.")
                txt.configure(state="disabled")
                return
            txt.insert("end", f"  Judged against the {len(sample)} message(s) "
                              f"loaded in “"
                              f"{self._folder_display_name(self._current_folder)}"
                              f"”.\n\n", "dim")
            self._rh_fixable = {}
            for flt in rules:
                fid  = flt.get("id", "")
                name = flt.get("name") or fid[:6]
                st   = _rule_stat_for(self._rule_stats, fid)
                hits = int(st.get("hits", 0))
                last = st.get("last", "")
                enabled = flt.get("enabled", True)

                here = 0
                for m in sample:
                    try:
                        if _filter_matches(flt, m):
                            here += 1
                    except Exception:
                        pass

                tag = "name"
                if not enabled:
                    tag = "dim"
                elif hits == 0:
                    tag = "dead"
                txt.insert("end", f"  {name}", tag)
                if not enabled:
                    txt.insert("end", "   (switched off)", "dim")
                txt.insert("end", "\n")

                when = (last[:16].replace("T", " ") if last else "never")
                line = f"      fired {hits} time(s) since this counter started"
                line += f"   ·   last: {when}"
                txt.insert("end", line + "\n",
                           "good" if hits else "warn")
                txt.insert("end", f"      matches {here} of the "
                                  f"{len(sample)} message(s) in front of you\n",
                           "good" if here else "dim")

                # Why is it catching nothing HERE?
                if enabled and here == 0 and sample:
                    blockers = _rule_blocking_conditions(flt, sample)
                    top_b = next((b for b in blockers if b["blocked"] > 0), None)
                    if top_b is None:
                        txt.insert("end",
                                   "      nothing here looks like it at all — "
                                   "that is fine if this folder is not where "
                                   "its mail arrives\n", "dim")
                    else:
                        txt.insert(
                            "end",
                            f"      ⚠  what is blocking it: "
                            f"{top_b['label']}\n", "warn")
                        txt.insert(
                            "end",
                            f"         drop that and it would match "
                            f"{top_b['would_match']} of them\n", "dim")
                        idx = len(self._rh_fixable)
                        self._rh_fixable[idx] = (flt, top_b)
                        b = tk.Button(
                            txt,
                            text=("✂  Drop those conditions from "
                                  f"“{name}”" if top_b["kind"] == "group"
                                  else f"✂  Drop that condition from “{name}”"),
                            bg=C_BTN_NEW, fg=C_BTN_FG,
                            font=("Segoe UI", 8, "bold"), relief="flat",
                            cursor="hand2", padx=8, pady=1,
                            command=lambda i=idx: _drop(i))
                        txt.window_create("end", window=b)
                        txt.insert("end", "\n")
                txt.insert("end", "\n")
            txt.configure(state="disabled")

        def _drop(i):
            flt, b = self._rh_fixable.get(i, (None, None))
            if flt is None:
                return
            name = flt.get("name") or flt.get("id", "")[:6]
            conds = flt.get("conditions") or []
            idxs = (sorted(b.get("indexes", []), reverse=True)
                    if b["kind"] == "group" else [b["index"]])
            if len(idxs) >= len(conds):
                messagebox.showwarning(
                    "Drop conditions",
                    "That is everything the rule tests — removing it would "
                    "make the rule match EVERY message. Edit or delete the "
                    "rule by hand instead.", parent=top)
                return
            listing = "\n".join(
                f"    {conds[i].get('field','')} {conds[i].get('op','')} "
                f"“{conds[i].get('value','')}”" for i in sorted(idxs))
            if not messagebox.askyesno(
                    "Drop conditions" if len(idxs) > 1 else "Drop a condition",
                    f"Remove {'these rows' if len(idxs) > 1 else 'this row'} "
                    f"from the rule “{name}”?\n\n{listing}\n\n"
                    f"The rule would then match {b['would_match']} of the "
                    f"messages loaded here instead of none.\n\n"
                    f"Everything else about the rule — its other conditions "
                    f"and all of its actions — stays exactly as it is. No mail "
                    f"is touched until the rule next runs.",
                    parent=top, default="no"):
                return
            removed = []
            for i in idxs:                       # highest index first
                removed.append(conds.pop(i))
            _save_filters(self._filter_store)
            what = "; ".join(f"{r.get('field')} {r.get('op')} "
                             f"“{r.get('value')}”" for r in reversed(removed))
            log.info("Rule health: dropped %d condition(s) from rule %r: %s",
                     len(removed), name, what)
            self._activity_log(
                "rule", rule=name,
                detail=f"dropped {len(removed)} condition(s) — {what} "
                       f"(they were blocking every match)")
            self._flash(f"{len(removed)} condition(s) removed from “{name}”")
            render()

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(fill="x", padx=14, pady=(0, 12))
        for text, colour, cmd in (
                ("Close", C_BTN_STD, top.destroy),
                ("Refresh", C_BTN_STD, render),
                ("Edit rules…", C_BTN_STD,
                 lambda: (top.destroy(), self._filters_dialog()))):
            tk.Button(btns, text=text, bg=colour, fg=C_BTN_FG,
                      font=("Segoe UI", 9), relief="flat", cursor="hand2",
                      padx=12, pady=4, command=cmd).pack(side="left", padx=4)
        render()

    # ── Mail filters ──────────────────────────────────────────────────────────
    def _filters_dialog(self, prefill_from="", prefill_msg=None):
        """Rules matched against every fetched message in every folder.

        Phase-1 safe by design: the action list contains only things this
        program can do to its OWN view. There is deliberately no "move to
        folder" or "delete" — those touch Gmail and belong to Phase 2.

        Pass prefill_msg to open a NEW rule pre-filled from that message
        (sender / subject / account), each criterion ticked but editable."""
        # Roomier: two condition sections, the live reading of the rule and the
        # action block no longer fit in 880×900 (Issu 2026-08-03). Clamped to
        # the screen so it can never open larger than the desktop.
        _sw = max(900, self.root.winfo_screenwidth())
        _sh = max(700, self.root.winfo_screenheight())
        top = self._dialog_shell("Mail filters",
                                 min(1240, int(_sw * 0.92)),
                                 min(1040, int(_sh * 0.92)))
        store = self._filter_store

        tk.Label(top,
                 text="Rules run on every folder and every account. Tick a "
                      "criterion to use it, and choose how it must match. "
                      "Everything here is LOCAL — Gmail is never changed.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 pady=4, wraplength=800, justify="left").pack(fill="x")

        body = tk.Frame(top, bg=C_BG3)
        body.pack(fill="both", expand=True, padx=12, pady=6)
        left = tk.Frame(body, bg=C_BG3)
        left.pack(side="left", fill="y")
        tk.Label(left, text="Rules", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9, "bold")).pack(anchor="w")
        lb = self._listbox(left, width=24)
        lb.pack(fill="y", expand=True, pady=4)

        # Reorder — filters run top-to-bottom, so order can matter.
        order_row = tk.Frame(left, bg=C_BG3)
        order_row.pack(fill="x")
        for txt, where in (("⤒", "top"), ("↑", "up"), ("↓", "down"),
                           ("⤓", "bottom")):
            tk.Button(order_row, text=txt, bg=C_BTN_STD, fg=C_BTN_FG,
                      font=("Segoe UI", 9), relief="flat", cursor="hand2",
                      width=2, padx=2, pady=1,
                      command=lambda w=where: _reorder(w)).pack(side="left",
                                                                padx=1)

        # Scrollable — the two condition sections below grow with every row
        # you add, and this dialog's height is otherwise fixed, so a 3rd or
        # 4th condition used to push the Save/Update row below the visible
        # window with no way to reach it (Issu 2026-08-06: "lägger jag till
        # en fjärde grej, så försvinner raden med Save"). Everything past
        # this point still just parents to `right` as before -- only its
        # container changed, from a plain Frame to one that scrolls.
        right_outer = tk.Frame(body, bg=C_BG3)
        right_outer.pack(side="left", fill="both", expand=True, padx=(12, 0))
        right_canvas = tk.Canvas(right_outer, bg=C_BG3, highlightthickness=0)
        right_canvas.pack(side="left", fill="both", expand=True)
        right_sb = tk.Scrollbar(right_outer, orient="vertical",
                                command=right_canvas.yview)
        right_sb.pack(side="right", fill="y")
        right_canvas.configure(yscrollcommand=right_sb.set)
        right = tk.Frame(right_canvas, bg=C_BG3)
        right_cwin = right_canvas.create_window((0, 0), window=right, anchor="nw")

        def _on_right_inner_configure(_e=None):
            right_canvas.configure(scrollregion=right_canvas.bbox("all"))
        def _on_right_canvas_configure(e):
            right_canvas.itemconfig(right_cwin, width=e.width)
        right.bind("<Configure>", _on_right_inner_configure)
        right_canvas.bind("<Configure>", _on_right_canvas_configure)
        _bind_mousewheel(right, right_canvas)

        def _scroll_into_view(widget):
            """Bring a widget inside this scrolling pane into sight.

            Focusing a box you cannot see is worse than not focusing it, so
            adding a condition scrolls to it as well as putting the cursor in
            it (Issu 2026-08-08)."""
            try:
                right_canvas.update_idletasks()
                total  = max(1, right.winfo_height())
                canv_h = max(1, right_canvas.winfo_height())
                # Position within the scrolled frame, not the screen.
                y = 0
                w = widget
                while w is not None and w is not right:
                    y += w.winfo_y()
                    w = w.master
                bot = y + max(1, widget.winfo_height()) + 30   # a little air
                y0 = right_canvas.canvasy(0)
                if y < y0:
                    right_canvas.yview_moveto(max(0.0, y / total))
                elif bot > y0 + canv_h:
                    right_canvas.yview_moveto(max(0.0, (bot - canv_h) / total))
            except Exception:
                pass

        e_name = self._labelled_entry(right, "Rule name:", width=12)

        _OP_BY_LABEL    = {v: k for k, v in _FILTER_OP_LABELS.items()}
        _FIELD_BY_LABEL = {v: k for k, v in _FILTER_FIELD_LABELS.items()}

        # ── Match: WHERE a suggested condition lands (Issu 2026-08-03) ───────
        #
        # This number no longer switches a rule between three modes — the three
        # modes are three SECTIONS below, and a rule uses as many of them as it
        # needs. It is a saved DEFAULT: which section gets the From/Subject
        # rows when a rule is built from a message, and which section a brand
        # new rule starts in. It must NOT move when you edit a rule, so it is
        # deliberately not bound to anything in the form.
        v_modenum = tk.StringVar(
            value=str(self.cfg.get("filter_default_section", "1")))
        v_every   = tk.BooleanVar(value=False)      # section 3, "All messages"
        mode_row = tk.Frame(right, bg=C_BG3); mode_row.pack(fill="x", pady=(4, 0))
        tk.Label(mode_row, text="Match:", bg=C_BG3, fg=C_FG_DIM, width=6,
                 anchor="e", font=("Segoe UI", 9)).pack(side="left")

        def _save_default_section(*_a):
            n = (v_modenum.get() or "1").strip()
            if n not in _FILTER_MODE_BY_NUM:
                return
            if str(self.cfg.get("filter_default_section", "1")) != n:
                self.cfg["filter_default_section"] = n
                _save_settings(self.cfg)

        sp_mode = tk.Spinbox(mode_row, from_=1, to=3, width=2,
                             textvariable=v_modenum, justify="center",
                             bg=C_BG2, fg=C_FG, buttonbackground=C_BG4,
                             relief="flat", font=("Segoe UI", 10, "bold"),
                             highlightthickness=0, insertbackground=C_ACCENT,
                             insertofftime=0, insertontime=9999999,
                             command=_save_default_section)
        no_blink(sp_mode)
        sp_mode.pack(side="left", padx=(0, 8))
        v_modenum.trace_add("write", _save_default_section)
        tk.Label(mode_row,
                 text="where a suggested condition goes, and where a new rule "
                      "starts.  Remembered — it does NOT change while you edit "
                      "a rule.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8),
                 anchor="w", wraplength=460,
                 justify="left").pack(side="left", fill="x", expand=True)
        add_tooltip(sp_mode,
                    "1 = the MUST section   ·   2 = the either/or section   ·  "
                    " 3 = all messages.\nThis is a saved default for NEW rules, "
                    "not a switch on the rule you are editing.")

        # ── The two condition sections ───────────────────────────────────────
        #
        #   MUST      every row here has to match          (AND)
        #   EITHER    at least one row here has to match   (OR)
        #
        # and the rule fires when both hold — "From is dhl.se AND the subject
        # is either A or B", which is precisely what could not be said before
        # and what forced one near-identical rule per subject line.
        cond_rows = []                       # every row, both sections
        hosts = {}

        def _section(group, colour):
            wrap = tk.Frame(right, bg=C_BG3)
            wrap.pack(fill="x", pady=(6, 0))
            head = tk.Frame(wrap, bg=C_BG3)
            head.pack(fill="x")
            tk.Frame(head, bg=colour, width=3).pack(side="left", fill="y")
            tk.Label(head, text="  " + _SECTION_TITLE[group], bg=C_BG3,
                     fg=colour, font=("Segoe UI", 9, "bold"),
                     anchor="w").pack(side="left")
            b = tk.Button(head, text="+", bg=C_BTN_NEW, fg=C_BTN_FG,
                          relief="flat", cursor="hand2",
                          font=("Segoe UI", 9, "bold"), width=2,
                          command=lambda g=group: _add_cond_row(group=g))
            b.pack(side="right", padx=4)
            add_tooltip(b, "Add a condition to this section")
            if group == "any":
                # The letter box is the whole of the pairs feature and it is
                # two characters wide — it has to say what it is somewhere the
                # eye lands, or it reads as decoration. On its OWN line:
                # beside a 48-character bold heading and the + button it would
                # simply be cut off, which is the same as not being there.
                tk.Label(wrap,
                         text="     the letter box pairs rows — two rows with "
                              "the SAME letter are ONE alternative and have to "
                              "match together.   “–” = the row on its own.",
                         bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8),
                         anchor="w", justify="left",
                         wraplength=500).pack(fill="x")
            host = tk.Frame(wrap, bg=C_BG3)
            host.pack(fill="x", padx=(10, 0))
            hosts[group] = host
            return wrap

        _section("all", C_ACCENT)
        _section("any", "#c9a227")

        def _add_cond_row(field="from", op="contains", value="", group="all",
                          pair="", focus=True):
            # focus=False when a whole rule is being LOADED into the form —
            # then the cursor belongs in the rule name, not in the last
            # condition row that happened to be rebuilt.
            row = tk.Frame(hosts[group], bg=C_BG3); row.pack(fill="x", pady=2)
            # ── The pair letter (Issu 2026-09-07) ────────────────────────────
            # Only in the either/or section, because pairing is what turns two
            # of its rows into ONE alternative. Two rows set to the same letter
            # have to match together; "–" leaves a row standing on its own,
            # which is what every row saved before pairs existed is.
            pv = None
            if group == "any":
                pv = tk.StringVar(value=_cond_pair({"pair": pair}) or _PAIR_NONE)
                pm = tk.OptionMenu(row, pv, *([_PAIR_NONE] + list(_PAIR_LABELS)))
                pm.configure(bg=C_BG2, fg="#c9a227", activebackground=C_BG4,
                             activeforeground=C_FG, highlightthickness=0,
                             relief="flat", font=("Segoe UI", 8, "bold"),
                             width=2, anchor="w")
                pm["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                                     activeforeground=C_FG)
                pm.pack(side="left", padx=(0, 3))
                add_tooltip(pm,
                            "Pair this row with another either/or row.\n"
                            "Same letter = ONE alternative: BOTH of those rows "
                            "have to match.\n"
                            "“–” = the row stands alone, an alternative by "
                            "itself (how it has always worked).\n\n"
                            "A → Subject “Beställningsuppdatering” + From "
                            "“vinted”\n"
                            "B → Subject “är på väg!” + From “sellpy”\n"
                            "= one rule that catches both, and nothing in "
                            "between.")
                pv.trace_add("write", lambda *a: _describe())
            fv = tk.StringVar(value=_FILTER_FIELD_LABELS.get(field, "From"))
            fm = tk.OptionMenu(row, fv, *[_FILTER_FIELD_LABELS[f]
                                          for f in _FILTER_FIELDS])
            fm.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                         activeforeground=C_FG, highlightthickness=0,
                         relief="flat", font=("Segoe UI", 8), width=8,
                         anchor="w")
            fm["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                                 activeforeground=C_FG)
            fm.pack(side="left", padx=(0, 3))
            ov = tk.StringVar(value=_FILTER_OP_LABELS.get(op, "contains"))
            om = tk.OptionMenu(row, ov, *[_FILTER_OP_LABELS[o]
                                          for o in _FILTER_OPS])
            om.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                         activeforeground=C_FG, highlightthickness=0,
                         relief="flat", font=("Segoe UI", 8), width=11,
                         anchor="w")
            om["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                                 activeforeground=C_FG)
            om.pack(side="left", padx=(0, 3))
            ev = tk.Entry(row, bg=C_BG2, fg=C_FG, relief="flat",
                          insertbackground=C_ACCENT, font=("Segoe UI", 10),
                          insertofftime=0, insertontime=9999999)
            no_blink(ev)
            ev.insert(0, value)
            ev.pack(side="left", fill="x", expand=True, ipady=2)
            rd = {"frame": row, "fv": fv, "ov": ov, "ev": ev,
                  "group": group, "pv": pv}

            def _rm():
                if rd in cond_rows:
                    cond_rows.remove(rd)
                row.destroy()
                _describe()
            # "→" moves a row to the OTHER section without retyping it: that is
            # the gesture in Issu's own example — keep From in MUST, push the
            # Subject over to the either/or side.
            other = "any" if group == "all" else "all"
            b_move = tk.Button(
                row, text=("↓" if group == "all" else "↑"),
                bg=C_BTN_STD, fg=C_BTN_FG, relief="flat", cursor="hand2",
                font=("Segoe UI", 9), width=2,
                command=lambda: (_add_cond_row(
                    _FIELD_BY_LABEL.get(fv.get(), "from"),
                    _OP_BY_LABEL.get(ov.get(), "contains"),
                    ev.get(), other), _rm()))
            b_move.pack(side="left", padx=(3, 0))
            add_tooltip(b_move, f"Move this row to the "
                                f"“{_SECTION_TITLE[other]}” section")
            tk.Button(row, text="+", bg=C_BTN_STD, fg=C_BTN_FG, relief="flat",
                      cursor="hand2", font=("Segoe UI", 9), width=2,
                      command=lambda g=group: _add_cond_row(group=g)).pack(
                          side="left", padx=(2, 0))
            tk.Button(row, text="−", bg=C_BTN_STD, fg=C_BTN_FG, relief="flat",
                      cursor="hand2", font=("Segoe UI", 9), width=2,
                      command=_rm).pack(side="left", padx=(2, 0))
            for w in (ev,):
                w.bind("<KeyRelease>", lambda e: _describe())
            fv.trace_add("write", lambda *a: _describe())
            ov.trace_add("write", lambda *a: _describe())
            cond_rows.append(rd)
            _describe()
            # ── The cursor lands in the new box (Issu 2026-08-08) ─────────────
            # "Mail filters… när jag lägger till ny (+), se till att jag hamnar
            # i det skrivfältet, med markören." Pressing + is a statement of
            # intent: you are about to type the thing you want matched. Having
            # to hunt for the field and click it first is pure friction.
            #
            # after_idle, because the row is still being laid out at this point
            # and focusing a widget that has not been mapped does nothing.
            if focus:
                try:
                    ev.after_idle(lambda: (ev.focus_set(), ev.icursor("end")))
                    ev.after_idle(lambda: _scroll_into_view(ev))
                except Exception:
                    pass
            return rd

        def _clear_cond_rows():
            for rd in list(cond_rows):
                try:
                    rd["frame"].destroy()
                except Exception:
                    pass
            cond_rows.clear()

        def _gather_conditions():
            """The rows as condition dicts, MUST section first."""
            out = []
            for g in ("all", "any"):
                for rd in cond_rows:
                    if rd["group"] != g:
                        continue
                    val = rd["ev"].get().strip()
                    if not val:
                        continue
                    row = {
                        "field": _FIELD_BY_LABEL.get(rd["fv"].get(), "from"),
                        "op":    _OP_BY_LABEL.get(rd["ov"].get(), "contains"),
                        "value": val, "group": g}
                    pair = (_cond_pair({"pair": rd["pv"].get()})
                            if rd.get("pv") is not None else "")
                    if pair:
                        row["pair"] = pair
                    out.append(row)
            return out

        def _set_conditions(conds, default_group=None):
            _clear_cond_rows()
            fallback = default_group or "all"
            for c in (conds or []):
                _add_cond_row(c.get("field", "from"),
                              c.get("op", "contains"), c.get("value", ""),
                              group=(c.get("group") or fallback),
                              pair=c.get("pair", ""), focus=False)
            if not cond_rows:
                _add_cond_row(group=fallback, focus=False)

        # ── Section 3 + a live plain-English reading of the rule ─────────────
        every_row = tk.Frame(right, bg=C_BG3); every_row.pack(fill="x", pady=(6, 0))
        tk.Checkbutton(every_row, text=_SECTION_TITLE["every"] +
                                       " — ignore the conditions above",
                       variable=v_every, bg=C_BG3, fg="#c05a5a",
                       selectcolor=C_BG2, activebackground=C_BG3,
                       activeforeground="#c05a5a",
                       font=("Segoe UI", 9, "bold"), highlightthickness=0,
                       command=lambda: _describe()).pack(side="left")

        lbl_logic = tk.Label(right, text="", bg=C_BG2, fg=C_ACCENT,
                             font=("Segoe UI", 8), anchor="w", justify="left",
                             wraplength=520, padx=8, pady=4)
        lbl_logic.pack(fill="x", pady=(4, 0))

        def _describe(*_a):
            """Keep the one-line reading of the rule true as it is typed —
            a two-section form is easy to misread, a sentence is not."""
            try:
                lbl_logic.configure(text=_filter_describe({
                    "match_mode": "every" if v_every.get() else "groups",
                    "conditions": _gather_conditions(),
                    "has_attachment": bool(v_attach.get())}))
            except Exception:
                pass

        tk.Label(right, text="   pick a field, how it must match, and the text. "
                             "+ adds a row to that section, − removes it, "
                             "↓ / ↑ moves a row to the other section.\n"
                             "   In section 2 the letter box PAIRS rows: give "
                             "two rows the same letter and they count as ONE "
                             "alternative that has to match together — "
                             "A = subject “Beställningsuppdatering” + from "
                             "“vinted”, B = subject “är på väg!” + from "
                             "“sellpy”, and the one rule catches both. "
                             "“–” leaves a row on its own, as before.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 7),
                 anchor="w", justify="left").pack(fill="x")

        # ── "Body has": pick words straight out of a real message ────────────
        # Instead of typing body text from memory, open the selected message,
        # highlight the words you want, and drop them straight into a Body
        # condition row. Field defaults to Body but you can retarget it.
        def _pick_from_body():
            msg = getattr(self, "_selected_msg", None)
            if not msg:
                messagebox.showinfo(
                    "Pick from message",
                    "Open (select) a message in the list first — then its full "
                    "text opens here for you to highlight words in.",
                    parent=top)
                return
            self._body_word_picker(top, msg, _add_cond_row)

        pick_row = tk.Frame(right, bg=C_BG3); pick_row.pack(fill="x", pady=(2, 0))
        tk.Button(pick_row, text="📄  Pick words from the open message…",
                  bg=C_BTN_STD, fg=C_BTN_FG, font=("Segoe UI", 8),
                  relief="flat", cursor="hand2", padx=8, pady=2,
                  command=_pick_from_body).pack(side="left")

        # Auto vs only-manual (Issu's request; default Auto).
        v_run = tk.StringVar(value="auto")
        runrow = tk.Frame(right, bg=C_BG3); runrow.pack(fill="x", pady=(6, 0))
        tk.Label(runrow, text="When to run:", bg=C_BG3, fg=C_FG_DIM, width=12,
                 anchor="e", font=("Segoe UI", 9)).pack(side="left")
        for val, text in (("auto", "Auto (on every new-mail check)"),
                          ("manual", "Only when I run filters")):
            tk.Radiobutton(runrow, text=text, value=val, variable=v_run,
                           bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                           activebackground=C_BG3, activeforeground=C_FG,
                           font=("Segoe UI", 8),
                           highlightthickness=0).pack(side="left", padx=2)

        # ── Extra triggers (DEL 04z2): archive / after-send ──────────────────
        v_run_archive = tk.BooleanVar(value=False)
        v_run_sent    = tk.BooleanVar(value=False)
        trigrow = tk.Frame(right, bg=C_BG3); trigrow.pack(fill="x")
        tk.Label(trigrow, text="Also run:", bg=C_BG3, fg=C_FG_DIM, width=12,
                 anchor="e", font=("Segoe UI", 9)).pack(side="left")
        tk.Checkbutton(trigrow, text="when I archive a message",
                       variable=v_run_archive, bg=C_BG3, fg=C_FG,
                       selectcolor=C_BG2, activebackground=C_BG3,
                       activeforeground=C_FG, font=("Segoe UI", 8),
                       highlightthickness=0).pack(side="left", padx=2)
        tk.Checkbutton(trigrow, text="right after a message is sent",
                       variable=v_run_sent, bg=C_BG3, fg=C_FG,
                       selectcolor=C_BG2, activebackground=C_BG3,
                       activeforeground=C_FG, font=("Segoe UI", 8),
                       highlightthickness=0).pack(side="left", padx=2)

        # ── Run-on-a-chosen-folder scope (DEL 04z2) ──────────────────────────
        # Limit a rule to one or more folders. Empty = every folder. Click a
        # name below to add it; or type them comma-separated.
        foldrow = tk.Frame(right, bg=C_BG3); foldrow.pack(fill="x", pady=(4, 0))
        tk.Label(foldrow, text="Only in folders:", bg=C_BG3, fg=C_FG_DIM,
                 width=12, anchor="e", font=("Segoe UI", 9)).pack(side="left")
        e_folders = tk.Entry(foldrow, bg=C_BG2, fg=C_FG, relief="flat",
                             insertbackground=C_ACCENT, font=("Segoe UI", 10),
                             insertofftime=0, insertontime=9999999)
        no_blink(e_folders)
        e_folders.pack(side="left", fill="x", expand=True, ipady=2)

        def _add_folder(name):
            have = [p.strip() for p in e_folders.get().split(",") if p.strip()]
            if name not in have:
                have.append(name)
            e_folders.delete(0, "end")
            e_folders.insert(0, ", ".join(have))

        fbtns = tk.Frame(right, bg=C_BG3); fbtns.pack(fill="x")
        tk.Label(fbtns, text=" " * 13, bg=C_BG3,
                 font=("Segoe UI", 7)).pack(side="left")
        for _fname in ("Inbox", "Sent", "Archive", "Spam", "Trash"):
            tk.Button(fbtns, text=_fname, bg=C_BG2, fg=C_FG_DIM,
                      font=("Segoe UI", 7), relief="flat", cursor="hand2",
                      padx=5, pady=0,
                      command=lambda n=_fname: _add_folder(n)).pack(
                          side="left", padx=1)
        tk.Label(right, text="              empty = run in every folder; "
                             "names are comma-separated",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 7),
                 anchor="w").pack(fill="x")

        # ── For this account only (Issu 2026-08-15) ───────────────────────────
        # Every rule runs on every account by default — that is the whole
        # point of, say, a Tradera shipping-receipt rule, since the same
        # kind of mail can land on more than one account. This is the
        # deliberate exception: pick one account and the rule becomes
        # invisible everywhere else, the same idea as "Only in folders:"
        # just above but for accounts instead of folders.
        _ALL_ACCTS = "(all accounts)"
        _real_emails = [a["email"] for a in self._accounts
                        if not a.get("virtual")]
        v_match_acct = tk.StringVar(value=_ALL_ACCTS)
        acctrow = tk.Frame(right, bg=C_BG3); acctrow.pack(fill="x", pady=(2, 0))
        tk.Label(acctrow, text="Only on account:", bg=C_BG3, fg=C_FG_DIM,
                 width=12, anchor="e", font=("Segoe UI", 9)).pack(side="left")
        om_match_acct = tk.OptionMenu(acctrow, v_match_acct, _ALL_ACCTS,
                                      *_real_emails)
        om_match_acct.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                                activeforeground=C_FG, highlightthickness=0,
                                relief="flat", font=("Segoe UI", 9),
                                anchor="w")
        om_match_acct["menu"].configure(bg=C_BG2, fg=C_FG,
                                        activebackground=C_BG4,
                                        activeforeground=C_FG)
        om_match_acct.pack(side="left", fill="x", expand=True, padx=(4, 0))

        v_enabled = tk.BooleanVar(value=True)
        v_attach  = tk.BooleanVar(value=False)
        v_read    = tk.BooleanVar(value=False)
        v_unread  = tk.BooleanVar(value=False)
        v_hide    = tk.BooleanVar(value=False)
        v_star    = tk.BooleanVar(value=False)
        v_spam        = tk.BooleanVar(value=False)
        v_spam_domain = tk.BooleanVar(value=False)
        v_unsub       = tk.StringVar(value="")     # "" | "offer" | "auto"
        v_notify  = tk.StringVar(value="default")
        v_trash   = tk.BooleanVar(value=False)
        v_seen_s  = tk.BooleanVar(value=False)
        v_flag_s  = tk.BooleanVar(value=False)
        v_rescue  = tk.BooleanVar(value=False)
        v_protect = tk.BooleanVar(value=True)
        # Wait before acting (DEL 04z3). Stored as minutes; edited as a number
        # plus a unit, because "26 hours" is how he says it and 1560 is not.
        v_delay_unit   = tk.StringVar(value="hours")
        v_delay_unread = tk.BooleanVar(value=True)

        opt = tk.Frame(right, bg=C_BG3)
        opt.pack(fill="x", pady=(8, 0))

        def _chk(parent, text, var):
            return tk.Checkbutton(parent, text=text, variable=var, bg=C_BG3,
                                  fg=C_FG, selectcolor=C_BG2,
                                  activebackground=C_BG3, activeforeground=C_FG,
                                  font=("Segoe UI", 9), highlightthickness=0,
                                  relief="flat", anchor="w")

        # Tag choices (built once; used by the compact "Tag" dropdown below).
        _ftag_opts = [("", "(no tag)")] + [
            (t["id"], f"{t.get('icon', '●')} {t['name']}")
            for t in self._tag_store.get("tags", [])]
        _ftag_label_by_id = {tid: lbl for tid, lbl in _ftag_opts}
        _ftag_id_by_label = {lbl: tid for tid, lbl in _ftag_opts}

        _r0 = tk.Frame(opt, bg=C_BG3); _r0.pack(fill="x")
        _chk(_r0, "Rule is enabled", v_enabled).pack(side="left")
        _chk(_r0, "Only messages WITH attachments", v_attach).pack(
            side="left", padx=(16, 0))

        tk.Frame(opt, bg=C_SEP, height=1).pack(fill="x", pady=6)
        tk.Label(opt, text="Then do this  (in F(re)email — and, with Server "
                           "changes ON, on Gmail too):",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9, "bold"),
                 anchor="w", justify="left", wraplength=540).pack(fill="x")

        # Actions — several to a row to save height. "Mark read" and "Star"
        # apply BOTH here AND on Gmail (Issu: "allt kan vara på bägge,
        # samtidigt") — the Gmail half runs when Server changes is on.
        _r1 = tk.Frame(opt, bg=C_BG3); _r1.pack(fill="x")
        _chk(_r1, "Mark read (+ on Gmail)", v_read).pack(side="left")
        _chk(_r1, "Mark unread", v_unread).pack(side="left", padx=(10, 0))
        _chk(_r1, "Star (+ on Gmail)", v_star).pack(side="left", padx=(10, 0))
        _r2 = tk.Frame(opt, bg=C_BG3); _r2.pack(fill="x")
        _chk(_r2, "Hide from the list", v_hide).pack(side="left")
        _chk(_r2, "Mark as spam", v_spam).pack(side="left", padx=(10, 0))
        _r3 = tk.Frame(opt, bg=C_BG3); _r3.pack(fill="x")
        tk.Label(_r3, text="      ", bg=C_BG3,
                 font=("Segoe UI", 7)).pack(side="left")
        _chk(_r3, "…everything from the whole domain (ignore what's before @)",
             v_spam_domain).pack(side="left")

        # ── Unsubscribe (DEL 04e2, Issu 2026-08-29) ──────────────────────────
        # "Jag har auto-trash på den; det hade varit gott om jag även kunnat
        # välja avregistrera." Sits directly under the junk actions, because
        # that is the rule you are editing when you want this.
        def _unsub_picked():
            """Ticking "automatically" is the one setting here that reaches
            out to somebody else's server with nobody watching. It is allowed
            — he asked for it — but it is not allowed to happen because a
            radio button was near the mouse."""
            if v_unsub.get() != "auto":
                return
            if not messagebox.askyesno(
                    "Unsubscribe without asking?",
                    "This rule will unsubscribe by itself, with no "
                    "confirmation, from every list it matches.\n\n"
                    "It only ever uses a route the sender declared in a "
                    "header (one-click, or the List-Unsubscribe address) — a "
                    "link found in the message text is never followed "
                    "automatically, and goes on the waiting list instead.\n\n"
                    "Remember that leaving a list also confirms your address "
                    "is real. For actual spam, trash and block it instead.\n\n"
                    "Set this rule to unsubscribe automatically?",
                    parent=top, default="no"):
                v_unsub.set("offer")

        tk.Frame(opt, bg=C_SEP, height=1).pack(fill="x", pady=6)
        _ru = tk.Frame(opt, bg=C_BG3); _ru.pack(fill="x")
        tk.Label(_ru, text="✖ Unsubscribe:", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 9, "bold")).pack(side="left")
        for val, text in (("", "no"),
                          ("offer", "collect them for me"),
                          ("auto", "do it automatically")):
            tk.Radiobutton(_ru, text=text, value=val, variable=v_unsub,
                           bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                           activebackground=C_BG3, activeforeground=C_FG,
                           font=("Segoe UI", 9), highlightthickness=0,
                           command=_unsub_picked).pack(side="left", padx=6)
        tk.Label(opt,
                 text="   “Collect them” contacts nobody: matching mail whose "
                      "sender offers a way out goes on a list you clear in one "
                      "pass (Tools ▸ Unsubscribes waiting), so a rule that "
                      "trashes a newsletter can also get you off it. "
                      "“Automatically” only uses a route the SENDER declared "
                      "in a header — RFC 8058 one-click, or the "
                      "List-Unsubscribe address — never a link merely found in "
                      "the text. Either way a list you have already left is "
                      "never asked twice.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 7, "italic"),
                 anchor="w", justify="left", wraplength=540).pack(fill="x")

        # Tag + colour + snooze on ONE compact row.
        _r4 = tk.Frame(opt, bg=C_BG3); _r4.pack(fill="x", pady=(4, 0))
        tk.Label(_r4, text="Tag:", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left")
        v_ftag = tk.StringVar(value="(no tag)")
        om_ftag = tk.OptionMenu(_r4, v_ftag, *[lbl for _t, lbl in _ftag_opts])
        om_ftag.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                          activeforeground=C_FG, highlightthickness=0,
                          relief="flat", font=("Segoe UI", 9), anchor="w")
        om_ftag["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                                  activeforeground=C_FG)
        om_ftag.pack(side="left", padx=(2, 0))
        tk.Label(_r4, text="Colour:", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left", padx=(12, 2))
        e_colour = tk.Entry(_r4, bg=C_BG2, fg=C_FG, relief="flat", width=9,
                            insertbackground=C_ACCENT, font=("Segoe UI", 10),
                            insertofftime=0, insertontime=9999999)
        no_blink(e_colour); e_colour.pack(side="left")
        tk.Label(_r4, text="Snooze:", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left", padx=(12, 2))
        e_snooze = tk.Entry(_r4, bg=C_BG2, fg=C_FG, relief="flat", width=5,
                           insertbackground=C_ACCENT, font=("Segoe UI", 10),
                           insertofftime=0, insertontime=9999999)
        no_blink(e_snooze); e_snooze.pack(side="left")
        tk.Label(_r4, text="min", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(side="left", padx=(2, 0))
        tk.Label(opt, text="   colour = #rrggbb (e.g. #3a2b55)   ·   manage "
                           "tags under View → Tags",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 7),
                 anchor="w").pack(fill="x")

        # Notify on ONE row.
        nrow = tk.Frame(opt, bg=C_BG3); nrow.pack(fill="x", pady=(2, 0))
        tk.Label(nrow, text="Notify:", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left")
        for val, text in (("default", "as usual"), ("always", "always"),
                          ("never", "never")):
            tk.Radiobutton(nrow, text=text, value=val, variable=v_notify,
                           bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                           activebackground=C_BG3, activeforeground=C_FG,
                           font=("Segoe UI", 9),
                           highlightthickness=0).pack(side="left", padx=4)

        # ── Wait before acting (DEL 04z3, Issu 2026-08-17) ───────────────────
        tk.Frame(opt, bg=C_SEP, height=1).pack(fill="x", pady=6)
        drow = tk.Frame(opt, bg=C_BG3); drow.pack(fill="x")
        tk.Label(drow, text="⏳ Wait before acting:", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 9, "bold")).pack(side="left")
        e_delay = tk.Entry(drow, bg=C_BG2, fg=C_FG, relief="flat", width=6,
                           insertbackground=C_ACCENT, font=("Segoe UI", 10),
                           insertofftime=0, insertontime=9999999)
        no_blink(e_delay)
        e_delay.pack(side="left", padx=(6, 3), ipady=2)
        om_dunit = tk.OptionMenu(drow, v_delay_unit, *_DELAY_UNITS)
        om_dunit.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                           activeforeground=C_FG, highlightthickness=0,
                           relief="flat", font=("Segoe UI", 9), anchor="w",
                           width=7)
        om_dunit["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                                   activeforeground=C_FG)
        om_dunit.pack(side="left")
        tk.Label(drow, text="after the mail arrived   (0 = act at once)",
                 bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(side="left", padx=(6, 0))
        tk.Label(opt, text="   The exception, not the rule: leave it at 0 and "
                           "this rule behaves exactly as before. Set it and the "
                           "rule ignores a message until it is that old, then "
                           "files it on the next check — so a buyer's “I'm "
                           "interested in…” can sit in the Inbox for 26 hours "
                           "and go to Temporär/Köpare by itself afterwards. "
                           "Counted from the message's OWN date, so it does not "
                           "matter whether the program was running; nothing is "
                           "queued, the rule is simply re-judged each check "
                           "against the mail as it actually is now.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 7, "italic"),
                 anchor="w", justify="left", wraplength=540).pack(fill="x")
        _chk(opt, "…and anything unread STAYS unread when it is filed",
             v_delay_unread).pack(anchor="w")
        tk.Label(opt, text="   On by default for a waiting rule. It refuses "
                           "this rule's own “mark read” (here and on Gmail) and "
                           "overrides the destination's “mail here reads "
                           "itself”, so filed mail keeps standing out until YOU "
                           "open it. It never makes already-read mail unread "
                           "again.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 7, "italic"),
                 anchor="w", justify="left", wraplength=540).pack(fill="x")

        # ── On Gmail (server-side actions, DEL 04y) ──────────────────────────
        tk.Frame(opt, bg=C_SEP, height=1).pack(fill="x", pady=6)
        tk.Label(opt, text="…and on Gmail itself  (needs Tools → Server "
                           "changes ON):",
                 bg=C_BG3, fg="#e0b050", font=("Segoe UI", 9, "bold"),
                 anchor="w").pack(fill="x")
        mrow = tk.Frame(opt, bg=C_BG3); mrow.pack(fill="x", pady=(2, 0))
        tk.Label(mrow, text="Move to folder:", bg=C_BG3, fg=C_FG_DIM,
                 anchor="e", font=("Segoe UI", 9)).pack(side="left")
        e_move = tk.Entry(mrow, bg=C_BG2, fg=C_FG, relief="flat",
                          insertbackground=C_ACCENT, font=("Segoe UI", 10),
                          insertofftime=0, insertontime=9999999)
        no_blink(e_move)
        e_move.pack(side="left", fill="x", expand=True, ipady=3, padx=(4, 4))

        # On WHICH account — "(same account)" or another account. Picking another
        # account = a cross-account move (upload to it + trash the source), which
        # is exactly Issu's Tradera→main-account rule.
        _SAME = "(same account)"
        v_move_acct = tk.StringVar(value=_SAME)

        # Browse: on >1 account, pick the account AND folder in one go (sets both
        # fields); otherwise just the folder on the one account.
        def _browse_move():
            if len(_real_emails) > 1:
                acct, folder = self._pick_account_and_folder(
                    "Move matching mail to…",
                    None if v_move_acct.get() == _SAME else v_move_acct.get())
                if folder:
                    e_move.delete(0, "end"); e_move.insert(0, folder)
                    if acct:
                        v_move_acct.set(acct)
            else:
                picked = self._pick_target_folder("Move matching mail to…")
                if picked:
                    e_move.delete(0, "end"); e_move.insert(0, picked)
        tk.Button(mrow, text="Browse…", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 8), relief="flat", cursor="hand2",
                  padx=8, pady=1, command=_browse_move).pack(side="left")

        arow2 = tk.Frame(opt, bg=C_BG3); arow2.pack(fill="x")
        tk.Label(arow2, text="on account:", bg=C_BG3, fg=C_FG_DIM,
                 anchor="e", font=("Segoe UI", 9)).pack(side="left")
        om_macct = tk.OptionMenu(arow2, v_move_acct, _SAME, *_real_emails)
        om_macct.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                          activeforeground=C_FG, highlightthickness=0,
                          relief="flat", font=("Segoe UI", 9), anchor="w")
        om_macct["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                                   activeforeground=C_FG)
        om_macct.pack(side="left", fill="x", expand=True, padx=(4, 4))
        tk.Label(opt, text="   folder/label name — created if missing. Leave "
                           "account “(same account)” for a normal move; pick "
                           "ANOTHER account to move it there (Tradera receipts → "
                           "issusbarn@… / Inbox/Temporär/0---Frakt & Kvitto). "
                           "Empty = don't move.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 7),
                 anchor="w", justify="left", wraplength=540).pack(fill="x")
        _chk(opt, "🔒 Protect destination folder — nothing automatic (this "
                  "rule, another rule, or month-folder filing) may move mail "
                  "back OUT of it", v_protect).pack(anchor="w")
        tk.Label(opt, text="   On by default: once mail is filed here on "
                           "purpose, it stays filed. Applied the moment you "
                           "save this rule — untick only for a destination "
                           "you WANT other automatic moves to keep touching.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 7, "italic"),
                 anchor="w", justify="left", wraplength=540).pack(fill="x")
        _rg = tk.Frame(opt, bg=C_BG3); _rg.pack(fill="x")
        _chk(_rg, "Delete → Trash", v_trash).pack(side="left")
        _chk(_rg, "↩ Rescue from Trash", v_rescue).pack(side="left", padx=(10, 0))
        # (Mark-read / Star on Gmail are folded into the "+ on Gmail" checkboxes
        # above — Issu wants one action that hits both, not two rows.)
        tk.Label(opt, text="   Auto-trash never touches mail you sent to "
                           "yourself. Permanent erase stays manual.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 7, "italic"),
                 anchor="w", justify="left", wraplength=540).pack(fill="x")
        tk.Label(opt, text="   Rescue = if a matching message is already "
                           "sitting in Gmail's Trash (e.g. Gmail auto-"
                           "trashed it before you ever saw it), deliver it "
                           "straight to THIS rule's own destination above, "
                           "in one step — same account: an ordinary move; "
                           "another account: a copy is appended there, "
                           "checked first so the same message is never "
                           "copied twice, and the Trash original is simply "
                           "left alone (never deleted automatically).",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 7, "italic"),
                 anchor="w", justify="left", wraplength=540).pack(fill="x")

        def _refresh():
            lb.delete(0, "end")
            for f in store.get("filters", []):
                mark = "" if f.get("enabled", True) else "  (off)"
                lb.insert("end", (f.get("name") or "(unnamed)") + mark)

        def _idx():
            cur = lb.curselection()
            return cur[0] if cur else -1

        def _load(event=None):
            i = _idx()
            if i < 0:
                return
            f = store["filters"][i]
            e_name.delete(0, "end"); e_name.insert(0, f.get("name", "") or "")
            # Read the rule through _split_conditions, so a filter saved before
            # sections existed lands in the right section by itself — a
            # "match any" rule fills the either/or side, a "match all" rule the
            # MUST side. NOTHING here touches the Match number box: it is a
            # saved default, not a property of the rule being edited.
            must, either = _split_conditions(f)
            v_every.set(f.get("match_mode", "all") == "every")
            _set_conditions([dict(c, group="all") for _i, c in must]
                            + [dict(c, group="any") for _i, c in either])
            e_colour.delete(0, "end"); e_colour.insert(0, f.get("action_color", "") or "")
            e_snooze.delete(0, "end")
            e_snooze.insert(0, str(f.get("action_snooze_min", 0) or 0))
            v_enabled.set(bool(f.get("enabled", True)))
            v_attach.set(bool(f.get("has_attachment")))
            # Read/star are now single "here + Gmail" toggles, so an old rule
            # that only set the Gmail half still shows the box ticked.
            v_read.set(bool(f.get("action_read") or f.get("action_seen_server")))
            v_unread.set(bool(f.get("action_unread")))
            v_hide.set(bool(f.get("action_hide")))
            v_star.set(bool(f.get("action_star") or f.get("action_flag_server")))
            v_notify.set(f.get("action_notify", "default"))
            v_run.set("auto" if f.get("run_on_fetch", True) else "manual")
            v_run_archive.set(bool(f.get("run_on_archive")))
            v_run_sent.set(bool(f.get("run_on_sent")))
            e_folders.delete(0, "end")
            e_folders.insert(0, f.get("run_folders", "") or "")
            v_match_acct.set(f.get("match_account", "") or _ALL_ACCTS)
            e_move.delete(0, "end"); e_move.insert(0, f.get("action_move", "") or "")
            v_move_acct.set(f.get("action_move_account", "") or _SAME)
            v_ftag.set(_ftag_label_by_id.get(f.get("action_tag", "") or "",
                                             "(no tag)"))
            v_spam.set(bool(f.get("action_spam")))
            v_spam_domain.set(bool(f.get("action_spam_domain")))
            v_unsub.set((f.get("action_unsub") or "") if
                        (f.get("action_unsub") or "") in ("offer", "auto")
                        else "")
            v_trash.set(bool(f.get("action_trash")))
            v_seen_s.set(bool(f.get("action_seen_server")))
            v_flag_s.set(bool(f.get("action_flag_server")))
            v_rescue.set(bool(f.get("action_rescue_trash")))
            # setdefault-backfilled to True for old filters (see
            # _FILTER_DEFAULTS), so .get(..., True) matches that for a
            # filter dict that somehow still lacks the key.
            v_protect.set(bool(f.get("action_protect_dest", True)))
            _dn, _du = _delay_from_minutes(f.get("delay_min", 0))
            e_delay.delete(0, "end"); e_delay.insert(0, str(_dn))
            v_delay_unit.set(_du)
            v_delay_unread.set(bool(f.get("delay_keep_unread", True)))

        lb.bind("<<ListboxSelect>>", _load)

        def _default_group():
            """Which section a new/suggested condition goes into — the saved
            Match number, NOT anything about the rule being edited."""
            return _FILTER_MODE_BY_NUM.get((v_modenum.get() or "1").strip(),
                                           "all")

        def _new():
            lb.selection_clear(0, "end")
            e_name.delete(0, "end")
            # A brand-new rule starts in the section the Match number names
            # (1 = MUST, 2 = either/or, 3 = all messages). The number itself is
            # never touched here — it is the default, not a property of a rule.
            g = _default_group()
            v_every.set(g == "every")
            _set_conditions([{"field": "from", "op": "contains", "value": "",
                              "group": "all" if g == "every" else g}])
            for e in (e_colour, e_move, e_folders):
                e.delete(0, "end")
            v_move_acct.set(_SAME)
            v_match_acct.set(_ALL_ACCTS)
            v_ftag.set("(no tag)")
            e_snooze.delete(0, "end"); e_snooze.insert(0, "0")
            for v in (v_attach, v_read, v_unread, v_hide, v_star,
                      v_spam, v_spam_domain,
                      v_trash, v_seen_s, v_flag_s, v_rescue,
                      v_run_archive, v_run_sent):
                v.set(False)
            v_unsub.set("")
            v_protect.set(True)
            e_delay.delete(0, "end"); e_delay.insert(0, "0")
            v_delay_unit.set("hours"); v_delay_unread.set(True)
            v_enabled.set(True)
            v_notify.set("default")
            v_run.set("auto")
            # A new rule starts at the top of the form with the cursor already
            # in the name box — nothing to scroll to, nothing to click first
            # (Issu 2026-08-08).
            try:
                right_canvas.yview_moveto(0.0)
            except Exception:
                pass
            e_name.focus_set()
            e_name.icursor("end")

        def _save(offer_run=True):
            """Save the rule. `offer_run=False` is the Update button: it saves
            and stops there.

            Renaming a rule, or folding two rules into one, changes nothing
            about which mail matches — being asked "shall I run the filters
            now?" every single time is pure noise (Issu 2026-08-03)."""
            # Gather the condition rows, MUST section first, each carrying the
            # section it belongs to.
            conds = _gather_conditions()
            # "…everything from the whole domain": widen every From condition to
            # the bare domain so the rule catches ANYONE at that domain, not just
            # the exact address (Issu). Transparent — the rows update to show it.
            if v_spam_domain.get():
                changed = False
                for c in conds:
                    v = c.get("value", "")
                    if c.get("field") == "from" and "@" in v:
                        c["value"] = v.split("@")[-1].strip()
                        changed = True
                if changed:
                    _set_conditions(conds)
            mode = "every" if v_every.get() else "groups"
            if mode != "every" and not conds and not v_attach.get():
                messagebox.showwarning(
                    "Filter",
                    "This rule has no conditions, so it would match nothing.\n\n"
                    "Add a condition, tick 'Only messages WITH attachments', or "
                    "tick “3 · All messages”.", parent=top)
                return
            # An either/or section on its own is fine (it is a plain OR), but a
            # SINGLE row in it is just a MUST row wearing the wrong hat — say so
            # once rather than let the form quietly mean something else.
            if (len([c for c in conds if c.get("group") == "any"]) == 1
                    and any(c.get("group") == "all" for c in conds)):
                if not messagebox.askyesno(
                        "One row in the either/or section",
                        "The “at least ONE of these” section has a single row, "
                        "so it can only be that one — the same as putting it in "
                        "the MUST section.\n\nSave it like this anyway?\n\n"
                        "(Add a second either/or row with + to get a real "
                        "“this OR that”.)", parent=top, default="yes"):
                    return
            try:
                snooze_min = max(0, int(e_snooze.get().strip() or "0"))
            except ValueError:
                messagebox.showwarning("Filter",
                                       "Snooze must be a number of minutes.",
                                       parent=top)
                return
            colour = e_colour.get().strip()
            if colour and not _re.match(r'^#[0-9a-fA-F]{6}$', colour):
                messagebox.showwarning("Filter",
                                       "Row colour must look like #3a2b55.",
                                       parent=top)
                return
            i = _idx()
            rec = dict(_FILTER_DEFAULTS)
            rec.update({
                "id": store["filters"][i]["id"] if i >= 0 else _new_id(),
                "name": e_name.get().strip() or "(unnamed)",
                "enabled": bool(v_enabled.get()),
                "conditions": conds, "match_mode": mode,
                # Legacy mirror fields kept empty — the engine reads conditions.
                "match_from": "", "match_to": "", "match_subject": "",
                "match_body": "", "match_folder": "",
                "run_on_fetch": (v_run.get() == "auto"),
                "run_on_archive": bool(v_run_archive.get()),
                "run_on_sent": bool(v_run_sent.get()),
                "run_folders": e_folders.get().strip(),
                "match_account": ("" if v_match_acct.get() == _ALL_ACCTS
                                 else v_match_acct.get()),
                "has_attachment": bool(v_attach.get()),
                "action_color": colour,
                "action_read": bool(v_read.get()),
                "action_unread": bool(v_unread.get()),
                "action_hide": bool(v_hide.get()),
                "action_star": bool(v_star.get()),
                "action_snooze_min": snooze_min,
                "action_notify": v_notify.get(),
                "action_move": e_move.get().strip(),
                "action_move_account": ("" if v_move_acct.get() == _SAME
                                        else v_move_acct.get()),
                "action_protect_dest": bool(v_protect.get()),
                "action_tag": _ftag_id_by_label.get(v_ftag.get(), ""),
                "action_spam": bool(v_spam.get()),
                "action_spam_domain": bool(v_spam_domain.get()),
                "action_unsub": v_unsub.get(),
                "action_trash": bool(v_trash.get()),
                # Coupled to the local read/star (Issu: one action, both places).
                "action_seen_server": bool(v_read.get()),
                "action_flag_server": bool(v_star.get()),
                "action_rescue_trash": bool(v_rescue.get()),
                "delay_min": _delay_to_minutes(e_delay.get(),
                                               v_delay_unit.get()),
                "delay_keep_unread": bool(v_delay_unread.get()),
            })
            # A rule that MATCHES mail but DOES nothing is the #1 filter
            # confusion (Issu 2026-08-02: "3 regler, ingen flyttar mail"). In
            # this program, matching and the action are separate — unlike
            # Thunderbird where you always pick a destination. So if no action
            # is set, say so and point at "Move to folder".
            has_action = (
                any(rec.get(k) for k in (
                    "action_move", "action_trash", "action_hide", "action_spam",
                    "action_read", "action_unread", "action_star", "action_tag",
                    "action_seen_server", "action_flag_server",
                    "action_rescue_trash"))
                or bool(rec.get("action_unsub"))
                or bool((rec.get("action_color") or "").strip())
                or int(rec.get("action_snooze_min") or 0) > 0
                or rec.get("action_notify") in ("always", "never"))
            if not has_action:
                if not messagebox.askyesno(
                        "This rule does nothing yet",
                        "The rule decides WHICH mail it matches, but you have "
                        "not told it to DO anything — so matching mail will not "
                        "move, get coloured, tagged, hidden or trashed.\n\n"
                        "To move mail to a folder (like Thunderbird), fill in "
                        "“Move to folder:” lower down — and Server changes must "
                        "be ON.\n\nSave this do-nothing rule anyway?",
                        parent=top, default="no"):
                    return
            # A rule that touches Gmail needs Server changes on. Offer to turn
            # it on right here rather than have the rule silently do nothing.
            if (_filter_has_server_action(rec)
                    and not self.cfg.get("allow_server_changes", False)):
                if messagebox.askyesno(
                        "Server changes are off",
                        "This rule acts on Gmail itself (move / trash / mark "
                        "read / star), but “Server changes” is currently OFF, "
                        "so those parts would do nothing.\n\nTurn Server "
                        "changes ON now?", parent=top, default="yes"):
                    self.cfg["allow_server_changes"] = True
                    _save_settings(self.cfg)
                    log.info("allow_server_changes enabled from the filter editor")
            # Same rule already exists, in substance (Issu 2026-08-06). Ask
            # before creating a second one that quietly fires alongside it.
            others = [f for k, f in enumerate(store.get("filters", []))
                     if k != i]
            overlaps = _rule_overlap_warnings(rec, others)
            if overlaps:
                if not messagebox.askyesno(
                        "This looks like an existing rule",
                        "Saving this rule may cause duplicate actions:\n\n"
                        + "\n\n".join(f"• {w}" for w in overlaps)
                        + "\n\nSave it anyway?", parent=top, default="no"):
                    return
            if i >= 0:
                store["filters"][i] = rec
            else:
                store.setdefault("filters", []).append(rec)
            _save_filters(store)
            _refresh()
            # Protect destination folder (Issu 2026-08-15): applied the
            # moment the rule is saved, not only after it first fires, so a
            # freshly made rule's destination is safe right away. A rule
            # scoped to one account (match_account) or forced to one account
            # (action_move_account, i.e. a cross-account rule) only needs
            # that one protected; an ordinary same-account rule can land on
            # any account, so every account's copy of that folder is
            # protected — that IS where it can land.
            #
            # protected_folders is keyed on the RAW modified-UTF-7 mailbox
            # name (same as msg["_folder"] — see _imap_utf7_encode), but the
            # "Move to folder:" box holds the DECODED path a person typed
            # ("Temporär/…"). Re-encoded per path segment here so the key
            # actually matches what a filed message's _folder will read —
            # a plain string transform, no live IMAP connection needed, so
            # it's exactly as safe to do at save time as _resolve_mailbox's
            # own encoding step is at move time.
            if rec.get("action_protect_dest") and rec.get("action_move"):
                raw_dest = "/".join(_imap_utf7_encode(p) for p in
                                    rec["action_move"].split("/"))
                macct = rec.get("action_move_account") or ""
                targets = ([macct] if macct
                          else [rec["match_account"]] if rec.get("match_account")
                          else _real_emails)
                if any(self._ensure_protected(t, raw_dest) for t in targets):
                    try:
                        self._populate_sidebar(self.sidebar_inner)
                    except Exception:
                        pass
            # Two promises that cannot both be kept: this rule says "keep it
            # unread", the destination says "mail here reads itself". The rule
            # wins at runtime (see _apply_auto_read), but silently winning is
            # how a setting becomes a mystery — so say it out loud once, here,
            # and offer to settle it properly.
            if (_filter_holds_unread(rec) and (rec.get("action_move") or "").strip()):
                dest  = rec["action_move"].strip()
                macct = (rec.get("action_move_account") or "").strip()
                clash = [t for t in ([macct] if macct else _real_emails)
                         if self._is_auto_read(t, dest)]
                if clash:
                    if messagebox.askyesno(
                            "That folder reads its own mail",
                            f"“{dest}” is marked “mail that lands here reads "
                            f"itself”, but this rule promises to keep what it "
                            f"files UNREAD.\n\nThe rule wins — mail it moves "
                            f"there stays unread — but anything arriving in "
                            f"that folder by any other route still reads "
                            f"itself.\n\nTake “{dest}” off the auto-read list, "
                            f"so the folder behaves the way this rule expects?",
                            parent=top, default="yes"):
                        keys = [k for k in (self.cfg.get("auto_read_folders", []) or [])
                                if "\t" in k and not (
                                    k.split("\t", 1)[0] in clash
                                    and _folder_norm(k.split("\t", 1)[1])
                                    == _folder_norm(dest))]
                        self.cfg["auto_read_folders"] = keys
                        _save_settings(self.cfg)
                        log.info("Auto-read cleared on %s for %s (a waiting "
                                 "rule keeps its mail unread)", dest, clash)
            # Keep the rule you just saved SELECTED, so Update can be pressed
            # again and again while you tune a name (it used to fall back to
            # "new rule" and the next Update would add a duplicate).
            try:
                j = next(k for k, f in enumerate(store["filters"])
                         if f.get("id") == rec.get("id"))
                lb.selection_clear(0, "end")
                lb.selection_set(j)
                lb.see(j)
            except StopIteration:
                pass
            self._flash("Filter updated" if not offer_run else "Filter saved")
            # Apply it to what is loaded NOW, so a "move to folder" (or hide /
            # spam / trash) rule acts on the mail you can already see — not only
            # future mail (Issu: "de reagerar inte, flyttas inte"). A rule only
            # runs on FETCH or when you run it, so a freshly-made rule otherwise
            # does nothing visible to mail already in the list.
            acts = any(rec.get(k) for k in (
                "action_move", "action_trash", "action_hide", "action_spam",
                "action_read", "action_star", "action_tag", "action_unread",
                "action_rescue_trash")) \
                or bool((rec.get("action_color") or "").strip()) \
                or bool(rec.get("action_unsub"))
            if acts and offer_run and messagebox.askyesno(
                    "Apply now?",
                    "Run your filters over the messages loaded in this folder "
                    "now, so this rule acts on mail you can already see?\n\n"
                    "(Otherwise it runs only on new mail from now on. To sweep "
                    "YEARS of old mail from a sender, use “🧹 Whole mailbox…”.)",
                    parent=top, default="yes"):
                self._run_filters_now()

        def _delete():
            i = _idx()
            if i < 0:
                return
            if messagebox.askyesno(
                    "Delete filter",
                    f"Delete “{store['filters'][i].get('name','')}”?",
                    parent=top):
                del store["filters"][i]
                _save_filters(store)
                _refresh(); _new()

        # ── "These rules could be one rule" (Issu 2026-08-03) ────────────────
        def _merge_dialog():
            groups   = _merge_groups(store.get("filters", []))
            clashes  = _merge_shared_senders(store.get("filters", []))
            win = self._dialog_shell("Rules that could be merged", 780, 560)
            tk.Label(win,
                     text="Rules set to “any of the following” (2) can be "
                          "merged with each other: two of those with the same "
                          "actions become ONE rule holding both lists of "
                          "conditions, and it means exactly what the pair "
                          "meant. A rule with just ONE condition counts here "
                          "too — “all of [x]” and “any of [x]” are the same "
                          "thing when there is only one “x” (e.g. six "
                          "separate single-sender “→ Trash” rules become one "
                          "rule matching any of the six). Rules set to "
                          "“all of the following” (1) with TWO OR MORE "
                          "conditions are never offered — ANDing them "
                          "together would make a THIRD, stricter rule that "
                          "matches less than either of them did.",
                     bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                     wraplength=740, justify="left",
                     pady=4).pack(fill="x", padx=12)

            wrap = tk.Frame(win, bg=C_BG2)
            wrap.pack(fill="both", expand=True, padx=12, pady=6)
            msb = tk.Scrollbar(wrap, bg=C_BG3, troughcolor=C_BG1)
            msb.pack(side="right", fill="y")
            mlb = tk.Listbox(wrap, bg=C_BG2, fg=C_FG, selectbackground=C_MSG_SEL,
                             selectforeground=C_FG_UNRD, highlightthickness=0,
                             relief="flat", activestyle="none",
                             font=("Consolas", 9), exportselection=False,
                             yscrollcommand=msb.set)
            msb.configure(command=mlb.yview)
            mlb.pack(side="left", fill="both", expand=True)

            rows = []          # listbox index -> group (or None for a heading)
            if not groups:
                mlb.insert("end", "  Nothing to merge — no two “any” rules "
                                  "share the same actions.")
                rows.append(None)
            for g in groups:
                names = ", ".join((r.get("name") or "(unnamed)")
                                  for r in g["rules"])
                n_cond = sum(len([c for c in (r.get("conditions") or [])
                                  if (c.get("value", "") or "").strip()])
                             for r in g["rules"])
                mark = "⚠ DUPLICATE" if g.get("dupe") else "⇒"
                mlb.insert("end", f" {mark} {len(g['rules'])} rules → 1 "
                                  f"({n_cond} conditions):  {names}")
                rows.append(g)
                mlb.insert("end", f"       {g['why']}")
                rows.append(None)
            if clashes:
                mlb.insert("end", "")
                rows.append(None)
                mlb.insert("end", "  ⚠ The same sender appears in more than one "
                                  "rule — they fire in list order:")
                rows.append(None)
                for sender, names in clashes[:20]:
                    mlb.insert("end", f"       {sender}  →  "
                                      + ", ".join(names))
                    rows.append(None)

            def _do_merge():
                sel = mlb.curselection()
                g = rows[sel[0]] if sel and sel[0] < len(rows) else None
                if not g:
                    messagebox.showinfo(
                        "Merge rules",
                        "Pick one of the “⇒ N rules → 1” or “⚠ DUPLICATE” "
                        "lines.", parent=win)
                    return
                merged = _merge_rules(g["rules"])
                keep_id = merged.get("id")
                drop = {id(r) for r in g["rules"][1:]}
                if not messagebox.askyesno(
                        "Merge rules",
                        f"Merge {len(g['rules'])} rules into "
                        f"“{merged.get('name', '')}” with "
                        f"{len(merged['conditions'])} condition(s)?\n\n"
                        f"The other {len(g['rules']) - 1} rule(s) are deleted. "
                        f"Their conditions are kept — nothing stops matching.",
                        parent=win, default="yes"):
                    return
                out = []
                for f in store.get("filters", []):
                    if id(f) in drop:
                        continue
                    out.append(merged if f.get("id") == keep_id else f)
                store["filters"] = out
                _save_filters(store)
                log.info("Merged %d rules into '%s' (%d conditions)",
                         len(g["rules"]), merged.get("name", ""),
                         len(merged["conditions"]))
                _refresh()
                win.destroy()
                self._flash("Rules merged")

            br = tk.Frame(win, bg=C_BG3)
            br.pack(fill="x", padx=12, pady=(0, 10))
            for text, colour, cmd in (
                    ("🔀 Merge the selected group", C_BTN_NEW, _do_merge),
                    ("Close", C_BTN_STD, win.destroy)):
                tk.Button(br, text=text, bg=colour, fg=C_BTN_FG,
                          font=("Segoe UI", 9), relief="flat", cursor="hand2",
                          padx=12, pady=4, command=cmd).pack(side="left", padx=4)
            mlb.bind("<Double-Button-1>", lambda e: _do_merge())

        def _reorder(where):
            flts = store.get("filters", [])
            i = _idx()
            if i < 0 or not flts:
                return
            if where == "up":
                j = max(0, i - 1)
            elif where == "down":
                j = min(len(flts) - 1, i + 1)
            elif where == "top":
                j = 0
            else:
                j = len(flts) - 1
            if j == i:
                return
            flts.insert(j, flts.pop(i))
            _save_filters(store)
            _refresh()
            lb.selection_clear(0, "end")
            lb.selection_set(j)
            lb.see(j)

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(fill="x", padx=12, pady=(0, 10))
        for text, colour, cmd in (
                ("Save", C_BTN_NEW, _save),
                ("Update", "#3a7d5a", lambda: _save(offer_run=False)),
                ("New", C_BTN_STD, _new),
                ("Delete", C_BTN_DEL, _delete),
                ("▶ Run now (loaded mail)", C_BTN_NEW,
                 lambda: (_save_filters(store), self._run_filters_now())),
                ("🧹 Whole mailbox…", "#8a5a2a",
                 lambda: (_save_filters(store), top.destroy(),
                          self._sweep_dialog())),
                ("🧬 Find duplicates…", "#8a5a2a",
                 lambda: (_save_filters(store), top.destroy(),
                          self._find_duplicates_dialog())),
                ("🔀 Merge similar…", "#4a5a8a", lambda: _merge_dialog()),
                ("🔍 Why didn't it fire?", "#5a4a8a",
                 self._filter_diag_dialog),
                ("🩺 Rule health…", C_BTN_NEW, self._rule_health_dialog),
                ("Filter log…", C_BTN_STD, self._filter_log_dialog),
                ("Close", C_BTN_STD, top.destroy)):
            b = tk.Button(btns, text=text, bg=colour, fg=C_BTN_FG,
                          font=("Segoe UI", 9), relief="flat", cursor="hand2",
                          padx=12, pady=4, command=cmd)
            b.pack(side="left", padx=4)
            if text == "Update":
                add_tooltip(b, "Save the changes and stop there — no “shall I "
                               "run the filters now?”. This is the one for "
                               "renaming a rule or tidying its conditions, "
                               "where nothing about WHICH mail matches has "
                               "changed.")
            if text == "Save":
                add_tooltip(b, "Save, then offer to run the filters over the "
                               "mail already loaded — for a rule you have just "
                               "made, or whose conditions you changed.")
            if text.startswith("🔀"):
                add_tooltip(b, "Finds rules that could become ONE rule: same "
                               "match mode, same actions, same triggers. Rules "
                               "matching “all of” are never merged — ANDing two "
                               "rules' conditions would change what they mean.")
            if text.startswith("🔍"):
                add_tooltip(b, "The last filter run explained: which rules ran, "
                               "which matched in full, and which came close — "
                               "and on exactly which condition they stopped.")
            if text.startswith("▶"):
                add_tooltip(b, "Runs every enabled rule over the mail currently "
                               "loaded in this folder (about forty per folder) "
                               "— right now, without waiting for the next "
                               "check.")
            if text.startswith("🧹"):
                add_tooltip(b, "Goes further: asks Gmail itself for EVERYTHING "
                               "one rule matches — years of it, not just what "
                               "is loaded — and offers to move the lot to the "
                               "Trash. Finding is read-only; the move asks "
                               "first.")
            if text.startswith("🧬"):
                add_tooltip(b, "Groups every message in one folder (and, if "
                               "asked, everything nested under it) by "
                               "Message-ID, so you can actually SEE if a "
                               "folder has piled-up duplicate copies — e.g. "
                               "from the cross-account rescue loop before it "
                               "was fixed. Read-only until you press Trash.")

        _refresh()
        # Prefill a NEW rule from a message you right-clicked: the sender and
        # this subject become condition rows (editable / removable), and the
        # account it arrived at is added too (Issu's request).
        if prefill_msg is not None:
            _new()
            sender = (parseaddr(prefill_msg.get("from", ""))[1]
                      or prefill_msg.get("from", "")).strip()
            subj = (prefill_msg.get("subject", "") or "").strip()
            # The From + Subject suggestion goes into the ONE section the Match
            # number names — not into all of them (Issu 2026-08-03: "så att det
            # inte hamnar i alla tre sektioner"). With the default 1 that is
            # the MUST section, which is where his own example starts: keep
            # From, drop the Subject with −, then build the either/or side.
            g = _default_group()
            g = "all" if g == "every" else g
            pre = []
            if sender:
                pre.append({"field": "from", "op": "contains",
                            "value": sender, "group": g})
            if subj:
                pre.append({"field": "subject", "op": "contains",
                            "value": subj, "group": g})
            _set_conditions(pre or None, default_group=g)
            e_name.delete(0, "end")
            # The name is just the ADDRESS now — "Rule for " ate the first nine
            # characters of every name in a 24-column list, which is exactly
            # the part of an address you need to tell two rules apart
            # (Issu 2026-08-03).
            e_name.insert(0, sender or "New rule")
        elif prefill_from:
            _new()
            g = _default_group()
            g = "all" if g == "every" else g
            _set_conditions([{"field": "from", "op": "contains",
                              "value": prefill_from, "group": g}],
                            default_group=g)
            e_name.insert(0, prefill_from)
        else:
            _new()          # start with one empty condition row

    # ── Duplicate mail finder (Issu 2026-08-06) ─────────────────────────────
    def _dup_fetch_full(self, m, callback):
        """Background full-body fetch of ONE duplicate candidate, so Open/
        Compare shows the real thing rather than the header-only stub the
        scan collected. `callback(built_or_None)` runs on the GUI thread."""
        account = m.get("account_email")
        pwd = self._secret_for(account)
        if not pwd:
            self.root.after(0, lambda: callback(None))
            return
        def worker():
            try:
                built = _fetch_single_full_body(
                    account, pwd, m.get("_folder"), m.get("uid"))
            except Exception as e:
                log.warning("Duplicate viewer: full fetch failed for %s/%s "
                           "uid %s: %s", account, m.get("_folder"),
                           m.get("uid"), e)
                built = None
            try:
                self.root.after(0, lambda: callback(built))
            except Exception:
                pass   # window closed mid-fetch
        threading.Thread(target=worker, daemon=True).start()

    def _dup_render_text(self, widget, m):
        widget.configure(state="normal")
        widget.delete("1.0", "end")
        header = (f"Account:     {m.get('account_email','')}\n"
                 f"Folder:      {m.get('_folder','')}\n"
                 f"From:        {m.get('from','')}\n"
                 f"Subject:     {m.get('subject','')}\n"
                 f"Date:        {m.get('date','')}\n"
                 f"Message-ID:  {m.get('_message_id','') or '(none)'}\n"
                 f"Size:        {m.get('_size', 0)} bytes\n"
                 + "─" * 50 + "\n\n")
        widget.insert("end", header + (m.get("body") or "(no text body — "
                                       "still loading, or this message has "
                                       "none)"))
        widget.configure(state="disabled")

    def _dup_open_message(self, m):
        top = self._dialog_shell(
            f"Message — {m.get('account_email','')} / {m.get('_folder','')}",
            720, 560)
        txt = tk.Text(top, bg=C_BG2, fg=C_FG, wrap="word", relief="flat",
                      font=("Segoe UI", 9), padx=8, pady=8)
        txt.pack(fill="both", expand=True, padx=12, pady=(0, 8))
        txt.insert("end", "Loading…")
        txt.configure(state="disabled")

        def done(built):
            if top.winfo_exists():
                self._dup_render_text(txt, built or m)
        self._dup_fetch_full(m, done)
        tk.Button(top, text="Close", bg=C_BTN_STD, fg=C_BTN_FG,
                 font=("Segoe UI", 9), relief="flat", cursor="hand2",
                 padx=12, pady=4, command=top.destroy).pack(pady=(0, 10))

    def _dup_compare_messages(self, members):
        shown = members[:3]     # three side by side is already a lot to read
        top = self._dialog_shell(
            f"Compare {len(shown)} messages", min(1180, 380 * len(shown) + 60),
            600)
        row = tk.Frame(top, bg=C_BG3)
        row.pack(fill="both", expand=True, padx=12, pady=(0, 8))
        for m in shown:
            col = tk.Frame(row, bg=C_BG3)
            col.pack(side="left", fill="both", expand=True, padx=4)
            tk.Label(col, text=f"{m.get('account_email','')}\n"
                               f"{m.get('_folder','')}",
                    bg=C_BG3, fg=C_ACCENT, font=("Segoe UI", 9, "bold"),
                    justify="left", anchor="w").pack(fill="x")
            txt = tk.Text(col, bg=C_BG2, fg=C_FG, wrap="word", relief="flat",
                         font=("Segoe UI", 9), padx=6, pady=6, width=40)
            txt.pack(fill="both", expand=True, pady=(4, 0))
            txt.insert("end", "Loading…")
            txt.configure(state="disabled")
            def done(built, txt=txt, m=m):
                if top.winfo_exists():
                    self._dup_render_text(txt, built or m)
            self._dup_fetch_full(m, done)
        tk.Button(top, text="Close", bg=C_BTN_STD, fg=C_BTN_FG,
                 font=("Segoe UI", 9), relief="flat", cursor="hand2",
                 padx=12, pady=4, command=top.destroy).pack(pady=(0, 10))

    def _dup_finder_dialog(self):
        """“Idiotsäker dublettkoll” (Issu 2026-08-06): scans chosen accounts'
        Inbox / Trash / Spam / and every folder any filter rule moves mail
        into, for messages that look like copies of one another — grouped,
        timestamped, with a confidence score and an Open/Compare path, since
        the copies themselves often have no downloaded body to tell them
        apart by eye. Read-only: it only ever SELECTs and FETCHes headers
        until you explicitly ask it to trash a redundant copy."""
        accounts = [a["email"] for a in self._accounts if not a.get("virtual")]
        if not accounts:
            messagebox.showinfo("Find duplicate mail",
                                "No accounts are configured yet.",
                                parent=self.root)
            return
        win = self._dialog_shell("Find duplicate mail", 900, 640)

        tk.Label(win, text="Scans headers only (Message-ID, sender, subject, "
                           "date, size) — nothing is changed until you "
                           "explicitly ask to trash a copy below.",
                bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                wraplength=860, justify="left").pack(fill="x", padx=12,
                                                     pady=(2, 0))

        top_row = tk.Frame(win, bg=C_BG3)
        top_row.pack(fill="x", padx=12, pady=(6, 0))
        tk.Label(top_row, text="Accounts:", bg=C_BG3, fg=C_FG_DIM,
                anchor="n", font=("Segoe UI", 9)).pack(side="left")
        acc_lb = tk.Listbox(top_row, bg=C_BG2, fg=C_FG, selectmode="multiple",
                            height=min(4, len(accounts)), exportselection=False,
                            selectbackground=C_MSG_SEL, selectforeground=C_FG_UNRD,
                            highlightthickness=0, relief="flat",
                            font=("Segoe UI", 9))
        for a in accounts:
            acc_lb.insert("end", a)
        acc_lb.selection_set(0, "end")
        acc_lb.pack(side="left", fill="x", expand=True, padx=(6, 0))

        status_var = tk.StringVar(value="Ready — pick accounts and scan.")
        tk.Label(win, textvariable=status_var, bg=C_BG3, fg=C_FG_DIM,
                font=("Segoe UI", 8), anchor="w").pack(fill="x", padx=12,
                                                       pady=(4, 0))

        wrap = tk.Frame(win, bg=C_BG2)
        wrap.pack(fill="both", expand=True, padx=12, pady=6)
        rsb = tk.Scrollbar(wrap, bg=C_BG3, troughcolor=C_BG1)
        rsb.pack(side="right", fill="y")
        rlb = tk.Listbox(wrap, bg=C_BG2, fg=C_FG, selectbackground=C_MSG_SEL,
                         selectforeground=C_FG_UNRD, highlightthickness=0,
                         relief="flat", activestyle="none",
                         font=("Consolas", 9), exportselection=False,
                         selectmode="extended", yscrollcommand=rsb.set)
        rsb.configure(command=rlb.yview)
        rlb.pack(side="left", fill="both", expand=True)

        state = {"groups": [], "rows": []}   # rows[i] -> (gi, mi) or None

        def _render():
            rlb.delete(0, "end")
            state["rows"] = []
            if not state["groups"]:
                rlb.insert("end", "  No likely duplicates found in the "
                                  "scanned folders.")
                state["rows"].append(None)
                return
            for gi, g in enumerate(state["groups"]):
                subj = next((m.get("subject") for m in g["members"]
                            if m.get("subject")), "(no subject)")
                rlb.insert("end", f" ⚠ {g['score']}%  ·  "
                                  f"{len(g['members'])} copies  ·  {g['why']}")
                state["rows"].append(None)
                rlb.insert("end", f"      “{subj[:100]}”")
                state["rows"].append(None)
                for mi, m in enumerate(g["members"]):
                    rlb.insert("end", f"        [{mi + 1}] "
                                      f"{m.get('account_email','')}"
                                      f"  ·  {m.get('_folder','')}"
                                      f"  ·  {m.get('date','')}"
                                      f"  ·  {m.get('_size', 0)} bytes")
                    state["rows"].append((gi, mi))
                rlb.insert("end", "")
                state["rows"].append(None)

        def _scan():
            sel = acc_lb.curselection()
            chosen = [accounts[i] for i in sel] or list(accounts)
            filters = _load_filters().get("filters", [])
            extra = {(f.get("action_move") or "").strip()
                    for f in filters if (f.get("action_move") or "").strip()}
            folders = ["Inbox", "Trash", "Spam"] + sorted(extra)
            status_var.set("Scanning…")

            def worker():
                collected = []
                for acct in chosen:
                    pwd = self._secret_for(acct)
                    if not pwd:
                        continue
                    def prog(text):
                        try:
                            self.root.after(0, lambda: status_var.set(text))
                        except Exception:
                            pass
                    try:
                        collected.extend(
                            _dup_scan_account(acct, pwd, folders, prog))
                    except Exception as e:
                        log.warning("Duplicate scan failed for %s: %s",
                                   acct, e)
                groups = _find_duplicate_groups(collected)

                def done():
                    state["groups"] = groups
                    _render()
                    status_var.set(
                        f"Scanned {len(chosen)} account(s) · "
                        f"{len(folders)} folder(s) each "
                        f"({', '.join(folders)}) — "
                        f"found {len(groups)} possible duplicate group(s).")
                try:
                    self.root.after(0, done)
                except Exception:
                    pass
            threading.Thread(target=worker, daemon=True).start()

        def _sel_members():
            picks = []
            for idx in rlb.curselection():
                row = state["rows"][idx] if idx < len(state["rows"]) else None
                if row:
                    gi, mi = row
                    picks.append(state["groups"][gi]["members"][mi])
            return picks

        def _open_one():
            picks = _sel_members()
            if not picks:
                messagebox.showinfo("Open", "Select one message first.",
                                    parent=win)
                return
            self._dup_open_message(picks[0])

        def _compare():
            picks = _sel_members()
            if len(picks) < 2:
                messagebox.showinfo(
                    "Compare", "Select two or more copies first "
                              "(click one, then Ctrl+click the others).",
                    parent=win)
                return
            self._dup_compare_messages(picks)

        def _trash_rest():
            idx = rlb.curselection()
            gi = next((state["rows"][i][0] for i in idx
                      if i < len(state["rows"]) and state["rows"][i]), None)
            if gi is None:
                messagebox.showinfo(
                    "Keep one, trash the rest",
                    "Click a row inside one duplicate group first.",
                    parent=win)
                return
            members = state["groups"][gi]["members"]
            picks = [m for m in _sel_members() if m in members]
            keep = picks[0] if picks else min(
                members, key=lambda m: m.get("_dt") or "9999")
            rest = [m for m in members if m is not keep]
            if not rest:
                return
            if not self.cfg.get("allow_server_changes", False):
                messagebox.showwarning(
                    "Server changes are off",
                    "Trashing a copy needs Tools → Server changes ON.",
                    parent=win)
                return
            lines = "\n".join(f"  • {m.get('account_email')} / "
                              f"{m.get('_folder')}  ({m.get('date','')})"
                              for m in rest)
            if not messagebox.askyesno(
                    "Keep one, trash the rest",
                    f"Keep the copy in {keep.get('account_email')} / "
                    f"{keep.get('_folder')} ({keep.get('date', '')}), and "
                    f"move these {len(rest)} other copie(s) to Trash?\n\n"
                    f"{lines}\n\n"
                    f"Nothing is permanently deleted — Trash only, exactly "
                    f"like every other delete in this program.",
                    parent=win, default="no"):
                return

            def worker():
                problems = []
                for m in rest:
                    pwd = self._secret_for(m.get("account_email"))
                    if not pwd:
                        problems.append(f"{m.get('account_email')}: no "
                                        f"saved password")
                        continue
                    prob = _imap_trash_message(
                        m.get("account_email"), pwd, m.get("_folder"),
                        m.get("uid"))
                    if prob:
                        problems.append(f"{m.get('account_email')}: {prob}")

                def done():
                    if problems:
                        messagebox.showwarning(
                            "Keep one, trash the rest",
                            "Some copies could not be trashed:\n\n"
                            + "\n".join(problems), parent=win)
                    else:
                        self._flash(f"{len(rest)} duplicate(s) trashed")
                    _scan()
                try:
                    self.root.after(0, done)
                except Exception:
                    pass
            threading.Thread(target=worker, daemon=True).start()

        br = tk.Frame(win, bg=C_BG3)
        br.pack(fill="x", padx=12, pady=(0, 10))
        for text, colour, cmd in (
                ("🔍 Scan for duplicates", C_BTN_NEW, _scan),
                ("👁 Open", C_BTN_STD, _open_one),
                ("⇄ Compare selected", C_BTN_STD, _compare),
                ("🗑 Keep one, trash the rest", C_BTN_DEL, _trash_rest),
                ("Close", C_BTN_STD, win.destroy)):
            tk.Button(br, text=text, bg=colour, fg=C_BTN_FG,
                     font=("Segoe UI", 9), relief="flat", cursor="hand2",
                     padx=10, pady=4, command=cmd).pack(side="left", padx=4)
        rlb.bind("<Double-Button-1>", lambda e: _open_one())

    # ── Outbox ────────────────────────────────────────────────────────────────
    def _outbox_dialog(self):
        top = self._dialog_shell("Outbox", 720, 440)
        tk.Label(top,
                 text="Messages waiting to be sent. F(re)email must be "
                      "running when their time comes.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 pady=4).pack(fill="x")

        frame = tk.Frame(top, bg=C_BG3)
        frame.pack(fill="both", expand=True, padx=12, pady=6)
        sb = tk.Scrollbar(frame, bg=C_BG3, troughcolor=C_BG1)
        sb.pack(side="right", fill="y")
        lb = tk.Listbox(frame, bg=C_BG2, fg=C_FG,
                        selectbackground=C_MSG_SEL, selectforeground=C_FG_UNRD,
                        highlightthickness=0, relief="flat", activestyle="none",
                        font=("Consolas", 9), yscrollcommand=sb.set)
        sb.configure(command=lb.yview)
        lb.pack(fill="both", expand=True)

        def _refresh():
            lb.delete(0, "end")
            items = self._outbox_store.get("messages", [])
            for m in items:
                dt   = _parse_iso(m.get("send_at", ""))
                when = dt.strftime("%Y-%m-%d %H:%M") if dt else "?"
                state = m.get("state", "queued")
                flag  = {"queued": "  ", "sending": "→ ", "failed": "! "}.get(state, "  ")
                lb.insert("end",
                          f"{flag}{when}  {(m.get('to') or '')[:26]:<26} "
                          f"{(m.get('subject') or '(no subject)')[:34]}"
                          + (f"   [{m.get('error','')[:30]}]"
                             if state == "failed" else ""))
            if not items:
                lb.insert("end", "   (the outbox is empty)")

        def _sel():
            cur = lb.curselection()
            items = self._outbox_store.get("messages", [])
            if not cur or cur[0] >= len(items):
                return None
            return items[cur[0]]

        def _send_now():
            m = _sel()
            if m is None:
                return
            m["send_at"] = _now_iso()
            m["state"]   = "queued"
            _save_outbox(self._outbox_store)
            self._outbox_tick()
            top.after(400, _refresh)

        def _reschedule():
            m = _sel()
            if m is None:
                return
            when = _ask_send_time(top, self.root)
            if when is None:
                return
            m["send_at"] = when.isoformat(timespec="seconds")
            m["state"]   = "queued"
            _save_outbox(self._outbox_store)
            _refresh()

        def _edit():
            m = _sel()
            if m is None:
                return
            self._cancel_outbox(m["id"], reopen=True)
            _refresh()

        def _cancel():
            m = _sel()
            if m is None:
                return
            if messagebox.askyesno(
                    "Remove from outbox",
                    f"Remove “{m.get('subject') or '(no subject)'}” from the "
                    f"outbox?\n\nIt will NOT be sent. Choose \"Edit\" instead "
                    f"if you want it back in a compose window.", parent=top):
                self._cancel_outbox(m["id"], reopen=False)
                _refresh()

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(fill="x", padx=12, pady=(0, 10))
        for text, colour, cmd in (("Send now", C_BTN_NEW, _send_now),
                                  ("Change time…", C_BTN_LATER, _reschedule),
                                  ("Edit…", C_BTN_STD, _edit),
                                  ("Remove", C_BTN_DEL, _cancel),
                                  ("Refresh", C_BTN_STD, _refresh),
                                  ("Close", C_BTN_STD, top.destroy)):
            tk.Button(btns, text=text, bg=colour, fg=C_BTN_FG,
                      font=("Segoe UI", 9), relief="flat", cursor="hand2",
                      padx=12, pady=4, command=cmd).pack(side="left", padx=3)
        _refresh()

    # ── Sending settings (undo send + drafts) ─────────────────────────────────
    def _sending_dialog(self):
        # Tall enough for every section without clipping the Save row — the
        # "Deleting" block below was added after the original 400 px.
        top = self._dialog_shell("Sending & deleting", 560, 780)

        v_on    = tk.BooleanVar(value=bool(self.cfg.get("undo_send_on", True)))
        v_count = tk.BooleanVar(value=bool(self.cfg.get("undo_countdown", False)))
        v_secs  = tk.StringVar(value=str(self.cfg.get("undo_send_seconds", 10)))
        v_keep  = tk.StringVar(value=str(self.cfg.get("draft_keep_min", 10)))
        v_del   = tk.StringVar(value=str(self.cfg.get("delete_undo_seconds", 60)))

        f = tk.Frame(top, bg=C_BG3)
        f.pack(fill="both", expand=True, padx=18, pady=10)

        tk.Checkbutton(f, text="Hold outgoing mail so I can undo it  "
                               "(recommended)",
                       variable=v_on, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 10, "bold"), highlightthickness=0,
                       anchor="w").pack(fill="x", pady=(4, 2))
        tk.Label(f, text="A “Cancel send” button appears in the message-list "
                         "bar, inside this window — not as a popup floating "
                         "over your other programs. One click and the message "
                         "comes back to you, untouched.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w",
                 justify="left", wraplength=460).pack(fill="x", padx=24)

        row = tk.Frame(f, bg=C_BG3)
        row.pack(fill="x", pady=(10, 2))
        tk.Label(row, text="Hold for:", bg=C_BG3, fg=C_FG_DIM, width=12,
                 anchor="e", font=("Segoe UI", 9)).pack(side="left")
        om = tk.OptionMenu(row, v_secs, "5", "10", "20", "30", "60", "120",
                           "300", "600")
        om.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                     activeforeground=C_FG, highlightthickness=0,
                     relief="flat", font=("Segoe UI", 9), width=6)
        om["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                             activeforeground=C_FG)
        om.pack(side="left")
        tk.Label(row, text="seconds   (5 s – 10 minutes)", bg=C_BG3,
                 fg=C_FG_DIM, font=("Segoe UI", 8)).pack(side="left", padx=6)

        tk.Checkbutton(f, text="Say “last chance” near the end of the window",
                       variable=v_count, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9), highlightthickness=0,
                       anchor="w").pack(fill="x", pady=(8, 0))
        tk.Label(f, text="The bar never counts down second by second — it "
                         "changes at most twice, and the last state turns red. "
                         "Nothing on this screen blinks.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w",
                 wraplength=460, justify="left").pack(fill="x", padx=24)

        tk.Frame(f, bg=C_SEP, height=1).pack(fill="x", pady=12)

        # ── Sending window (DEL 04r) ─────────────────────────────────────────
        v_win   = tk.BooleanVar(value=bool(self.cfg.get("send_window_on")))
        v_wfrom = tk.StringVar(value=self.cfg.get("send_window_from", "08:00"))
        v_wto   = tk.StringVar(value=self.cfg.get("send_window_to", "20:00"))
        v_wdays = tk.BooleanVar(value=bool(self.cfg.get("send_window_weekdays")))
        v_whol  = tk.BooleanVar(
            value=bool(self.cfg.get("send_window_skip_holidays")))

        tk.Checkbutton(f, text="Only send mail during certain hours",
                       variable=v_win, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 10, "bold"), highlightthickness=0,
                       anchor="w").pack(fill="x")
        tk.Label(f, text="Write at midnight, let it leave at a decent hour. "
                         "Anything you send outside the window waits for the "
                         "next allowed moment — File → Outbox shows when, and "
                         "can push it out immediately.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w",
                 justify="left", wraplength=460).pack(fill="x", padx=24)

        wrow = tk.Frame(f, bg=C_BG3)
        wrow.pack(fill="x", padx=24, pady=4)
        tk.Label(wrow, text="Between", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left")
        for var in (v_wfrom, v_wto):
            e = tk.Entry(wrow, textvariable=var, bg=C_BG2, fg=C_FG,
                         relief="flat", width=6, font=("Segoe UI", 10),
                         insertbackground=C_ACCENT,
                         insertofftime=0, insertontime=9999999)
            no_blink(e)
            e.pack(side="left", ipady=2, padx=4)
            if var is v_wfrom:
                tk.Label(wrow, text="and", bg=C_BG3, fg=C_FG_DIM,
                         font=("Segoe UI", 9)).pack(side="left")
        tk.Label(wrow, text="(24-hour clock)", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(side="left", padx=6)

        tk.Checkbutton(f, text="Weekdays only (no Saturday or Sunday)",
                       variable=v_wdays, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9), highlightthickness=0,
                       anchor="w").pack(fill="x", padx=24)
        tk.Checkbutton(f, text="Skip Swedish public holidays as well",
                       variable=v_whol, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9), highlightthickness=0,
                       anchor="w").pack(fill="x", padx=24)

        preview = tk.Label(f, text="", bg=C_BG2, fg=C_ACCENT,
                           font=("Consolas", 8), anchor="w", padx=8, pady=4)
        preview.pack(fill="x", padx=24, pady=(4, 0))

        def _preview(*_a):
            probe = {"send_window_on": bool(v_win.get()),
                     "send_window_from": v_wfrom.get(),
                     "send_window_to": v_wto.get(),
                     "send_window_weekdays": bool(v_wdays.get()),
                     "send_window_skip_holidays": bool(v_whol.get())}
            now = datetime.now()
            nxt = _send_window_next(now, probe)
            preview.configure(
                text=("A message sent right now would go out immediately."
                      if nxt == now else
                      f"A message sent right now would wait until "
                      f"{nxt.strftime('%A %d %B, %H:%M')}."))

        for v in (v_win, v_wfrom, v_wto, v_wdays, v_whol):
            v.trace_add("write", _preview)
        _preview()

        tk.Frame(f, bg=C_SEP, height=1).pack(fill="x", pady=12)

        row2 = tk.Frame(f, bg=C_BG3)
        row2.pack(fill="x")
        tk.Label(row2, text="Keep drafts:", bg=C_BG3, fg=C_FG_DIM, width=12,
                 anchor="e", font=("Segoe UI", 9)).pack(side="left")
        e_keep = tk.Entry(row2, textvariable=v_keep, bg=C_BG2, fg=C_FG,
                          relief="flat", width=6, font=("Segoe UI", 10),
                          insertbackground=C_ACCENT,
                          insertofftime=0, insertontime=9999999)
        no_blink(e_keep)
        e_keep.pack(side="left", ipady=3)
        tk.Label(row2, text="minutes after the message was sent", bg=C_BG3,
                 fg=C_FG_DIM, font=("Segoe UI", 8)).pack(side="left", padx=6)
        tk.Label(f, text="Unsent drafts are never deleted automatically — "
                         "only drafts whose message actually went out.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w",
                 wraplength=460, justify="left").pack(fill="x", padx=24,
                                                      pady=(2, 0))

        tk.Frame(f, bg=C_SEP, height=1).pack(fill="x", pady=12)

        # ── Deleting: the undo window (DEL 09, Issu 2026-08-01) ──────────────
        # Delete asks nothing and acts at once; the message simply waits this
        # long behind an Undo button before Gmail is told. 0 = commit instantly.
        tk.Label(f, text="Deleting", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 10, "bold"), anchor="w").pack(fill="x")
        tk.Label(f, text="Delete never asks “are you sure” — the message goes "
                         "from the list at once and an Undo button appears in "
                         "the corner. Gmail is only told when that window runs "
                         "out (or when you close the program).",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w",
                 justify="left", wraplength=470).pack(fill="x", padx=24)

        drow = tk.Frame(f, bg=C_BG3)
        drow.pack(fill="x", pady=(6, 2))
        tk.Label(drow, text="Undo for:", bg=C_BG3, fg=C_FG_DIM, width=12,
                 anchor="e", font=("Segoe UI", 9)).pack(side="left")
        om_del = tk.OptionMenu(drow, v_del, "0", "10", "30", "60", "120",
                               "300", "600")
        om_del.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                         activeforeground=C_FG, highlightthickness=0,
                         relief="flat", font=("Segoe UI", 9), width=6)
        om_del["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4,
                                 activeforeground=C_FG)
        om_del.pack(side="left")
        tk.Label(drow, text="seconds   (0 = delete straight away, no Undo)",
                 bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(side="left", padx=6)

        def _save(event=None):
            try:
                secs = max(0, min(600, int(v_secs.get())))
                keep = max(0, int(v_keep.get()))
                dsec = max(0, min(600, int(v_del.get())))
            except ValueError:
                messagebox.showwarning("Sending", "Use whole numbers.",
                                       parent=top)
                return
            self.cfg["undo_send_on"]      = bool(v_on.get())
            self.cfg["undo_send_seconds"] = secs
            self.cfg["undo_countdown"]    = bool(v_count.get())
            self.cfg["draft_keep_min"]    = keep
            self.cfg["delete_undo_seconds"] = dsec
            self.cfg["send_window_on"]            = bool(v_win.get())
            self.cfg["send_window_from"]          = v_wfrom.get().strip()
            self.cfg["send_window_to"]            = v_wto.get().strip()
            self.cfg["send_window_weekdays"]      = bool(v_wdays.get())
            self.cfg["send_window_skip_holidays"] = bool(v_whol.get())
            _save_settings(self.cfg)
            top.destroy()
            self._flash("Sending & deleting settings saved")

        top.bind("<Return>", _save)
        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(pady=10)
        tk.Button(btns, text="Save", bg=C_BTN_NEW, fg=C_BTN_FG,
                  font=("Segoe UI", 9, "bold"), relief="flat", cursor="hand2",
                  padx=18, pady=4, command=_save).pack(side="left", padx=5)
        tk.Button(btns, text="Cancel", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=18, pady=4, command=top.destroy).pack(side="left", padx=5)

    # ── Notification settings ─────────────────────────────────────────────────
    def _reading_dialog(self):
        """When does a message stop being 'new' (turn read)?"""
        top = self._dialog_shell("Reading", 560, 760)
        v_on   = tk.BooleanVar(value=bool(self.cfg.get("mark_read_enabled", True)))
        v_secs = tk.StringVar(value=str(self.cfg.get("mark_read_seconds", 1)))
        v_re   = tk.StringVar(value=str(self.cfg.get("reread_seconds", 5)))
        v_srv  = tk.BooleanVar(value=bool(self.cfg.get("mark_read_on_server", True)))
        v_html = tk.BooleanVar(value=bool(self.cfg.get("always_html_view", False)))
        v_pre  = tk.BooleanVar(value=bool(self.cfg.get("prefetch_bodies", True)))
        v_pren = tk.StringVar(value=str(self.cfg.get("prefetch_count", 12)))
        v_blank = tk.BooleanVar(
            value=bool(self.cfg.get("collapse_blank_lines", True)))
        v_links = tk.BooleanVar(
            value=bool(self.cfg.get("trim_keep_links", True)))

        f = tk.Frame(top, bg=C_BG3)
        f.pack(fill="both", expand=True, padx=18, pady=12)

        tk.Checkbutton(f, text="Mark a message read once I have kept it open a "
                               "moment",
                       variable=v_on, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 10, "bold"), highlightthickness=0,
                       anchor="w").pack(fill="x", pady=(2, 2))
        tk.Label(f, text="Scrolling past a message does not read it — you have "
                         "to stay on it. Set 0 to mark read the instant it "
                         "opens.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w",
                 justify="left", wraplength=450).pack(fill="x", padx=24)

        r1 = tk.Frame(f, bg=C_BG3)
        r1.pack(fill="x", pady=(10, 2))
        tk.Label(r1, text="Becomes read after:", bg=C_BG3, fg=C_FG_DIM, width=20,
                 anchor="e", font=("Segoe UI", 9)).pack(side="left")
        e1 = tk.Entry(r1, textvariable=v_secs, bg=C_BG2, fg=C_FG, relief="flat",
                      width=6, font=("Segoe UI", 10), insertbackground=C_ACCENT,
                      insertofftime=0, insertontime=9999999)
        no_blink(e1)
        e1.pack(side="left", ipady=3)
        tk.Label(r1, text="seconds  (your preference: 1)", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(side="left", padx=6)

        r2 = tk.Frame(f, bg=C_BG3)
        r2.pack(fill="x", pady=2)
        tk.Label(r2, text="After I mark it unread:", bg=C_BG3, fg=C_FG_DIM,
                 width=20, anchor="e", font=("Segoe UI", 9)).pack(side="left")
        e2 = tk.Entry(r2, textvariable=v_re, bg=C_BG2, fg=C_FG, relief="flat",
                      width=6, font=("Segoe UI", 10), insertbackground=C_ACCENT,
                      insertofftime=0, insertontime=9999999)
        no_blink(e2)
        e2.pack(side="left", ipady=3)
        tk.Label(r2, text="seconds to read again  (default 5)", bg=C_BG3,
                 fg=C_FG_DIM, font=("Segoe UI", 8)).pack(side="left", padx=6)
        tk.Label(f, text="So a message you deliberately flagged unread is not "
                         "re-read by a passing glance.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w",
                 justify="left", wraplength=450).pack(fill="x", padx=24)

        tk.Frame(f, bg=C_SEP, height=1).pack(fill="x", pady=12)

        tk.Checkbutton(f, text="Also mark read on Gmail (never marks unread "
                               "there)",
                       variable=v_srv, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9), highlightthickness=0,
                       anchor="w").pack(fill="x")
        tk.Label(f, text="Adds the \\Seen flag on the server so your phone / "
                         "Thunderbird / Rambox stop showing it as new. Freemail "
                         "only ever ADDS it, never removes it — 'mark unread' "
                         "here stays local. Needs Tools → Server changes on.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w",
                 justify="left", wraplength=450).pack(fill="x", padx=24)

        tk.Frame(f, bg=C_SEP, height=1).pack(fill="x", pady=12)

        # ── Formatted (HTML) view (Issu 2026-08-01) ─────────────────────────
        # The same switch as the tick-box in the reading pane, kept here too so
        # it can be found without a message open.
        tk.Checkbutton(f, text="Always open the formatted (HTML) view "
                               "automatically",
                       variable=v_html, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9), highlightthickness=0,
                       anchor="w").pack(fill="x")
        tk.Label(f, text="For mail that is really a web page. One window is "
                         "reused rather than a new one per message, and remote "
                         "images stay blocked until you allow them. The same "
                         "tick-box sits next to “View formatted (HTML)” in the "
                         "reading pane.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w",
                 justify="left", wraplength=450).pack(fill="x", padx=24)

        tk.Checkbutton(f, text="Show a run of blank lines as one blank line",
                       variable=v_blank, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9), highlightthickness=0,
                       anchor="w").pack(fill="x", pady=(8, 0))
        tk.Label(f, text="Mail built out of HTML tables arrives with hundreds "
                         "of empty lines in it — one Tradera message held 410. "
                         "This only changes what is drawn; the message itself "
                         "keeps every line, and so does any reply you write.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w",
                 justify="left", wraplength=450).pack(fill="x", padx=24)

        tk.Checkbutton(f, text="Never hide a line that carries a link",
                       variable=v_links, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9), highlightthickness=0,
                       anchor="w").pack(fill="x", pady=(8, 0))
        tk.Label(f, text="A hide rule may fold the words around an address, "
                         "never the address itself — unless the rule's own "
                         "patterns are about links (Tradera's is, so its "
                         "navigation links still go). This is what keeps "
                         "BoardGameGeek's “Link to the original message” on "
                         "screen while the footer around it folds away.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w",
                 justify="left", wraplength=450).pack(fill="x", padx=24)

        tk.Frame(f, bg=C_SEP, height=1).pack(fill="x", pady=12)

        # ── Read ahead (Issu 2026-08-08) ─────────────────────────────────────
        tk.Checkbutton(f, text="Fetch messages before I open them "
                               "(recommended)",
                       variable=v_pre, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 10, "bold"), highlightthickness=0,
                       anchor="w").pack(fill="x", pady=(2, 2))
        tk.Label(f, text="The message LIST arrives first (that is what makes "
                         "changing folder quick), and the messages themselves "
                         "then come down quietly behind it. Clicking one is "
                         "then a read from your own disk with nothing to wait "
                         "for. It uses its own connection, steps aside the "
                         "instant you click anything, and stops when you leave "
                         "the folder.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w",
                 justify="left", wraplength=470).pack(fill="x", padx=24)

        r3 = tk.Frame(f, bg=C_BG3)
        r3.pack(fill="x", pady=(8, 2))
        tk.Label(r3, text="Read ahead:", bg=C_BG3, fg=C_FG_DIM, width=20,
                 anchor="e", font=("Segoe UI", 9)).pack(side="left")
        e3 = tk.Entry(r3, textvariable=v_pren, bg=C_BG2, fg=C_FG, relief="flat",
                      width=6, font=("Segoe UI", 10), insertbackground=C_ACCENT,
                      insertofftime=0, insertontime=9999999)
        no_blink(e3)
        e3.pack(side="left", ipady=3)
        tk.Label(r3, text="of the newest messages  (default 12)", bg=C_BG3,
                 fg=C_FG_DIM, font=("Segoe UI", 8)).pack(side="left", padx=6)
        tk.Label(f, text="Raise it if you often open older mail; lower it (or "
                         "switch this off) on a metered or slow connection.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w",
                 justify="left", wraplength=470).pack(fill="x", padx=24)

        def _save(event=None):
            try:
                secs = max(0, int(v_secs.get()))
                rr   = max(0, int(v_re.get()))
                pren = max(0, min(200, int(v_pren.get())))
            except ValueError:
                messagebox.showwarning("Reading", "Use whole numbers.",
                                       parent=top)
                return
            self.cfg["mark_read_enabled"]   = bool(v_on.get())
            self.cfg["mark_read_seconds"]   = secs
            self.cfg["reread_seconds"]      = rr
            self.cfg["mark_read_on_server"] = bool(v_srv.get())
            self.cfg["always_html_view"]    = bool(v_html.get())
            self.cfg["collapse_blank_lines"] = bool(v_blank.get())
            self.cfg["trim_keep_links"]      = bool(v_links.get())
            self.cfg["prefetch_bodies"]     = bool(v_pre.get())
            self.cfg["prefetch_count"]      = pren
            # Keep the identical tick-box in the open reading pane in step, so
            # the two places can never disagree on screen.
            try:
                if getattr(self, "_always_html_var", None) is not None:
                    self._always_html_var.set(bool(v_html.get()))
            except Exception:
                pass
            _save_settings(self.cfg)
            top.destroy()
            self._flash("Reading settings saved")

        top.bind("<Return>", _save)
        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(pady=10)
        tk.Button(btns, text="Save", bg=C_BTN_NEW, fg=C_BTN_FG,
                  font=("Segoe UI", 9, "bold"), relief="flat", cursor="hand2",
                  padx=18, pady=4, command=_save).pack(side="left", padx=5)
        tk.Button(btns, text="Cancel", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=18, pady=4, command=top.destroy).pack(side="left", padx=5)

    def _search_exclude_dialog(self, parent=None):
        """Pick the folders — or whole accounts — that searching leaves alone.

        Issu 2026-08-17: "Search has three choices. It could have a fourth as
        well — All except…, where a setting lets you pick folders (or whole
        accounts) to keep out of the search. I am going to put
        0---Frakt & kvitto in there."

        What is ticked here is exactly what the "All except…" scope skips, and
        what the search WINDOW skips while its "Skip what I left out" box is
        on. NOTHING else reads this list: a folder left out of searching is
        still fetched, still filtered, still counted, still in the sidebar. It
        is a search setting, not a way of hiding a folder — that is what
        right-click → hide is for.

        The checkbox stores the RAW mailbox name, not the pretty one on screen,
        so renaming nothing and re-reading the folder list later still matches.
        Entries for accounts or folders this dialog cannot see (an account you
        removed, a "*" line typed into settings.json by hand) are carried
        through Save untouched rather than quietly dropped."""
        owner = parent if parent is not None else self.root
        top = tk.Toplevel(owner)
        top.title("Search: what to leave out")
        top.configure(bg=C_BG3)
        _center_over(top, owner, 660, 680)
        top.transient(owner)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())
        tk.Label(top, text="Search: what to leave out", bg=C_BG1, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold"), pady=8).pack(fill="x")

        tk.Label(top, text="Ticked = searching skips it. This is what the "
                           "“All except…” scope next to the search box means, "
                           "and what the search window skips while “Skip what "
                           "I left out” is on. Everything else — fetching, "
                           "filters, unread counts, the sidebar — is left "
                           "exactly as it was.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w",
                 justify="left", wraplength=610).pack(fill="x", padx=18,
                                                      pady=(10, 6))

        accounts = [a for a in self._accounts if not a.get("virtual")]
        if not accounts:
            tk.Label(top, text="No account is set up yet, so there is nothing "
                               "to leave out.",
                     bg=C_BG3, fg=C_FG, font=("Segoe UI", 10),
                     pady=20).pack(fill="x", padx=18)
            tk.Button(top, text="Close", bg=C_BTN_STD, fg=C_BTN_FG,
                      font=("Segoe UI", 9), relief="flat", cursor="hand2",
                      padx=18, pady=4, command=top.destroy).pack(pady=10)
            return

        # ── The scrolling list of accounts and their folders ─────────────────
        body = tk.Frame(top, bg=C_BG2)
        body.pack(fill="both", expand=True, padx=14)
        sb = tk.Scrollbar(body, orient="vertical", bg=C_BG3, troughcolor=C_BG1)
        sb.pack(side="right", fill="y")     # BEFORE the canvas, or it renders
                                            # one pixel wide (house rule)
        canvas = tk.Canvas(body, bg=C_BG2, highlightthickness=0,
                           yscrollcommand=sb.set)
        canvas.pack(fill="both", expand=True)
        sb.configure(command=canvas.yview)
        inner = tk.Frame(canvas, bg=C_BG2)
        cwin = canvas.create_window((0, 0), window=inner, anchor="nw")
        inner.bind("<Configure>",
                   lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
        canvas.bind("<Configure>",
                    lambda e: canvas.itemconfig(cwin, width=e.width))
        _bind_mousewheel(inner, canvas)

        ex_folders  = _search_excluded_folders(self.cfg)
        ex_accounts = _search_excluded_accounts(self.cfg)
        v_acct, v_fold, fold_boxes = {}, {}, {}

        for a in accounts:
            email = a["email"]
            sec = tk.Frame(inner, bg=C_BG2, padx=10, pady=8)
            sec.pack(fill="x")

            head = tk.Frame(sec, bg=C_BG2)
            head.pack(fill="x")
            tk.Label(head, text=f"✉  {email}", bg=C_BG2, fg=C_FG,
                     font=("Segoe UI", 10, "bold"),
                     anchor="w").pack(side="left")
            v_a = tk.BooleanVar(value=email.strip().lower() in ex_accounts)
            v_acct[email] = v_a
            cb_a = tk.Checkbutton(head, text="Skip this whole account",
                                  variable=v_a, bg=C_BG2, fg="#d08a6a",
                                  selectcolor=C_BG3, activebackground=C_BG2,
                                  activeforeground="#d08a6a",
                                  font=("Segoe UI", 9), highlightthickness=0,
                                  anchor="w")
            cb_a.pack(side="right")
            add_tooltip(cb_a, "Never search this account at all. The folder "
                              "ticks below go grey — they are still "
                              "remembered, they just have nothing to do while "
                              "the whole account is out.")

            grid = tk.Frame(sec, bg=C_BG2, padx=16)
            grid.pack(fill="x", pady=(4, 0))
            fold_boxes[email] = []

            def add_folder(parent_frame, folder_key, label, tip=None):
                v = tk.BooleanVar(
                    value=_search_folder_skipped(self.cfg, email, folder_key,
                                                 ex_folders))
                v_fold[(email, folder_key)] = v
                cb = tk.Checkbutton(parent_frame, text=label, variable=v,
                                    bg=C_BG2, fg=C_FG_DIM, selectcolor=C_BG3,
                                    activebackground=C_BG2,
                                    activeforeground=C_FG,
                                    font=("Segoe UI", 9), highlightthickness=0,
                                    anchor="w")
                cb.pack(fill="x", anchor="w")
                fold_boxes[email].append(cb)
                if tip:
                    add_tooltip(cb, tip)

            std_row = tk.Frame(grid, bg=C_BG2)
            std_row.pack(fill="x")
            std_cols = [tk.Frame(std_row, bg=C_BG2) for _ in range(3)]
            for i, col in enumerate(std_cols):
                col.pack(side="left", fill="x", expand=True)
            for i, folder in enumerate(_SEARCH_FOLDERS):
                add_folder(std_cols[i % 3], folder,
                           f"{_FOLDER_ICONS.get(folder, '📁')} {folder}")

            customs = (self._user_folders or {}).get(email, [])
            if customs:
                tk.Label(grid, text="Your own folders:", bg=C_BG2,
                         fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                         anchor="w").pack(fill="x", pady=(6, 1))
                for uf in customs:
                    mailbox = uf.get("mailbox")
                    if not mailbox:
                        continue
                    depth = int(uf.get("depth", 0) or 0)
                    add_folder(grid, mailbox,
                               "   " * depth + "📁 " +
                               (uf.get("full") or uf.get("display") or mailbox),
                               f"Raw mailbox name: {mailbox}")
            else:
                tk.Label(grid, text="Your own folders are not loaded yet — "
                                    "Accounts → Refresh folder list, then "
                                    "open this again.",
                         bg=C_BG2, fg=C_FG_DIM, font=("Segoe UI", 8),
                         anchor="w", justify="left",
                         wraplength=560).pack(fill="x", pady=(6, 0))

            def sync(email=email, v_a=v_a):
                state = "disabled" if v_a.get() else "normal"
                for cb in fold_boxes[email]:
                    try:
                        cb.configure(state=state)
                    except Exception:
                        pass
            cb_a.configure(command=sync)
            sync()

            tk.Frame(sec, bg=C_SEP, height=1).pack(fill="x", pady=(8, 0))

        # Anything in the saved list this dialog is not showing — an account
        # that has been removed, a "*" line — is kept, and said out loud so it
        # is never a silent surprise.
        shown_pairs = {(e.strip().lower(), f) for (e, f) in v_fold}
        carried = [k for k in (self.cfg.get("search_exclude_folders") or [])
                   if "\t" in str(k)
                   and (str(k).split("\t", 1)[0].strip().lower(),
                        str(k).split("\t", 1)[1]) not in shown_pairs]
        if carried:
            tk.Label(top,
                     text=f"{len(carried)} more entr"
                          f"{'ies are' if len(carried) != 1 else 'y is'} in the "
                          f"list from somewhere this window cannot show "
                          f"(a removed account, or a “*” line typed into "
                          f"settings.json). Saving keeps "
                          f"{'them' if len(carried) != 1 else 'it'}.",
                     bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w",
                     justify="left", wraplength=610).pack(fill="x", padx=18,
                                                          pady=(6, 0))

        def _clear():
            for v in v_acct.values():
                v.set(False)
            for v in v_fold.values():
                v.set(False)
            for email in fold_boxes:
                for cb in fold_boxes[email]:
                    try:
                        cb.configure(state="normal")
                    except Exception:
                        pass

        def _save(event=None):
            self.cfg["search_exclude_accounts"] = sorted(
                e for e, v in v_acct.items() if v.get())
            self.cfg["search_exclude_folders"] = sorted(
                list(carried) +
                [f"{e}\t{f}" for (e, f), v in v_fold.items() if v.get()])
            _save_settings(self.cfg)
            n_a = len(self.cfg["search_exclude_accounts"])
            n_f = len(self.cfg["search_exclude_folders"])
            top.destroy()
            if not n_a and not n_f:
                self._flash("Searching leaves nothing out")
            else:
                self._flash(f"Searching leaves out {n_f} folder(s)"
                            + (f" and {n_a} whole account(s)" if n_a else ""))

        top.bind("<Return>", _save)
        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(pady=10)
        tk.Button(btns, text="Save", bg=C_BTN_NEW, fg=C_BTN_FG,
                  font=("Segoe UI", 9, "bold"), relief="flat", cursor="hand2",
                  padx=18, pady=4, command=_save).pack(side="left", padx=5)
        b_clr = tk.Button(btns, text="Leave nothing out", bg=C_BTN_STD,
                          fg=C_BTN_FG, font=("Segoe UI", 9), relief="flat",
                          cursor="hand2", padx=12, pady=4, command=_clear)
        b_clr.pack(side="left", padx=5)
        add_tooltip(b_clr, "Untick everything. Nothing is saved until you "
                           "press Save.")
        tk.Button(btns, text="Cancel", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=18, pady=4, command=top.destroy).pack(side="left",
                                                             padx=5)

    def _notifications_dialog(self):
        top = self._dialog_shell("Notifications", 460, 330)
        v_on    = tk.BooleanVar(value=bool(self.cfg.get("notify_on", True)))
        v_sound = tk.BooleanVar(value=bool(self.cfg.get("notify_sound", False)))
        v_win   = tk.BooleanVar(value=bool(self.cfg.get("notify_windows", True)))
        v_flash = tk.BooleanVar(value=bool(self.cfg.get("notify_flash", True)))

        f = tk.Frame(top, bg=C_BG3)
        f.pack(fill="both", expand=True, padx=18, pady=12)
        tk.Checkbutton(f, text="Tell me when new mail arrives",
                       variable=v_on, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 10, "bold"), highlightthickness=0,
                       anchor="w").pack(fill="x")
        tk.Label(f, text="A small window in the bottom-right corner shows who "
                         "wrote and about what. Click it to open the message. "
                         "It only appears for BACKGROUND checks — pressing "
                         "Refresh yourself never pops anything up.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w",
                 justify="left", wraplength=400).pack(fill="x", padx=24,
                                                      pady=(2, 8))
        tk.Checkbutton(f, text="Use a real Windows notification (Action Center)",
                       variable=v_win, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9), highlightthickness=0,
                       anchor="w").pack(fill="x")
        tk.Label(f, text="When on, new mail shows a native Windows toast that "
                         "also lands in the Action Center. If that is not "
                         "available, the in-app window is used instead.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w",
                 justify="left", wraplength=400).pack(fill="x", padx=24,
                                                      pady=(2, 6))
        tk.Checkbutton(f, text="Also play a sound", variable=v_sound,
                       bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9), highlightthickness=0,
                       anchor="w").pack(fill="x")
        tk.Checkbutton(f, text="Flash the taskbar button (two gentle flashes)",
                       variable=v_flash, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9), highlightthickness=0,
                       anchor="w").pack(fill="x")
        tk.Label(f, text="Taskbar button only, never the title bar, and it "
                         "stops on its own — turn it off if you prefer no "
                         "flashing at all.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w",
                 justify="left", wraplength=400).pack(fill="x", padx=24,
                                                      pady=(0, 4))
        tk.Label(f, text="Individual senders can be forced to always or never "
                         "notify — see Tools → Mail filters.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 anchor="w", wraplength=400,
                 justify="left").pack(fill="x", padx=24, pady=(8, 0))

        def _save(event=None):
            self.cfg["notify_on"]      = bool(v_on.get())
            self.cfg["notify_sound"]   = bool(v_sound.get())
            self.cfg["notify_windows"] = bool(v_win.get())
            self.cfg["notify_flash"]   = bool(v_flash.get())
            _save_settings(self.cfg)
            top.destroy()
            self._flash("Notification settings saved")

        def _test():
            title = "📬  Test notification"
            line  = "This is what a new-mail notification looks like."
            if v_win.get() and self._windows_toast(title, line):
                return
            NotifyToast(self.root, title, [line])

        top.bind("<Return>", _save)
        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(pady=10)
        tk.Button(btns, text="Save", bg=C_BTN_NEW, fg=C_BTN_FG,
                  font=("Segoe UI", 9, "bold"), relief="flat", cursor="hand2",
                  padx=18, pady=4, command=_save).pack(side="left", padx=5)
        tk.Button(btns, text="Test", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=18, pady=4, command=_test).pack(side="left", padx=5)
        tk.Button(btns, text="Cancel", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=18, pady=4, command=top.destroy).pack(side="left", padx=5)

    # ── Backup ────────────────────────────────────────────────────────────────
    def _backup_dialog(self):
        top = self._dialog_shell("Backup", 560, 380)
        v_exit = tk.BooleanVar(value=bool(self.cfg.get("backup_on_exit", False)))
        v_keep = tk.StringVar(value=str(self.cfg.get("backup_keep", 10)))
        v_dir  = tk.StringVar(value=self.cfg.get("backup_dir")
                              or _default_backup_dir())

        f = tk.Frame(top, bg=C_BG3)
        f.pack(fill="both", expand=True, padx=16, pady=10)
        tk.Label(f, text="A backup is one .zip holding every account, rule, "
                         "signature, template, contact and unsent draft. App "
                         "passwords stay encrypted inside it and can only be "
                         "read back by this Windows user on this machine.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9), anchor="w",
                 justify="left", wraplength=500).pack(fill="x", pady=(0, 10))

        row = tk.Frame(f, bg=C_BG3)
        row.pack(fill="x", pady=3)
        tk.Label(row, text="Folder:", bg=C_BG3, fg=C_FG_DIM, width=10,
                 anchor="e", font=("Segoe UI", 9)).pack(side="left")
        e_dir = tk.Entry(row, textvariable=v_dir, bg=C_BG2, fg=C_FG,
                         relief="flat", font=("Segoe UI", 9),
                         insertbackground=C_ACCENT,
                         insertofftime=0, insertontime=9999999)
        no_blink(e_dir)
        e_dir.pack(side="left", fill="x", expand=True, ipady=3, padx=4)

        def _browse():
            from tkinter import filedialog
            d = filedialog.askdirectory(parent=top, title="Backup folder")
            if d:
                v_dir.set(d)

        tk.Button(row, text="…", bg=C_BTN_STD, fg=C_BTN_FG, relief="flat",
                  padx=8, command=_browse).pack(side="left")

        tk.Checkbutton(f, text="Write a backup automatically every time I "
                               "close the program",
                       variable=v_exit, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9), highlightthickness=0,
                       anchor="w").pack(fill="x", pady=(10, 0))
        row2 = tk.Frame(f, bg=C_BG3)
        row2.pack(fill="x", pady=3)
        tk.Label(row2, text="Keep:", bg=C_BG3, fg=C_FG_DIM, width=10,
                 anchor="e", font=("Segoe UI", 9)).pack(side="left")
        e_keep = tk.Entry(row2, textvariable=v_keep, bg=C_BG2, fg=C_FG,
                          relief="flat", width=6, font=("Segoe UI", 10),
                          insertbackground=C_ACCENT,
                          insertofftime=0, insertontime=9999999)
        no_blink(e_keep)
        e_keep.pack(side="left", ipady=3)
        tk.Label(row2, text="automatic backups", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(side="left", padx=6)

        def _save_settings_only():
            try:
                keep = max(1, int(v_keep.get()))
            except ValueError:
                messagebox.showwarning("Backup", "Keep must be a number.",
                                       parent=top)
                return False
            self.cfg["backup_on_exit"] = bool(v_exit.get())
            self.cfg["backup_keep"]    = keep
            self.cfg["backup_dir"]     = v_dir.get().strip()
            _save_settings(self.cfg)
            return True

        def _backup():
            if not _save_settings_only():
                return
            try:
                path = _backup_now(v_dir.get().strip())
                _prune_backups(os.path.dirname(path), int(v_keep.get()))
            except Exception as e:
                log.error("Backup failed: %s", e)
                messagebox.showerror("Backup", f"Backup failed:\n{e}",
                                     parent=top)
                return
            self._flash("Backup written!")
            messagebox.showinfo("Backup", f"Backup written to:\n\n{path}",
                                parent=top)

        def _restore():
            from tkinter import filedialog
            p = filedialog.askopenfilename(
                parent=top, title="Restore from backup",
                filetypes=[("Backup zip", "*.zip"), ("All files", "*.*")],
                initialdir=v_dir.get().strip() or _default_backup_dir())
            if not p:
                return
            if not messagebox.askyesno(
                    "Restore backup",
                    f"Replace the current settings, accounts and rules with "
                    f"the contents of:\n\n{os.path.basename(p)}\n\n"
                    f"Your current configuration is backed up first, and "
                    f"F(re)email must be restarted afterwards.\n\nContinue?",
                    parent=top, default="no"):
                return
            try:
                n = _restore_backup(p)
            except Exception as e:
                log.error("Restore failed: %s", e)
                messagebox.showerror("Restore", f"Restore failed:\n{e}",
                                     parent=top)
                return
            # The restored settings.json is on disk — but this still-running
            # program holds the OLD settings in memory and would write them
            # straight back over it when you close the window. Suppress that
            # one save; everything else (accounts, rules, calendar) is read
            # fresh at start-up anyway.
            self._settings_restored = True
            messagebox.showinfo(
                "Restore",
                f"{n} file(s) restored.\n\nPlease close and start F(re)email "
                f"again for the restored settings to take effect.", parent=top)

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(pady=10)
        for text, colour, cmd in (("Back up now", C_BTN_NEW, _backup),
                                  ("Restore…", C_BTN_LATER, _restore),
                                  ("Save settings", C_BTN_STD,
                                   lambda: _save_settings_only() and
                                   (top.destroy(), self._flash("Saved"))),
                                  ("Close", C_BTN_STD, top.destroy)):
            tk.Button(btns, text=text, bg=colour, fg=C_BTN_FG,
                      font=("Segoe UI", 9), relief="flat", cursor="hand2",
                      padx=14, pady=4, command=cmd).pack(side="left", padx=4)

    # ── Default mail client (Windows) ─────────────────────────────────────────
    def _default_client_dialog(self):
        top = self._dialog_shell("Default mail client", 560, 380)
        f = tk.Frame(top, bg=C_BG3)
        f.pack(fill="both", expand=True, padx=18, pady=12)

        tk.Label(f, text="Make F(re)email open mailto: links",
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 11, "bold"),
                 anchor="w").pack(fill="x")
        tk.Label(f,
                 text="Registering adds F(re)email to Windows' list of mail "
                      "programs. Everything is written under your own user "
                      "account (HKEY_CURRENT_USER) — nothing system-wide, and "
                      "\"Unregister\" removes it completely.\n\n"
                      "Windows 11 does not let a program make itself the "
                      "default, so the last step is yours: the Default apps "
                      "page opens right after, and you pick F(re)email there.\n\n"
                      "Once it is the default, clicking an e-mail address on a "
                      "web page opens a compose window here with the address, "
                      "subject and text already filled in.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9), anchor="w",
                 justify="left", wraplength=500).pack(fill="x", pady=(6, 10))

        tk.Label(f, text=f"Command that will be registered:\n{_launch_command()}",
                 bg=C_BG2, fg=C_FG_DIM, font=("Consolas", 8), anchor="w",
                 justify="left", wraplength=490, padx=8,
                 pady=6).pack(fill="x")

        def _register():
            try:
                msg = _register_mail_client()
            except Exception as e:
                log.error("Register as mail client failed: %s", e)
                messagebox.showerror("Default mail client",
                                     f"Could not register:\n{e}", parent=top)
                return
            messagebox.showinfo("Default mail client", msg, parent=top)
            try:
                open_path("ms-settings:defaultapps")
            except Exception as e:
                log.warning("Could not open Default apps page: %s", e)

        def _unregister():
            try:
                msg = _unregister_mail_client()
            except Exception as e:
                messagebox.showerror("Default mail client",
                                     f"Could not unregister:\n{e}", parent=top)
                return
            messagebox.showinfo("Default mail client", msg, parent=top)

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(pady=10)
        tk.Button(btns, text="Register", bg=C_BTN_NEW, fg=C_BTN_FG,
                  font=("Segoe UI", 9, "bold"), relief="flat", cursor="hand2",
                  padx=16, pady=4, command=_register).pack(side="left", padx=5)
        tk.Button(btns, text="Unregister", bg=C_BTN_DEL, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=16, pady=4, command=_unregister).pack(side="left", padx=5)
        tk.Button(btns, text="Close", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=16, pady=4, command=top.destroy).pack(side="left", padx=5)

    # ── Phase 2 switch (DEL 04i) ──────────────────────────────────────────────
    def _server_changes_dialog(self):
        """The one place where deleting on Gmail can be turned on."""
        top = self._dialog_shell("Server changes", 620, 560)
        v_on = tk.BooleanVar(
            value=bool(self.cfg.get("allow_server_changes", False)))

        f = tk.Frame(top, bg=C_BG3)
        f.pack(fill="both", expand=True, padx=16, pady=10)

        tk.Label(f, text="Let Delete remove mail from Gmail too",
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 11, "bold"),
                 anchor="w").pack(fill="x")
        tk.Label(f,
                 text="With this off (the default), Delete only hides a "
                      "message from this program's view; it stays on Gmail "
                      "and comes back on Refresh.\n\n"
                      "With it on, Delete moves the message to the Gmail "
                      "Trash — the same thing Thunderbird does when it is set "
                      "to delete on the server.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9), anchor="w",
                 justify="left", wraplength=560).pack(fill="x", pady=(4, 10))

        box = tk.Frame(f, bg=C_BG2, padx=12, pady=10)
        box.pack(fill="x")
        tk.Label(box, text="What it will and will not do",
                 bg=C_BG2, fg=C_ACCENT, font=("Segoe UI", 9, "bold"),
                 anchor="w").pack(fill="x")
        for line in (
                "✔  Moves the message to the Trash, where Gmail keeps it for "
                "30 days and you can restore it.",
                "✔  Tells you first — including every Gmail label the message "
                "would disappear from.",
                "✔  Warns you extra loudly for mail you sent to yourself, "
                "where Inbox and Sent are the same message.",
                "✘  Never erases anything permanently, and never empties the "
                "Trash.",
                "✘  Never happens automatically. No rule, filter or timer in "
                "this program can delete on the server — only you, clicking "
                "Delete and confirming."):
            tk.Label(box, text=line, bg=C_BG2,
                     fg=C_FG if line.startswith("✔") else C_FG_DIM,
                     font=("Segoe UI", 8), anchor="w", justify="left",
                     wraplength=530).pack(fill="x", pady=1)

        tk.Checkbutton(f, text="Delete on Gmail as well  (Phase 2)",
                       variable=v_on, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 10, "bold"), highlightthickness=0,
                       anchor="w").pack(fill="x", pady=(12, 0))

        arch = "on" if self.cfg.get("archive_auto") else "OFF"
        tk.Label(f,
                 text=f"Strongly recommended before you switch this on: turn "
                      f"on the local archive (File → Local archive), so every "
                      f"message you have looked at already exists as a file "
                      f"you own. It is currently {arch}.",
                 bg=C_BG3, fg="#ffd08a" if arch == "OFF" else C_FG_DIM,
                 font=("Segoe UI", 8, "italic"), anchor="w", justify="left",
                 wraplength=560).pack(fill="x", padx=4, pady=(10, 0))

        def _save():
            want = bool(v_on.get())
            if want and not self.cfg.get("allow_server_changes", False):
                # Turning it ON is the one action here worth a second look.
                if not messagebox.askyesno(
                        "Delete on Gmail",
                        "From now on, Delete will move messages to the Gmail "
                        "Trash for real.\n\nYou will still be asked to "
                        "confirm every single deletion, and nothing is ever "
                        "erased permanently.\n\nTurn it on?",
                        parent=top, default="no"):
                    return
            self.cfg["allow_server_changes"] = want
            _save_settings(self.cfg)
            log.info("allow_server_changes set to %s", want)
            top.destroy()
            self._flash("Delete now removes on Gmail" if want
                        else "Delete is local only again")

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(pady=12)
        tk.Button(btns, text="Save", bg=C_BTN_NEW, fg=C_BTN_FG,
                  font=("Segoe UI", 9, "bold"), relief="flat", cursor="hand2",
                  padx=18, pady=4, command=_save).pack(side="left", padx=5)
        tk.Button(btns, text="Local archive…", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=14, pady=4,
                  command=lambda: (top.destroy(),
                                   self._archive_dialog())).pack(side="left",
                                                                 padx=5)
        tk.Button(btns, text="Cancel", bg=C_BTN_STD, fg=C_BTN_FG,
                  font=("Segoe UI", 9), relief="flat", cursor="hand2",
                  padx=18, pady=4, command=top.destroy).pack(side="left",
                                                             padx=5)

    # ── Local archive (DEL 04h) ───────────────────────────────────────────────
    def _archive_dialog(self):
        """Keep your own copies. Explains what this is instead of what people
        coming from POP3 expect it to be."""
        top = self._dialog_shell("Local archive", 620, 560)
        v_auto = tk.BooleanVar(value=bool(self.cfg.get("archive_auto", False)))
        v_dir  = tk.StringVar(value=self.cfg.get("archive_dir")
                              or _archive_dir(self.cfg))

        f = tk.Frame(top, bg=C_BG3)
        f.pack(fill="both", expand=True, padx=16, pady=10)

        tk.Label(f, text="Your own copy of every message",
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 11, "bold"),
                 anchor="w").pack(fill="x")
        tk.Label(f,
                 text="Messages are written as .eml files into "
                      "account / folder / month sub-folders, so you can find "
                      "them years from now in Explorer without this program. "
                      "The same message is only ever written once.\n\n"
                      "This only ADDS files. Nothing is removed from Gmail, "
                      "now or later.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9), anchor="w",
                 justify="left", wraplength=560).pack(fill="x", pady=(4, 10))

        row = tk.Frame(f, bg=C_BG3)
        row.pack(fill="x", pady=3)
        tk.Label(row, text="Folder:", bg=C_BG3, fg=C_FG_DIM, width=9,
                 anchor="e", font=("Segoe UI", 9)).pack(side="left")
        e_dir = tk.Entry(row, textvariable=v_dir, bg=C_BG2, fg=C_FG,
                         relief="flat", font=("Segoe UI", 9),
                         insertbackground=C_ACCENT,
                         insertofftime=0, insertontime=9999999)
        no_blink(e_dir)
        e_dir.pack(side="left", fill="x", expand=True, ipady=3, padx=4)

        def _browse():
            from tkinter import filedialog
            d = filedialog.askdirectory(parent=top, title="Archive folder",
                                        initialdir=v_dir.get())
            if d:
                v_dir.set(d)

        tk.Button(row, text="…", bg=C_BTN_STD, fg=C_BTN_FG, relief="flat",
                  padx=8, command=_browse).pack(side="left")

        tk.Checkbutton(f, text="Keep a copy of every message automatically",
                       variable=v_auto, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 10, "bold"), highlightthickness=0,
                       anchor="w").pack(fill="x", pady=(12, 0))
        tk.Label(f, text="Off by default — this writes to your disk, so it is "
                         "your decision, not the program's. With it on, every "
                         "message F(re)email fetches is archived in the "
                         "background.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w",
                 justify="left", wraplength=540).pack(fill="x", padx=24)

        stats_lbl = tk.Label(f, text="", bg=C_BG2, fg=C_FG,
                             font=("Consolas", 9), anchor="w", justify="left",
                             padx=10, pady=8)
        stats_lbl.pack(fill="x", pady=(12, 0))

        def _refresh_stats():
            s = _archive_stats({"archive_dir": v_dir.get()})
            mb = s["bytes"] / (1024 * 1024)
            stats_lbl.configure(
                text=f"Archived now : {s['files']} message(s), "
                     f"{mb:.1f} MB\nLocation     : {s['path']}")

        def _save_only():
            self.cfg["archive_auto"] = bool(v_auto.get())
            self.cfg["archive_dir"]  = v_dir.get().strip()
            _save_settings(self.cfg)

        def _archive_now():
            _save_only()
            msgs = [m for m in self._messages if not m.get("_note_path")]
            if not msgs:
                messagebox.showinfo("Archive",
                                    "There is nothing loaded to archive. Open "
                                    "a folder first.", parent=top)
                return
            n = _archive_run(self.cfg, msgs)
            _refresh_stats()
            messagebox.showinfo(
                "Archive",
                f"{n} new message(s) archived"
                f"{f', {len(msgs) - n} were already there' if n < len(msgs) else ''}.",
                parent=top)

        tk.Label(f,
                 text="“Delete from the server after N days” is deliberately "
                      "not offered. On Gmail one message carries several "
                      "labels, so a timed rule aimed at Sent would also strip "
                      "it out of the Inbox — while you are not watching. Keep "
                      "copies here; delete over there by hand, seeing what "
                      "goes.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 anchor="w", justify="left",
                 wraplength=560).pack(fill="x", pady=(12, 0))

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(pady=10)
        for text, colour, cmd in (
                ("Archive this folder now", C_BTN_NEW, _archive_now),
                ("Open folder", C_BTN_STD,
                 lambda: self._open_path(v_dir.get())),
                ("Save", C_BTN_STD, lambda: (_save_only(), top.destroy(),
                                             self._flash("Archive settings saved"))),
                ("Close", C_BTN_STD, top.destroy)):
            tk.Button(btns, text=text, bg=colour, fg=C_BTN_FG,
                      font=("Segoe UI", 9), relief="flat", cursor="hand2",
                      padx=12, pady=4, command=cmd).pack(side="left", padx=4)
        _refresh_stats()

    def _open_path(self, path):
        """Open a folder in the system file manager."""
        try:
            os.makedirs(path, exist_ok=True)
            if platform.system() == "Windows":
                open_path(path)
            elif platform.system() == "Darwin":
                os.system(f'open "{path}"')
            else:
                os.system(f'xdg-open "{path}"')
        except Exception as e:
            messagebox.showerror("Open folder", f"Could not open:\n{e}",
                                 parent=self.root)

    # ── Blocked / local-spam senders ──────────────────────────────────────────
    def _blocklist_dialog(self):
        """What "Unsubscribe + block" and "+ mark as spam" have collected.

        Phase 1 cannot touch Gmail, so blocking is a local curtain: the mail
        still arrives and still sits in Gmail untouched, it is simply not
        shown here. Removing an entry brings it straight back."""
        top = self._dialog_shell("Blocked, trusted & kept-unread senders",
                                 600, 470)
        store = self._blocklist_store

        tk.Label(top,
                 text="🚫 Blocked senders are hidden from every list. "
                      "⚠ Spam senders keep the spam flag. "
                      "✔ Trusted senders get no phishing warnings (except "
                      "about dangerous attachments, which are never hidden) — "
                      "an entry that is a bare domain, e.g. "
                      "“boardgamegeek.com”, trusts everyone writing from it. "
                      "● Kept-unread senders stay marked unread in the Inbox "
                      "even after you read them (their taskbar badge is "
                      "blue-purple, not red). Nothing is deleted and Gmail is "
                      "not changed.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 wraplength=540, justify="left", pady=4).pack(fill="x", padx=12)

        frame = tk.Frame(top, bg=C_BG3)
        frame.pack(fill="both", expand=True, padx=12, pady=6)
        lb = self._listbox(frame, width=60)
        lb.pack(fill="both", expand=True)

        rows = []      # (kind, index) parallel to the listbox

        def _refresh():
            lb.delete(0, "end")
            rows.clear()
            for kind, key, icon in (("blocked", "blocked", "🚫"),
                                    ("spam", "spam", "⚠"),
                                    ("trusted", "trusted", "✔"),
                                    ("always_unread", "always_unread", "●")):
                for i, b in enumerate(store.get(key, [])):
                    lb.insert("end", f" {icon}  {b.get('match','')}"
                                     f"      (added {b.get('added','')[:10]})")
                    rows.append((key, i))
            if not rows:
                lb.insert("end", "   (nothing blocked, trusted or kept-unread)")

        def _remove():
            cur = lb.curselection()
            if not cur or cur[0] >= len(rows):
                return
            key, i = rows[cur[0]]
            entry = store[key][i]
            if key == "trusted":
                question = ("Trust this sender no longer (phishing warnings "
                            f"come back)?\n\n{entry.get('match','')}")
            elif key == "always_unread":
                question = ("Stop keeping this sender's mail marked unread?"
                            f"\n\n{entry.get('match','')}")
            else:
                question = f"Stop hiding “{entry.get('match','')}”?"
            if not messagebox.askyesno("Remove", question, parent=top):
                return
            del store[key][i]
            _save_blocklist(store)
            _refresh()
            self._refresh_messages()

        def _add_to(key, title, prompt):
            from tkinter import simpledialog
            val = simpledialog.askstring(title, prompt, parent=top)
            if not val:
                return
            store.setdefault(key, []).append(
                {"match": val.strip(), "added": _now_iso(), "reason": "manual"})
            _save_blocklist(store)
            _refresh()
            self._refresh_messages()

        def _add():
            _add_to("blocked", "Block sender",
                    "Address or part of an address to hide:")

        def _add_unread():
            _add_to("always_unread", "Keep sender unread",
                    "Address or part of an address whose mail should stay\n"
                    "marked unread even after you read it:")

        def _add_trusted():
            # The counterpart of the reading pane's "✔ Not phishing" buttons —
            # so a sender or a whole domain can be trusted before the first
            # false warning, and it is obvious that domains belong here too.
            _add_to("trusted", "Trust sender or domain",
                    "Address to stop warning about — or a bare domain\n"
                    "(e.g. boardgamegeek.com) to trust everyone there:")

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(pady=10)
        # Tip: you can also right-click any message → "Always keep sender
        # unread" to add its sender here in one click.
        for text, colour, cmd in (("Block…", C_BTN_NEW, _add),
                                  ("Trust…", "#2e6b4f", _add_trusted),
                                  ("Keep unread…", "#5a3fa8", _add_unread),
                                  ("Remove", C_BTN_DEL, _remove),
                                  ("Close", C_BTN_STD, top.destroy)):
            b = tk.Button(btns, text=text, bg=colour, fg=C_BTN_FG,
                          font=("Segoe UI", 9), relief="flat", cursor="hand2",
                          padx=14, pady=4, command=cmd)
            b.pack(side="left", padx=5)
            if text.startswith("Trust"):
                add_tooltip(b, "Stops the phishing warnings for one address, "
                               "or for every address at one domain. Warnings "
                               "about dangerous attachments are never "
                               "silenced.")
        tk.Label(top, text="Tip: right-click any message → “Always keep sender "
                           "unread” adds it here in one click.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 7, "italic"),
                 pady=2).pack()
        _refresh()

    # ── mailto: hand-off from Windows ─────────────────────────────────────────
    def open_mailto(self, url):
        """Open a compose window prefilled from a mailto: URL (DEL 04e)."""
        data = _parse_mailto(url)
        if not any(data.values()):
            return
        ComposeWindow(self.root, self.cfg, app=self, accounts=self._accounts,
                      prefill=data)

    # ── Window events ─────────────────────────────────────────────────────────
    def _on_configure(self, event):
        if event.widget is not self.root:
            return
        try:
            # Remember whether the window was MAXIMIZED, and — importantly —
            # do not overwrite the remembered size with the maximized one.
            # Otherwise un-maximizing next time gives you a window the size
            # of the screen instead of the size you actually chose, and the
            # maximized state itself is forgotten.
            zoomed = (self.root.state() == "zoomed")
            self.cfg["win_zoomed"] = zoomed
            if zoomed:
                return
            self.cfg["win_width"]  = self.root.winfo_width()
            self.cfg["win_height"] = self.root.winfo_height()
            self.cfg["win_x"]      = self.root.winfo_x()
            self.cfg["win_y"]      = self.root.winfo_y()
            # Only save the divider positions once _restore_sashes has actually
            # placed them. Before that (the first frames of a cold-boot
            # autostart) the panes are laid out tiny and sash_coord would
            # report a clamped, one-message-tall value that must never be
            # written back over the saved position.
            if getattr(self, "_sash_ready", False):
                self.cfg["sash_left"]  = self.pane.sash_coord(0)[0]
                self.cfg["sash_right"] = self.rpane.sash_coord(0)[1]
        except Exception:
            pass

    def _on_close(self):
        # A delete still sitting in its Undo window is committed now — the user
        # asked to delete it, so quitting must not silently un-delete it
        # (Issu 2026-08-01). Done before the outbox prompt so it can't be
        # skipped by a "cancel exit".
        try:
            self._flush_pending_deletes()
        except Exception as e:
            log.warning("flush pending deletes on close failed: %s", e)
        # Cancel every per-account auto-check timer, plus the other tickers.
        self._cancel_all_autochecks()
        self._cancel_read_timer()
        for attr in ("_outbox_after_id", "_cal_after_id"):
            aid = getattr(self, attr, None)
            if aid is not None:
                try:
                    self.root.after_cancel(aid)
                except Exception:
                    pass

        # Warn about mail that is queued but not yet sent — closing the
        # program is exactly when a scheduled message silently dies.
        pending = [m for m in self._outbox_store.get("messages", [])
                   if m.get("state") in ("queued", "failed")]
        if pending:
            when = []
            for m in pending[:4]:
                dt = _parse_iso(m.get("send_at", ""))
                when.append(f"  • {m.get('subject') or '(no subject)'} — "
                            f"{dt.strftime('%Y-%m-%d %H:%M') if dt else 'as soon as possible'}")
            if not messagebox.askyesno(
                    "Messages still in the outbox",
                    f"{len(pending)} message(s) have not been sent yet:\n\n" +
                    "\n".join(when) +
                    ("\n  …" if len(pending) > 4 else "") +
                    "\n\nThey stay in the outbox and go out the next time "
                    "F(re)email is running at their time.\n\nExit anyway?",
                    parent=self.root):
                return

        # From here on we are definitely leaving. The background body prefetch
        # checks this and stops, so closing the program is never held up by a
        # read-ahead nobody is waiting for any more (Issu 2026-08-08).
        self._closing = True

        if self.cfg.get("backup_on_exit", False):
            try:
                d = self.cfg.get("backup_dir") or _default_backup_dir()
                _backup_now(d)
                _prune_backups(d, int(self.cfg.get("backup_keep", 10)))
            except Exception as e:
                log.warning("Backup on exit failed: %s", e)

        # Do NOT write our in-memory settings back if a backup was just
        # restored — that would undo the restore (see _backup_dialog).
        if getattr(self, "_settings_restored", False):
            log.info("Settings were restored from a backup — not overwriting "
                     "settings.json on exit.")
        else:
            # Capture the CURRENT divider positions one last time, so a sash you
            # dragged and never touched the window afterwards is still saved.
            self._remember_sashes()
            _save_settings(self.cfg)
        # Close every pooled IMAP connection cleanly (DEL 04v).
        try:
            _imap_pool_close_all()
        except Exception:
            pass
        self.root.destroy()


# ******************************************************************************
# DEL 58 — PHONE SYNC (the Android app "Issu's Freemail") — THE CORE (no Tk in this part, so it can be tested alone)
# ******************************************************************************
# ToDo (2026-11-15): what is shared with the phone, and how.
#   The MAIL itself is NOT shared by this: the phone app talks to Gmail by itself (IMAP/SMTP) exactly like this program does, so no mail text
#   ever goes to the relay.  What goes through the relay (Issu's own small server, relay\freemail_relay.py) are F(re)email's OWN things:
#     "a" PROFILES = the Gmail accounts you tick (name, colour, signature text, the WhyBrowse profile its links open in).  Never a password.
#     "e" calendar events (both ways)         "c" address-book people (both ways)      "n" notes (the phone may add its own; PC notes are read-only there)
#     "p" post-it notes (PC -> phone)          "g" signatures, "t" templates (PC -> phone)
#   The Gmail app passwords travel ONLY by hand: "Copy mail logins for the phone" puts them on the clipboard (code ISSUMAIL1:...), you paste
#   it in the app.  They are never sent to the relay.
#   A record is {k: kind, u: change time in ms, d: 1 = deleted, s: "p" made on the phone / "c" made here, ...}; the newest u wins.  The letter "s" is
#   RESERVED for that flag: no kind may use it for its own data (events use "st" = start, templates "sj" = subject).  Both sides keep
#   complete copies and work offline; a round = pull, apply, push what changed, pull again (our own pushes echo back and are skipped).
#   Same transport rules as WhyBrowse.py DEL 57 and the same pairing code format ISSUSYNC1 (app = "freemail").
import base64 as _ps_b64
import hashlib as _ps_hashlib
import email.policy as _ps_policy
import email.utils as _ps_eutils

PS_CODE_PREFIX = "ISSUSYNC1:"
PS_LOGIN_PREFIX = "ISSUMAIL1:"
PS_STATE_F = os.path.join(_FM_DIR, "phone_sync.json")      # PRIVATE: holds the relay key
PS_RELAY_JSON = os.path.join(_FM_DIR, "relay.json")         # {"url": ..., "key": ...} written by relay\make_installer.py
PS_SHARE_KINDS = (("events", "Calendar events (both ways)"), ("contacts", "Address book people (both ways)"),
                  ("notes", "Notes (the phone can add its own)"), ("postit", "Post-it notes (to the phone)"),
                  ("signatures", "Signatures (to the phone)"), ("templates", "Templates / canned replies (to the phone)"))
_PS_ID = _re.compile(r"^[A-Za-z0-9_\-]{1,40}$")
_PS_ISO = _re.compile(r"^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2})?)?$")
_PS_EMAIL = _re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
_PS_URL = _re.compile(r"^https?://[^\s]+$", _re.I)


def ps_code_make(url, key, app="freemail"):
    """The text that is copied to the phone: prefix + base64url of {"a": app, "u": address, "k": key}.  It contains the relay key."""
    raw = json.dumps({"a": app, "u": url, "k": key}, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
    return PS_CODE_PREFIX + _ps_b64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")


def _ps_decode_json_prefix(t, prefix):
    """Shared by both codes: spaces / line breaks inside a code are ignored, and so is text after it (it sticks to the end, so shorten until
    what is left decodes)."""
    t = _re.sub(r"\s+", "", t or "")
    i = t.find(prefix)
    if i < 0:
        return None
    m = _re.match(r"[A-Za-z0-9_\-]+", t[i + len(prefix):])
    if not m:
        return None
    body = m.group(0)
    for n in range(len(body), max(len(body) - 400, 15), -1):
        try:
            d = json.loads(_ps_b64.urlsafe_b64decode(body[:n] + "=" * (-n % 4)).decode("utf-8"))
        except Exception:
            continue
        if isinstance(d, dict):
            return d
    return None


def ps_code_parse(text):
    d = _ps_decode_json_prefix(text, PS_CODE_PREFIX)
    if not d:
        return None
    url, key = str(d.get("u") or ""), str(d.get("k") or "")
    if not _PS_URL.match(url) or len(key) < 8:
        return None
    return {"app": str(d.get("a") or ""), "url": url, "key": key}


def ps_logins_make(items):
    """items = [(email, password, name)].  The code for 'Copy mail logins for the phone': it holds PASSWORDS - it goes to the clipboard only."""
    arr = [{"e": e, "p": p, "n": n or e} for e, p, n in items if e and p]
    raw = json.dumps({"a": "freemail", "x": arr}, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
    return PS_LOGIN_PREFIX + _ps_b64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")


def ps_logins_parse(text):
    d = _ps_decode_json_prefix(text, PS_LOGIN_PREFIX)
    if not d or not isinstance(d.get("x"), list):
        return None
    out = []
    for o in d["x"]:
        if isinstance(o, dict) and _PS_EMAIL.match(str(o.get("e") or "")) and o.get("p"):
            out.append({"email": str(o["e"]), "password": str(o["p"]), "name": str(o.get("n") or o["e"])})
    return out


def _ps_sha(text, n):
    return _ps_hashlib.sha1(text.encode("utf-8")).hexdigest()[:n]


def ps_rid(kind, text):
    """The same id on every device for the same thing: kind letter + _ + sha1 of its identity."""
    return kind + "_" + _ps_sha(text, 16)


def ps_event_rid(evid):
    return "e_" + evid if _PS_ID.match(evid or "") and len(evid) <= 30 else ps_rid("e", evid or "")


def _ps_hash(rec):
    d = {k: v for k, v in rec.items() if k not in ("u", "q", "d", "id", "x")}
    return _ps_sha(json.dumps(d, sort_keys=True, ensure_ascii=False, separators=(",", ":")), 16)


def ps_post(url, key, since, recs, timeout=25):
    """One call of the relay.  Raises RuntimeError with a plain text on every problem."""
    body = json.dumps({"since": since, "recs": recs}, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
    req = _urlreq.Request(url.rstrip("/") + "/sync", data=body, method="POST",
                          headers={"X-Sync-Key": key, "Content-Type": "application/json", "User-Agent": "Freemail-sync/1"})
    try:
        with _urlreq.urlopen(req, timeout=timeout) as r:
            ans = json.loads(r.read().decode("utf-8"))
    except _urlerr.HTTPError as e:
        raise RuntimeError({401: "the server says the key is wrong", 429: "the server says too many requests",
                            413: "too much data for the server"}.get(e.code, "the server answered HTTP %d" % e.code))
    except _urlerr.URLError as e:
        raise RuntimeError("could not reach the server (%s)" % (getattr(e, "reason", e),))
    except (ValueError, OSError) as e:
        raise RuntimeError("the server's answer was not understood (%s)" % (e,))
    if not isinstance(ans, dict) or "seq" not in ans:
        raise RuntimeError("the server's answer was not understood")
    return ans


def _ps_clip(v, n):
    return str(v if v is not None else "")[:n]


def ps_event_record(ev):
    """A calendar event of this program -> a sync record (None = not shared: too old to be of use on a phone)."""
    start = str(ev.get("start") or "")
    if not _PS_ISO.match(start):
        return None
    end = str(ev.get("end") or "")
    rr = ev.get("rrule") or {}
    horizon = (datetime.now() - timedelta(days=45)).strftime("%Y-%m-%dT%H:%M:%S")
    if not rr and (end or start) < horizon:
        return None
    if rr and rr.get("until") and str(rr["until"]) < horizon:
        return None
    rms = []
    for m in ev.get("reminders") or []:
        try:
            rms.append(int(m))
        except (TypeError, ValueError):
            pass
    return {"k": "e", "i": str(ev.get("id") or ""), "t": _ps_clip(ev.get("title"), 300), "l": _ps_clip(ev.get("location"), 300),
            "ds": _ps_clip(ev.get("description"), 4000), "st": start, "en": end if _PS_ISO.match(end) else "",
            "ad": bool(ev.get("all_day")), "rr": {k: rr[k] for k in ("freq", "interval", "count", "until", "byday") if rr.get(k) not in (None, "", 0, [])} if rr else {},
            "rm": rms[:10], "c": _ps_clip(ev.get("color"), 9)}


def ps_event_fields(r):
    """A sync record -> the fields of a calendar event of this program (None when the record is not usable)."""
    start = str(r.get("st") or "")
    if not _PS_ISO.match(start):
        return None
    end = str(r.get("en") or "")
    rr = r.get("rr") if isinstance(r.get("rr"), dict) else {}
    rr2 = {}
    if str(rr.get("freq") or "").upper() in ("DAILY", "WEEKLY", "MONTHLY", "YEARLY"):
        rr2["freq"] = str(rr["freq"]).upper()
        for k in ("interval", "count"):
            try:
                rr2[k] = max(0, int(rr.get(k) or 0))
            except (TypeError, ValueError):
                pass
        rr2["until"] = _ps_clip(rr.get("until"), 30)
        rr2["byday"] = [d for d in (rr.get("byday") or []) if isinstance(d, str) and len(d) == 2][:7]
    rms = []
    for m in r.get("rm") or []:
        try:
            rms.append(max(0, min(100000, int(m))))
        except (TypeError, ValueError):
            pass
    col = str(r.get("c") or "")
    return {"title": _ps_clip(r.get("t"), 300), "location": _ps_clip(r.get("l"), 300), "description": _ps_clip(r.get("ds"), 4000),
            "start": start, "end": end if _PS_ISO.match(end) else "", "all_day": bool(r.get("ad")), "rrule": rr2,
            "reminders": rms[:10], "color": col if _re.match(r"^#[0-9a-fA-F]{6}$", col) else ""}


def ps_match_profiles(accounts, profiles):
    """'Add all (profiles)': which WhyBrowse profile belongs to which account.  accounts = [{email, name}], profiles = [{id, name}].
    Returns {email: profile id} for the accounts where one profile is clearly the right one (others are left out, never guessed)."""
    def norm(s):
        return _re.sub(r"[^a-z0-9]", "", (s or "").lower())
    out, taken = {}, set()
    for a in accounts:
        em, nm = (a.get("email") or "").lower(), norm(a.get("name"))
        local = norm(em.split("@")[0])
        found = None
        for p in profiles:                                           # 1. the profile is named by the address itself
            if p["id"] not in taken and (p.get("name") or "").strip().lower() == em:
                found = p
                break
        if not found:
            for p in profiles:                                       # 2. the address name is part of the profile name, or the other way round
                pn = norm((p.get("name") or "").split("(")[0])
                if p["id"] in taken or not pn:
                    continue
                if (len(local) >= 4 and local in norm(p.get("name"))) or (len(pn) >= 4 and pn in local):
                    found = p
                    break
        if not found and len(nm) >= 3 and nm != "main":
            for p in profiles:                                       # 3. the account's own name ("Gotanetreserv") is in the profile name
                if p["id"] not in taken and nm in norm(p.get("name")):
                    found = p
                    break
        if found:
            out[a["email"]] = found["id"]
            taken.add(found["id"])
    return out


class PsCore:
    """host = PsHost (or a fake in the tests); state = the dict saved in phone_sync.json (url, key, since, known, src, auto, accounts, share, last)."""

    def __init__(self, host, state, now=None):
        self.host = host
        self.st = state
        for k, v in (("known", {}), ("src", {}), ("since", 0), ("accounts", []), ("share", {})):
            self.st.setdefault(k, v)
        self.now = now or (lambda: int(time.time() * 1000))

    def _shares(self, name):
        return bool(self.st["share"].get(name, True))

    # ---- what is shared right now (record id -> record, without u)
    def gather(self):
        out = {}
        ticked = {e.lower() for e in self.st["accounts"]}
        for a in self.host.accounts():
            em = (a.get("email") or "").strip()
            if em and em.lower() in ticked:
                out[ps_rid("a", em.lower())] = {"k": "a", "e": em, "n": _ps_clip(a.get("name") or em, 60), "c": _ps_clip(a.get("color") or "#4dabf7", 9),
                                                "w": _ps_clip(a.get("wb"), 60), "sg": _ps_clip(a.get("sig"), 4000)}
        if self._shares("events"):
            for ev in self.host.events():
                rec = ps_event_record(ev)
                if rec and rec["i"]:
                    out[ps_event_rid(rec["i"])] = rec
        if self._shares("contacts"):
            for p in self.host.contacts()[:5000]:
                em = str(p.get("email") or "").strip()
                if _PS_EMAIL.match(em):
                    out[ps_rid("c", em.lower())] = {"k": "c", "n": _ps_clip(p.get("name"), 120), "e": em, "g": _ps_clip(p.get("group"), 60)}
        if self._shares("notes"):
            for n in self.host.notes()[:500]:
                if _PS_ID.match(n["rid"]):
                    out[n["rid"]] = {"k": "n", "t": _ps_clip(n["t"], 300), "b": _ps_clip(n["b"], 20000), "dt": _ps_clip(n.get("dt"), 30)}
        if self._shares("postit"):
            seen = {}
            for p in self.host.postits()[:200]:
                t = str(p.get("title") or "")
                seen[t] = seen.get(t, 0) + 1
                out[ps_rid("p", t + "\x1f" + str(seen[t]))] = {"k": "p", "t": _ps_clip(t, 200), "b": _ps_clip(p.get("body"), 8000),
                                                               "c": int(p.get("color") or 0), "pn": 1 if p.get("pinned") else 0}
        if self._shares("signatures"):
            for g in self.host.signatures()[:100]:
                if g.get("name"):
                    out[ps_rid("g", g["name"])] = {"k": "g", "n": _ps_clip(g["name"], 100), "x": _ps_clip(g.get("text"), 4000)}
        if self._shares("templates"):
            for t in self.host.templates()[:200]:
                if t.get("name"):
                    out[ps_rid("t", t["name"])] = {"k": "t", "n": _ps_clip(t["name"], 100), "sj": _ps_clip(t.get("subject"), 300), "b": _ps_clip(t.get("body"), 8000)}
        for rid, rec in out.items():
            rec["s"] = "p" if self.st["src"].get(rid) == "p" else "c"
        return out

    # ---- what the other side sent
    def apply_remote(self, recs):
        stats = {"added": 0, "changed": 0, "removed": 0}
        known = self.st["known"]
        order = {"c": 0, "e": 1, "n": 2}
        for rid, r in sorted((recs or {}).items(), key=lambda kv: order.get(kv[1].get("k"), 3) if isinstance(kv[1], dict) else 9):
            if not isinstance(r, dict):
                continue
            try:
                u = int(r.get("u", 0))
            except (TypeError, ValueError):
                continue
            kn = known.get(rid)
            if kn and u <= int(kn.get("u", 0)):
                continue
            kind = r.get("k") or rid[:1]
            if r.get("d"):
                self._apply_delete(rid, kind, stats)
            else:
                if self._apply_record(rid, kind, r, stats) is False:
                    continue
                if r.get("s") == "p":
                    self.st["src"][rid] = "p"
            known[rid] = {"h": "" if r.get("d") else _ps_hash(r), "u": u, "d": 1 if r.get("d") else 0}
        return stats

    def _apply_record(self, rid, kind, r, stats):
        if kind == "e":
            evid = str(r.get("i") or "")
            f = ps_event_fields(r)
            if not _PS_ID.match(evid) or f is None or not self.shares_apply("events"):
                return True
            existed = self.host.upsert_event(evid, f)
            stats["changed" if existed else "added"] += 1
        elif kind == "c":
            em = str(r.get("e") or "").strip()
            if not _PS_EMAIL.match(em) or not self.shares_apply("contacts"):
                return True
            existed = self.host.upsert_contact(_ps_clip(r.get("n"), 120), em, _ps_clip(r.get("g"), 60))
            stats["changed" if existed else "added"] += 1
        elif kind == "n":
            if not self.shares_apply("notes") or not _PS_ID.match(rid):
                return True
            res = self.host.upsert_note(rid, _ps_clip(r.get("t"), 300), _ps_clip(r.get("b"), 20000), str(r.get("dt") or ""))
            if res is None:                      # a note of this PC (not made on a phone): the phone may not change it
                return False
            stats["changed" if res else "added"] += 1
        return True

    def shares_apply(self, name):
        return self._shares(name)

    def _apply_delete(self, rid, kind, stats):
        if kind == "e" and self.host.delete_event_by_rid(rid):
            stats["removed"] += 1
        elif kind == "c" and self.host.delete_contact_by_rid(rid):
            stats["removed"] += 1
        elif kind == "n" and self.st["src"].get(rid) == "p" and self.host.delete_note(rid):
            stats["removed"] += 1

    # ---- what we send
    def make_push(self):
        """Returns (records to send, the 'known' entries to keep once the server has them)."""
        local = self.gather()
        known = self.st["known"]
        push, newknown = {}, {}
        now = self.now()
        for rid, rec in local.items():
            h = _ps_hash(rec)
            kn = known.get(rid)
            if kn is None or kn.get("d") or kn.get("h") != h:
                u = max(now, int(kn.get("u", 0)) + 1 if kn else 0)
                push[rid] = dict(rec, u=u)
                newknown[rid] = {"h": h, "u": u, "d": 0}
        for rid, kn in known.items():
            if rid not in local and not kn.get("d"):    # not shared any more (unticked, deleted here): the phone drops it
                u = max(now, int(kn.get("u", 0)) + 1)
                push[rid] = {"k": rid[:1], "d": 1, "u": u}
                newknown[rid] = {"h": "", "u": u, "d": 1}
        return push, newknown

    def pull(self, ans):
        stats = self.apply_remote(ans.get("recs") or {})
        try:
            self.st["since"] = int(ans.get("seq", self.st["since"]))
        except (TypeError, ValueError):
            pass
        return stats

    def commit(self, newknown):
        self.st["known"].update(newknown)

    def sync(self, post):
        """The whole round with a blocking post(since, recs) -> answer (used by the tests; the program does the same step by step)."""
        stats = self.pull(post(self.st["since"], {}))
        push, newknown = self.make_push()
        if push:
            ans = post(self.st["since"], push)
            self.commit(newknown)
            for k, v in self.pull(ans).items():
                stats[k] += v
        stats["sent"] = len(push)
        return stats


def ps_state_load():
    st = {}
    try:
        if os.path.isfile(PS_STATE_F):
            with open(PS_STATE_F, "r", encoding="utf-8") as f:
                st = json.load(f)
    except Exception as e:
        log.warning("Phone sync: could not read the state: %s", e)
    if not isinstance(st, dict):
        st = {}
    for k, v in (("url", ""), ("key", ""), ("since", 0), ("known", {}), ("src", {}), ("auto", True), ("accounts", []), ("share", {}), ("last", {})):
        st.setdefault(k, v)
    return st


def ps_state_save(st):
    try:
        os.makedirs(os.path.dirname(PS_STATE_F), exist_ok=True)
        tmp = PS_STATE_F + ".tmp"
        with open(tmp, "w", encoding="utf-8") as f:
            json.dump(st, f)
        os.replace(tmp, PS_STATE_F)
    except Exception as e:
        log.warning("Phone sync: could not save the state: %s", e)


def ps_configured(st):
    return bool(st.get("url")) and bool(st.get("key"))


def ps_server_label(st):
    s = _re.sub(r"^[a-zA-Z]+://", "", st.get("url") or "")
    return s.split("/", 1)[0]


def ps_set_server(st, url, key):
    """A new server (or none): what was remembered about the old one is forgotten."""
    st["url"], st["key"], st["since"] = url, key, 0
    st["known"], st["src"], st["last"] = {}, {}, {}


def ps_wb_profiles():
    """The WhyBrowse profiles [{id, name}] (read-only look at its settings.json; favourites and phone-made ones are left out)."""
    try:
        with open(os.path.join(_HELPFILES, "WhyBrowse", "settings.json"), "r", encoding="utf-8") as f:
            data = json.load(f)
        return [{"id": str(p.get("id")), "name": str(p.get("name") or p.get("id"))} for p in data.get("profiles", [])
                if p.get("id") and not p.get("is_favourites") and p.get("id") != "favourites" and not p.get("phone_origin")]
    except Exception:
        return []


# ******************************************************************************
# DEL 58 — PHONE SYNC — THIS PROGRAM'S SIDE (adapter to the real stores, background runner, the "Phone sync" window)
# ******************************************************************************
class PsHost:
    """What PsCore needs from the running program.  Everything is read from / written to the program's own stores, on the Tk thread only."""

    def __init__(self, app):
        self.app = app

    def accounts(self):
        out = []
        bmap = (self.app._browser_store.get("map") or {}) if getattr(self.app, "_browser_store", None) else {}
        profs = {p["id"]: p["name"] for p in ps_wb_profiles()}
        for a in self.app._accounts:
            if a.get("virtual"):
                continue
            em = a["email"]
            wb = bmap.get(em) or bmap.get(em.lower()) or ""
            out.append({"email": em, "name": a.get("name") or em, "color": (getattr(self.app, "_acct_colors", {}) or {}).get(em, "#4dabf7"),
                        "wb": profs.get(wb, wb), "sig": _signature_for(self.app._signature_store, em)})
        return out

    # ---- calendar
    def events(self):
        return list(self.app._calendar_store.get("events", []))

    def upsert_event(self, evid, f):
        evs = self.app._calendar_store.setdefault("events", [])
        for ev in evs:
            if ev.get("id") == evid:
                for k, v in f.items():
                    if k == "color" and not v:
                        continue
                    ev[k] = v
                existed = True
                break
        else:
            ev = {"id": evid, "uid": "", "source": "phone", "created": datetime.now().strftime("%Y-%m-%dT%H:%M:%S")}
            ev.update(f)
            ev["color"] = f.get("color") or EVENT_PALETTE[0]
            evs.append(ev)
            existed = False
        _save_calendar(self.app._calendar_store)
        self._calendar_changed()
        return existed

    def delete_event_by_rid(self, rid):
        evs = self.app._calendar_store.get("events", [])
        keep = [e for e in evs if ps_event_rid(str(e.get("id") or "")) != rid]
        if len(keep) == len(evs):
            return False
        self.app._calendar_store["events"] = keep
        _save_calendar(self.app._calendar_store)
        self._calendar_changed()
        return True

    def _calendar_changed(self):
        try:
            w = getattr(self.app, "_calendar_win", None)
            if w is not None and w.top.winfo_exists():
                w.render()
        except Exception:
            pass

    # ---- address book
    def contacts(self):
        return list(self.app._addressbook_store.get("people", []))

    def upsert_contact(self, name, email, group):
        people = self.app._addressbook_store.setdefault("people", [])
        for p in people:
            if (p.get("email") or "").lower() == email.lower():
                p["name"] = name or p.get("name", "")
                if group:
                    p["group"] = group
                existed = True
                break
        else:
            people.append({"name": name, "email": email, "group": group})
            existed = False
        _save_addressbook(self.app._addressbook_store)
        return existed

    def delete_contact_by_rid(self, rid):
        people = self.app._addressbook_store.get("people", [])
        keep = [p for p in people if ps_rid("c", (p.get("email") or "").lower()) != rid]
        if len(keep) == len(people):
            return False
        self.app._addressbook_store["people"] = keep
        _save_addressbook(self.app._addressbook_store)
        return True

    # ---- notes (one .eml per note; a note made on the phone carries the header X-Freemail-Sync-Id = its record id)
    def _note_files(self):
        folder = _notes_dir(self.app.cfg)
        try:
            return [os.path.join(folder, n) for n in os.listdir(folder) if n.lower().endswith(".eml")] if os.path.isdir(folder) else []
        except OSError:
            return []

    def _read_note(self, path):
        try:
            with open(path, "rb") as f:
                em = _email.message_from_bytes(f.read(), policy=_ps_policy.default)
            part = em.get_body(preferencelist=("plain", "html"))
            body = part.get_content() if part is not None else ""
            dt = ""
            try:
                dt = _ps_eutils.parsedate_to_datetime(em["Date"]).strftime("%Y-%m-%dT%H:%M:%S") if em["Date"] else ""
            except Exception:
                dt = ""
            sid = str(em.get("X-Freemail-Sync-Id") or "").strip()
            return {"rid": sid if _PS_ID.match(sid) else ps_rid("n", os.path.basename(path)), "t": str(em["Subject"] or ""), "b": body,
                    "dt": dt, "phone": bool(sid), "path": path}
        except Exception as e:
            log.warning("Phone sync: unreadable note %s: %s", path, e)
            return None

    def notes(self):
        out = [n for n in (self._read_note(p) for p in self._note_files()) if n]
        out.sort(key=lambda n: n.get("dt") or "", reverse=True)
        return out

    def upsert_note(self, rid, title, body, dt=""):
        """True = changed a phone note, False = made a new one, None = this id is a note of the PC (never changed from the phone)."""
        found = next((n for n in (self._read_note(p) for p in self._note_files()) if n and n["rid"] == rid), None)
        if found and not found["phone"]:
            return None
        em = EmailMessage()
        em["Subject"] = title or "(no subject)"
        em["From"] = "me"
        em["To"] = "me"
        try:                                        # the phone's time of the note, so both sides read the same date back
            when = datetime.strptime(dt[:19], "%Y-%m-%dT%H:%M:%S")
        except ValueError:
            when = datetime.now()
        em["Date"] = format_datetime(when)
        em["X-Freemail-Note"] = "yes"
        em["X-Freemail-Note-Source"] = "phone"
        em["X-Freemail-Sync-Id"] = rid
        em.set_content(body or "")
        if found:
            path = found["path"]
        else:
            folder = _notes_dir(self.app.cfg)
            os.makedirs(folder, exist_ok=True)
            path = os.path.join(folder, _note_filename(title, datetime.now()))
            n = 1
            while os.path.exists(path):
                root_, ext_ = os.path.splitext(path)
                path = "%s(%d)%s" % (root_, n, ext_)
                n += 1
        with open(path, "wb") as f:
            f.write(em.as_bytes())
        return bool(found)

    def delete_note(self, rid):
        for p in self._note_files():
            n = self._read_note(p)
            if n and n["rid"] == rid and n["phone"]:
                return _note_delete(p)
        return False

    # ---- the rest (to the phone only)
    def postits(self):
        return _postit_load()

    def signatures(self):
        return list(self.app._signature_store.get("signatures", []))

    def templates(self):
        return list(self.app._template_store.get("templates", []))

    # ---- mail logins: only for the phone's clipboard code
    def logins(self, emails):
        want = {e.lower() for e in emails}
        out = []
        for a in self.app._accounts:
            if a.get("virtual") or a["email"].lower() not in want:
                continue
            pw = _decrypt_secret(a.get("secret", ""))
            if pw:
                out.append((a["email"], pw, a.get("name") or a["email"]))
        return out


class PsRunner:
    """One sync round on a worker thread.  The worker only talks to the network; everything that touches the program's data is handed to the Tk
    thread (root.after) and waited for, so the stores are never changed from two threads."""

    def __init__(self, app):
        self.app = app
        self.busy = False

    def _main(self, fn, timeout=90):
        box, ev = {}, threading.Event()

        def run():
            try:
                box["v"] = fn()
            except Exception as e:                       # handed back to the worker, which reports it
                box["e"] = e
            ev.set()
        self.app.root.after(0, run)
        if not ev.wait(timeout):
            raise RuntimeError("the program did not answer")
        if "e" in box:
            raise box["e"]
        return box.get("v")

    def start(self, done=None):
        """done(ok, message) is called on the Tk thread.  Returns False when a round is already running or nothing is set up."""
        st = self.app._ps_state
        if self.busy or not ps_configured(st):
            return False
        self.busy = True
        threading.Thread(target=self._work, args=(done,), daemon=True).start()
        return True

    def _finish(self, ok, msg, done):
        def f():
            self.busy = False
            st = self.app._ps_state
            st["last"] = {"t": time.time(), "ok": ok, "msg": msg}
            ps_state_save(st)
            if done:
                try:
                    done(ok, msg)
                except Exception as e:
                    log.warning("Phone sync: done callback: %s", e)
            cb = getattr(self.app, "_ps_on_finished", None)
            if cb:
                try:
                    cb(ok, msg)
                except Exception:
                    pass
        try:
            self.app.root.after(0, f)
        except Exception:
            self.busy = False

    def _work(self, done):
        st = self.app._ps_state
        url, key = st["url"], st["key"]
        try:
            a1 = ps_post(url, key, st["since"], {})

            def step2():
                core = PsCore(PsHost(self.app), st)
                stats = core.pull(a1)
                push, newknown = core.make_push()
                return core, stats, push, newknown
            core, stats, push, newknown = self._main(step2)
            if push:
                a2 = ps_post(url, key, st["since"], push)

                def step4():
                    core.commit(newknown)
                    return core.pull(a2)
                for k, v in self._main(step4).items():
                    stats[k] = stats.get(k, 0) + v
            msg = "sent %d, new %d, changed %d, removed %d" % (len(push), stats["added"], stats["changed"], stats["removed"])
            self._finish(True, msg, done)
        except Exception as e:
            log.warning("Phone sync failed: %s", e)
            self._finish(False, str(e) or e.__class__.__name__, done)


class _PsChoice:
    """A drop-down that quacks like an Entry (get / set), made of a tk.OptionMenu so it follows the dark theme."""

    def __init__(self, parent, choices, current):
        self.var = tk.StringVar(value=current)
        self.choices = choices
        self.menu = tk.OptionMenu(parent, self.var, *choices)
        self.menu.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4, activeforeground=C_FG, relief="flat", highlightthickness=0,
                            font=("Segoe UI", 9), anchor="w", width=40)
        self.menu["menu"].configure(bg=C_BG2, fg=C_FG, activebackground=C_BG4, activeforeground=C_FG, font=("Segoe UI", 9))

    def get(self):
        v = self.var.get()
        return "" if v == _PS_NONE else v

    def set(self, v):
        self.var.set(v or _PS_NONE)

    def pack(self, **kw):
        self.menu.pack(**kw)


_PS_NONE = "(none: use the fallback)"


def _ps_profile_label(profiles, value):
    """A stored profile value (an id or a name) -> the text shown in the drop-down 'Name  [id]'."""
    for p in profiles:
        if value and (value == p["id"] or value.lower() == p["name"].lower()):
            return "%s  [%s]" % (p["name"], p["id"])
    return value or _PS_NONE


def _ps_profile_value(text):
    """The reverse: 'Name  [id]' -> the id; anything else (a name typed in an older version) stays as it is."""
    m = _re.search(r"\[([^\]]+)\]\s*$", text or "")
    return m.group(1) if m else (text or "").strip()


def _ps_boot(self):
    """Called once from __init__: loads the state and, when a server is set up, syncs a little after start and then every 10 minutes."""
    self._ps_state = ps_state_load()
    self._ps_runner = PsRunner(self)
    self._ps_kick_id = None
    self._ps_on_finished = None
    if ps_configured(self._ps_state) and self._ps_state.get("auto", True):
        self.root.after(20000, self._ps_tick)


def _ps_tick(self):
    try:
        st = self._ps_state
        if ps_configured(st) and st.get("auto", True):
            self._ps_runner.start()
            self.root.after(10 * 60 * 1000, self._ps_tick)
    except Exception as e:
        log.warning("Phone sync tick: %s", e)


def _ps_kick(self):
    """A few seconds after the last change in the Phone sync window: send it (so there is no second thing to remember)."""
    try:
        if self._ps_kick_id is not None:
            self.root.after_cancel(self._ps_kick_id)
        self._ps_kick_id = self.root.after(3000, lambda: self._ps_runner.start())
    except Exception:
        pass


def _ps_server_dialog(self, parent_refresh):
    st = self._ps_state
    top = self._dialog_shell("Phone sync server", 640, 380)
    tk.Label(top, text="Paste the code made by the relay installer (it starts with ISSUSYNC1:) - or press 'Use relay.json' if the installer made the file "
                       "Helpfiles\\Freemail\\relay.json on this PC.  The code holds the key of your own server: keep it private.",
             bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9), wraplength=600, justify="left", pady=6).pack(fill="x", padx=14)
    e = self._labelled_entry(top, "Code:", 8)
    lbl = tk.Label(top, text="", bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9), wraplength=600, justify="left")
    lbl.pack(fill="x", padx=14, pady=6)
    if ps_configured(st):
        lbl.configure(text="Now: " + ps_server_label(st))

    def use_json():
        try:
            with open(PS_RELAY_JSON, "r", encoding="utf-8") as f:
                d = json.load(f)
            url, key = str(d.get("url") or ""), str(d.get("key") or "")
            if not _PS_URL.match(url) or len(key) < 8:
                raise ValueError("url or key missing")
            e.delete(0, "end")
            e.insert(0, ps_code_make(url, key))
            lbl.configure(fg="#7ddc7d", text="relay.json read: " + ps_server_label({"url": url}) + " - press Save.")
        except Exception as ex:
            lbl.configure(fg="#ffb86c", text="Could not use relay.json (%s)." % ex)

    def save():
        code = ps_code_parse(e.get())
        if not code:
            lbl.configure(fg="#ffb86c", text="That is not a sync code.")
            return
        if code["app"] not in ("", "freemail"):
            lbl.configure(fg="#ffb86c", text="That code is for another app (%s)." % code["app"])
            return
        if (code["url"], code["key"]) != (st.get("url"), st.get("key")):
            ps_set_server(st, code["url"], code["key"])
            ps_state_save(st)
        top.destroy()
        parent_refresh()
        self._ps_kick()

    def clear():
        ps_set_server(st, "", "")
        ps_state_save(st)
        top.destroy()
        parent_refresh()

    btns = tk.Frame(top, bg=C_BG3)
    btns.pack(pady=10)
    for text, colour, cmd in (("Use relay.json", C_BTN_STD, use_json), ("Save", C_BTN_NEW, save), ("Forget server", C_BTN_STD, clear),
                              ("Cancel", C_BTN_STD, top.destroy)):
        tk.Button(btns, text=text, bg=colour, fg=C_BTN_FG, font=("Segoe UI", 9), relief="flat", cursor="hand2", padx=14, pady=4,
                  command=cmd).pack(side="left", padx=4)


def _ps_dialog(self):
    """Accounts menu -> Phone sync: the server, WHICH PROFILES (= Gmail accounts) the phone gets, what else is shared, the codes for the phone."""
    st = self._ps_state
    host = PsHost(self)
    top = self._dialog_shell("Phone sync  (the Android app Issu's Freemail)", 860, 780)
    wrap = 800

    def lab(parent, text, dim=True, size=9, bold=False, **kw):
        l = tk.Label(parent, text=text, bg=C_BG3, fg=C_FG_DIM if dim else C_FG, font=("Segoe UI", size, "bold" if bold else "normal"),
                     wraplength=wrap, justify="left", anchor="w", **kw)
        l.pack(fill="x", padx=14, pady=(2, 2))
        return l

    lab(top, "The phone app shows the PROFILES (Gmail accounts) you tick here and reads their mail from Gmail itself, like this program does - "
             "no mail goes through your server.  Through the server go only: the profiles' names / colours / signatures, calendar, address book, "
             "notes, post-it notes and templates.  Passwords are never sent through it.", dim=True)
    lbl_status = lab(top, "", dim=False)
    lbl_will = lab(top, "", dim=False, bold=True)

    row1 = tk.Frame(top, bg=C_BG3)
    row1.pack(fill="x", padx=14, pady=4)

    def btn(parent, text, cmd, colour=C_BTN_STD):
        b = tk.Button(parent, text=text, bg=colour, fg=C_BTN_FG, font=("Segoe UI", 9), relief="flat", cursor="hand2", padx=12, pady=4, command=cmd)
        b.pack(side="left", padx=(0, 6))
        return b

    # ---- the profiles
    tk.Frame(top, bg=C_SEP, height=1).pack(fill="x", padx=14, pady=8)
    lab(top, "Profiles on the phone  (one per Gmail account)", dim=False, size=10, bold=True)
    lab(top, "Tick the accounts the phone should have.  A ticked profile is sent a few seconds later.  The 'link opens in' column is the "
             "WhyBrowse profile (Accounts > Browser profiles) that the phone's links will use.")
    box = tk.Frame(top, bg=C_BG3)
    box.pack(fill="x", padx=14)
    vars_ = {}
    wb = {p["id"]: p["name"] for p in ps_wb_profiles()}
    bmap = self._browser_store.get("map") or {}

    def changed():
        ps_state_save(st)
        refresh()
        self._ps_kick()

    def toggle(email, var):
        cur = {e.lower() for e in st["accounts"]}
        if var.get():
            cur.add(email.lower())
        else:
            cur.discard(email.lower())
        st["accounts"] = [a["email"] for a in host.accounts() if a["email"].lower() in cur]
        changed()

    for a in host.accounts():
        r = tk.Frame(box, bg=C_BG3)
        r.pack(fill="x", pady=1)
        v = tk.BooleanVar(value=a["email"].lower() in {e.lower() for e in st["accounts"]})
        vars_[a["email"]] = v
        tk.Checkbutton(r, variable=v, bg=C_BG3, activebackground=C_BG3, selectcolor=C_BG2, highlightthickness=0,
                       command=lambda em=a["email"], var=v: toggle(em, var)).pack(side="left")
        tk.Label(r, text="  ", bg=a["color"]).pack(side="left", padx=(0, 6))
        tk.Label(r, text="%s" % (a["name"],), bg=C_BG3, fg=C_FG, font=("Segoe UI", 10, "bold"), width=16, anchor="w").pack(side="left")
        tk.Label(r, text=a["email"], bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9), width=34, anchor="w").pack(side="left")
        wbv = bmap.get(a["email"]) or ""
        tk.Label(r, text="link opens in: " + (wb.get(wbv, wbv) or "(not set)"), bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w").pack(side="left")

    row2 = tk.Frame(top, bg=C_BG3)
    row2.pack(fill="x", padx=14, pady=(6, 0))

    def set_all(on):
        st["accounts"] = [a["email"] for a in host.accounts()] if on else []
        for em, var in vars_.items():
            var.set(on)
        changed()

    btn(row2, "Add all (profiles)", lambda: set_all(True), C_BTN_NEW)
    btn(row2, "Remove all", lambda: set_all(False))

    # ---- what else
    tk.Frame(top, bg=C_SEP, height=1).pack(fill="x", padx=14, pady=8)
    lab(top, "Also share with the phone", dim=False, size=10, bold=True)
    sh = tk.Frame(top, bg=C_BG3)
    sh.pack(fill="x", padx=14)
    for i, (name, text) in enumerate(PS_SHARE_KINDS):
        v = tk.BooleanVar(value=bool(st["share"].get(name, True)))

        def cmd(n=name, var=v):
            st["share"][n] = bool(var.get())
            changed()
        tk.Checkbutton(sh, text=text, variable=v, command=cmd, bg=C_BG3, fg=C_FG, selectcolor=C_BG2, activebackground=C_BG3,
                       activeforeground=C_FG, font=("Segoe UI", 9), highlightthickness=0, anchor="w", width=44).grid(row=i // 2, column=i % 2, sticky="w")

    # ---- codes
    tk.Frame(top, bg=C_SEP, height=1).pack(fill="x", padx=14, pady=8)
    lab(top, "Put it on the phone (once)", dim=False, size=10, bold=True)
    lab(top, "1. Server...  (once)     2. Copy the sync code, paste it in the app: Settings > Sync.     "
             "3. Copy the mail logins, paste them in the app: Settings > Mail logins.  The logins hold your Gmail app passwords: they go to the "
             "clipboard only, never to the server - send them only to your own phone.")
    lbl_code = lab(top, "", dim=False)
    row3 = tk.Frame(top, bg=C_BG3)
    row3.pack(fill="x", padx=14, pady=4)

    def copy_code():
        if not ps_configured(st):
            lbl_code.configure(fg="#ffb86c", text="No server yet: press Server... first.")
            return
        top.clipboard_clear()
        top.clipboard_append(ps_code_make(st["url"], st["key"]))
        lbl_code.configure(fg="#7ddc7d", text="Sync code copied.  In the app: Settings > Sync > Paste code.  (Copy something else when you are done.)")

    def copy_logins():
        em = list(st["accounts"])
        if not em:
            lbl_code.configure(fg="#ffb86c", text="No profile is ticked yet.")
            return
        if not messagebox.askyesno("Mail logins", "This copies the Gmail app passwords of the ticked profiles to the clipboard, as one code for the phone.\n\n"
                                   "They are NOT sent to the server.  Paste the code only in your own phone, then copy something else.\n\nCopy them now?", parent=top):
            return
        items = host.logins(em)
        if not items:
            lbl_code.configure(fg="#ffb86c", text="No password could be read for the ticked profiles.")
            return
        top.clipboard_clear()
        top.clipboard_append(ps_logins_make(items))
        lbl_code.configure(fg="#7ddc7d", text="%d mail login(s) copied.  In the app: Settings > Mail logins > Paste.  Copy something else when you are done." % len(items))

    def sync_now():
        if self._ps_runner.start():
            lbl_status.configure(text="Syncing...")

    btn(row3, "Server...", lambda: _ps_server_dialog(self, refresh))
    b_sync = btn(row3, "Sync now", sync_now)
    btn(row3, "Copy sync code", copy_code)
    btn(row3, "Copy mail logins", copy_logins)

    v_auto = tk.BooleanVar(value=bool(st.get("auto", True)))

    def auto():
        st["auto"] = bool(v_auto.get())
        ps_state_save(st)
        if st["auto"]:
            self.root.after(1000, self._ps_tick)
    tk.Checkbutton(top, text="Sync automatically (a little after start, then every 10 minutes)", variable=v_auto, command=auto, bg=C_BG3, fg=C_FG,
                   selectcolor=C_BG2, activebackground=C_BG3, activeforeground=C_FG, font=("Segoe UI", 9), highlightthickness=0,
                   anchor="w").pack(fill="x", padx=14, pady=(6, 0))

    def refresh():
        try:
            if ps_configured(st):
                last = st.get("last") or {}
                when = time.strftime("%Y-%m-%d %H:%M", time.localtime(last["t"])) if last.get("t") else "never"
                lbl_status.configure(fg=C_FG, text="Server: %s     Last sync: %s  -  %s" % (ps_server_label(st), when, last.get("msg") or "-"))
            else:
                lbl_status.configure(fg="#ffb86c", text="No server yet.  Press Server... and paste the code (or use relay.json).")
            try:
                recs = PsCore(host, st).gather()
            except Exception as e:
                log.warning("Phone sync summary: %s", e)
                recs = {}
            n = {}
            for r in recs.values():
                n[r["k"]] = n.get(r["k"], 0) + 1
            if not n.get("a"):
                lbl_will.configure(fg="#f0a030", text="The phone gets no profile yet: tick the accounts above (or press Add all (profiles)).")
            else:
                lbl_will.configure(fg=C_FG, text="The phone gets: %d profile(s), %d events, %d people, %d notes, %d post-it, %d signatures, %d templates."
                                   % (n.get("a", 0), n.get("e", 0), n.get("c", 0), n.get("n", 0), n.get("p", 0), n.get("g", 0), n.get("t", 0)))
            b_sync.configure(state="normal" if ps_configured(st) and not self._ps_runner.busy else "disabled")
        except tk.TclError:
            pass

    self._ps_on_finished = lambda ok, msg: refresh()
    top.bind("<Destroy>", lambda e: setattr(self, "_ps_on_finished", None) if e.widget is top else None)
    btns = tk.Frame(top, bg=C_BG3)
    btns.pack(pady=10)
    tk.Button(btns, text="Close", bg=C_BTN_STD, fg=C_BTN_FG, font=("Segoe UI", 9), relief="flat", cursor="hand2", padx=18, pady=4,
              command=top.destroy).pack()
    refresh()


FreemailApp._ps_boot = _ps_boot
FreemailApp._ps_tick = _ps_tick
FreemailApp._ps_kick = _ps_kick
FreemailApp._phone_sync_dialog = _ps_dialog


# ******************************************************************************
# DEL 10 — ENTRY POINT
# ******************************************************************************

def main():
    # FIRST line of every session: which file this actually is. When a new
    # feature "does nothing", the first thing to rule out is that the updated
    # copy was never put where the program is started from — and that is not
    # something you can see from the outside (Issu 2026-08-16, twice).
    try:
        log.info("=== F(re)email starting — %s — %s",
                 _build_stamp(),
                 os.path.abspath(sys.executable if getattr(sys, "frozen", False)
                                 else __file__))
    except Exception:
        pass

    # Move any pre-existing data into Helpfiles/Freemail/ BEFORE the app loads
    # its settings/accounts, so the very first run of this version already reads
    # from the new, consolidated location.
    _migrate_to_freemail_dir()

    root = tk.Tk()
    root.title("F(re)email")
    # Tk draws the buttons of its own message boxes and translates them with
    # the SYSTEM language — "Ja / Nej / Avbryt" on a Swedish Windows, inside a
    # program whose house rule is English only. Do this BEFORE any dialog can
    # possibly open (Issu 2026-08-03).
    _force_english_dialogs(root)
    app = FreemailApp(root)   # noqa: F841

    # Started from a mailto: link (Windows default-mail-client registration,
    # DEL 04e)? Open a prefilled compose window as soon as the UI is up.
    mailto = next((a for a in sys.argv[1:]
                   if a.lower().startswith("mailto:")), None)
    if mailto:
        root.after(300, lambda: app.open_mailto(mailto))

    root.after(0, lambda: _set_window_icon(root))
    root.after(1500, app._warn_unreadable_passwords)
    root.mainloop()

if __name__ == "__main__":
    main()
