# ============================================================================
#  ALLT I PROGRAMMET SKA ALLTID VARA PA ENGELSKA - ALDRIG SVENSKA!
#  EVERYTHING IN THIS PROGRAM MUST ALWAYS BE IN ENGLISH - NEVER SWEDISH!
# ============================================================================
#
#  WhyBrowse - a real, full web browser built on PyQt6-WebEngine (embedded
#  Chromium). It renders modern pages exactly like Chrome/Edge because it
#  uses the same engine under the hood. Tabs, address bar, back/forward,
#  bookmarks, history, downloads, zoom, find-on-page and full screen.
#
#  Created by  Lars "Issu" Olsson
#
#  Requirements (installed once via the .bat launcher):
#      pip install PyQt6 PyQt6-WebEngine
#      pip install libtorrent      (OPTIONAL - only for downloading torrents
#                                   inside WhyBrowse itself; see DEL 49)
#
#  ---------------------------------------------------------------------------
#  # ToDo  (what was done last, and what is left)
#  ---------------------------------------------------------------------------
#  DONE 2026-08-30 (rev83) - DEL 49, TORRENTS & MAGNET LINKS:
#      * magnet: and .torrent links are recognised when clicked on a page,
#        pasted in any address box, COPIED anywhere (clipboard watch), handed
#        over by another program, or right-clicked;
#      * three things can happen to one: download it here (built-in libtorrent
#        engine, with a Torrents window), save it as a .magnet file for a
#        torrent program's watch folder, or open it in that program;
#      * separate torrent folder (default X:\) or the normal download folder;
#        ask / automatic / ignore; speed limits; resume after a restart.
#  DONE 2026-09-28 (rev94) - DEL 51, THE NAV ARROWS' RIGHT-CLICK + "KEEP MY PLACE":
#      * right-click the Back arrow = the FIRST page of this tab (blank pages
#        skipped); right-click the Forward arrow = a COPY of this page in a new
#        tab beside this one. Forward is dimmed instead of disabled, because a
#        disabled widget gets no mouse events and so could never be right-clicked;
#      * "Keep my place": once YOU have scrolled a page, the page may not scroll
#        you back while it finishes loading. Settings - Performance, per site
#        under Exceptions, and in the Troubleshoot list.
#  DONE 2026-08-30 (rev84) - from the first look at rev83:
#      * the Torrents window is a window of its OWN (no parent), so it can go
#        behind the browser instead of sitting permanently in front of it, and
#        it remembers its size/position;
#      * "close this window when everything has finished" - in the window and
#        in Settings;
#      * Settings: the scrollbar is always visible, wide, on the left - AND the
#        mouse wheel can no longer change a drop-down/number box/slider it
#        merely passes over (WheelGuard).
#  LEFT for a later rev, deliberately:
#      * per-torrent file selection (pick which files inside a torrent to get);
#      * proper libtorrent resume data (today a resumed torrent re-checks the
#        files on disk instead - correct, just a few seconds of disk work);
#      * a torrent's own progress in the tab bar / taskbar badge.
#
#  All help files live relative to this program in /Helpfiles (works as EXE
#  too). Logs go to /Helpfiles/0---Empty. The window remembers its size and
#  the program remembers its settings between runs.
# ============================================================================


# ============================================================================
#  DEL 01 - IMPORTS, PART 1
#  Only the handful of modules the instant link hand-off (DEL 01b) needs. The
#  rest of the imports come afterwards, in DEL 01c, so that a launch whose only
#  job is to pass a URL to the window that is already open can finish and quit
#  before Python has loaded anything expensive.
# ============================================================================
import sys
import os
import json
import time
import hashlib

try:
    import ctypes
except Exception:
    ctypes = None

# NOTE: `platform` is deliberately NOT imported here. Its first call builds a
# full uname() - which on Windows costs about 40 ms - and the hand-off below
# runs on every single link click, so it asks os.name instead. platform is
# imported with the rest in DEL 01c and used normally from there on.


# ============================================================================
#  DEL 01b - INSTANT LINK HAND-OFF  (runs BEFORE Qt is even imported)
# ----------------------------------------------------------------------------
#  Click a link in another program - F(re)email, Thunderbird, anything - while
#  WhyBrowse is already open, and Windows starts a WHOLE SECOND WhyBrowse just
#  to say "open this address". That second copy used to load Qt and Chromium
#  first (seconds; and as a one-file .exe it also unpacks ~200 MB into a temp
#  folder every single time), only to hand the URL over the local pipe to the
#  window that was already there and immediately quit again. THAT is where the
#  "clicking a link takes forever" seconds went - not the address lookup.
#
#  This block does the hand-off FIRST, with nothing but the standard library.
#  If a running WhyBrowse answers on the pipe, the URL goes straight in and
#  this process exits in a few milliseconds - Qt is never imported at all. If
#  nobody answers, we fall through and start up completely normally.
#
#  Nothing else changes: same pipe, same wire format ("profile<TAB>url"), so an
#  older running instance still understands us and a plain URL behaves exactly
#  as before. The Qt version further down (forward_url_to_running_instance) is
#  kept as the belt-and-braces path for the case where the pipe only becomes
#  reachable later.
#
#  SIDE EFFECT WORTH KNOWING: this makes WhyBrowse.py itself a usable "open
#  this link in my browser" command. Point another program at
#      pythonw.exe  WhyBrowse.py  --profile=<id>  "<url>"
#  and it costs about a fifth of a second instead of a full browser launch.
# ============================================================================
def _early_base_dir():
    """The program's own folder - the same value BASE_DIR gets in DEL 03, but
    available this early, before the constants section has run.

    It must agree with app_base_dir() exactly: this one decides which pipe an
    already-running WhyBrowse is listening on, and a mismatch would make a
    second launch talk to nobody and open its own window.
    """
    d = os.path.dirname(os.path.abspath(
        sys.executable if getattr(sys, "frozen", False) else __file__))
    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 os.path.dirname(os.path.abspath(
        sys.executable if getattr(sys, "frozen", False) else __file__))


def _early_pipe_candidates(base_dir):
    """Every pipe name a running WhyBrowse could be listening on, best first.

    The name is an md5 of the program's folder (see ipc_pipe_name), which a
    caller has to reproduce EXACTLY - and Windows will happily hand the same
    folder back as "c:\\..." one time and "C:\\..." the next, which hashes
    differently. So the running instance writes its real pipe name into
    Helpfiles/WhyBrowse/ipc.json; that file is the authority and the md5
    guesses are only the fallback for when it is missing."""
    names, seen = [], set()

    def _add(n):
        if n and n not in seen:
            seen.add(n)
            names.append(n)

    # 1. What the running instance says it is actually listening on.
    try:
        p = os.path.join(base_dir, "Helpfiles", "WhyBrowse", "ipc.json")
        with open(p, "r", encoding="utf-8") as f:
            _add((json.load(f) or {}).get("pipe", ""))
    except Exception:
        pass

    # 2. The md5 of this folder, in the capitalisations Windows tends to use.
    for variant in (base_dir, os.path.normpath(base_dir),
                    base_dir[:1].upper() + base_dir[1:],
                    base_dir[:1].lower() + base_dir[1:]):
        try:
            _add("WhyBrowse_ipc_" + hashlib.md5(
                variant.encode("utf-8")).hexdigest())
        except Exception:
            pass
    return names


def _pipe_write(pipe_name, payload, timeout_ms=400):
    """Push `payload` into a local named pipe. True if it was accepted.

    Plain Win32 - no Qt - so this works before (and without) PyQt6. A pipe that
    nobody is listening on fails instantly, which is exactly what we want: the
    cost of guessing wrong is a fraction of a millisecond."""
    if os.name != "nt" or ctypes is None:
        return False
    path = r"\\.\pipe\%s" % pipe_name
    GENERIC_WRITE, OPEN_EXISTING, ERROR_PIPE_BUSY = 0x40000000, 3, 231
    try:
        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
            # Busy means the server IS there but every pipe instance is in use
            # for the moment - worth waiting for. Anything else means no
            # WhyBrowse is listening, so give up at once.
            if k32.GetLastError() != ERROR_PIPE_BUSY or time.time() > deadline:
                return False
            k32.WaitNamedPipeW(path, 100)
        try:
            data = payload.encode("utf-8")
            written = ctypes.c_uint32(0)
            ok = k32.WriteFile(ctypes.c_void_p(h), data, len(data),
                               ctypes.byref(written), None)
            k32.FlushFileBuffers(ctypes.c_void_p(h))
            return bool(ok) and written.value == len(data)
        finally:
            k32.CloseHandle(ctypes.c_void_p(h))
    except Exception:
        return False


def _early_log(base_dir, text):
    """One line into the normal log, without needing the logging section that
    has not been defined yet at this point in the file."""
    try:
        d = os.path.join(base_dir, "Helpfiles", "0---Empty")
        os.makedirs(d, exist_ok=True)
        with open(os.path.join(d, "whybrowse_log.txt"), "a",
                  encoding="utf-8") as f:
            f.write("[%s] %s\n" % (time.strftime("%Y-%m-%d %H:%M:%S"), text))
    except Exception:
        pass


def _early_link_handoff():
    """True when the URL on our command line was accepted by a WhyBrowse that
    is already running - meaning this process has nothing left to do."""
    if os.name != "nt":
        return False
    url, profile = "", ""
    for a in sys.argv[1:]:
        a = (a or "").strip().strip('"')
        if not a:
            continue
        if a.startswith("--profile="):
            profile = a.split("=", 1)[1].strip()
        elif a.startswith("-"):
            continue
        elif not url and a.startswith(("http://", "https://", "file://",
                                       "magnet:")):
            # magnet: too (DEL 49) - another program handing us a torrent link
            # must reach the WINDOW THAT IS ALREADY OPEN, not start a second
            # browser that asks its own question and then quits.
            url = a
    if not url:
        return False                     # a normal launch: start as usual
    base = _early_base_dir()
    payload = ("%s\t%s" % (profile, url)) if profile else url
    t0 = time.time()
    for name in _early_pipe_candidates(base):
        if _pipe_write(name, payload):
            _early_log(base, "Instant hand-off (no Qt loaded, %.0f ms): %s "
                             "profile=%s" % ((time.time() - t0) * 1000.0,
                                             url[:120], profile or "-"))
            return True
    return False


if __name__ == "__main__" and _early_link_handoff():
    raise SystemExit(0)


# ============================================================================
#  DEL 01c - IMPORTS, PART 2  (only reached when we really are starting up)
# ============================================================================
import re
import glob
import shutil
import sqlite3
import difflib
import tempfile
import platform
import threading
import subprocess
import traceback
import webbrowser
import urllib.request
import hmac
import random

# Optional: per-tab memory / CPU in the Profiles overview (DEL 41). If psutil is
# not installed those two columns simply hide themselves - nothing else breaks.
try:
    import psutil
except Exception:
    psutil = None

from PyQt6.QtCore import (
    Qt, QUrl, QSize, QTimer, QPoint, QPointF, QRect, QDateTime, pyqtSignal,
    QObject, QEvent, QStringListModel, QMimeData, QDir, QStandardPaths
)
from PyQt6.QtNetwork import QNetworkCookie, QLocalServer, QLocalSocket
from PyQt6.QtGui import (
    QIcon, QAction, QKeySequence, QShortcut, QFont, QColor, QPixmap, QPainter,
    QCursor, QMouseEvent, QDrag
)
from PyQt6.QtWidgets import (
    QApplication, QMainWindow, QTabWidget, QToolBar, QLineEdit, QPushButton,
    QWidget, QVBoxLayout, QHBoxLayout, QLabel, QDialog, QMenu, QFileDialog,
    QMessageBox, QStatusBar, QSizePolicy, QFrame, QListWidget,
    QListWidgetItem, QStyle, QTextBrowser, QCheckBox, QComboBox, QPlainTextEdit,
    QScrollArea, QGridLayout, QColorDialog, QInputDialog, QCompleter,
    QTreeWidget, QTreeWidgetItem, QAbstractItemView, QSpinBox,
    QWidgetAction, QToolButton, QStylePainter, QStyleOptionTab, QTabBar, QSplitter,
    QSlider, QFileIconProvider
)
from PyQt6.QtWebEngineWidgets import QWebEngineView
from PyQt6.QtWebEngineCore import (
    QWebEnginePage, QWebEngineProfile, QWebEngineSettings,
    QWebEngineDownloadRequest, QWebEngineScript,
    QWebEngineUrlRequestInterceptor, QWebEngineContextMenuRequest,
    qWebEngineChromiumVersion, qWebEngineChromiumSecurityPatchVersion, qWebEngineVersion
)


# ============================================================================
#  DEL 02 - CONSTANTS, COLORS AND NAMES
#  (Button colors are written out plainly so they are easy to change, e.g.
#   swap "#ffffff" / "white" for "red", "blue", "green", ...)
# ============================================================================
APP_NAME      = "WhyBrowse"
APP_TAGLINE   = "A real web browser, powered by Chromium"
APP_AUTHOR    = 'Created by  Lars "Issu" Olsson'
APP_ID        = "IssuSoft.WhyBrowse.1"          # Windows AppUserModelID

# TEMPORARY build marker so we always know WHICH version is running. Bumped on
# every change while we debug. Shown in a manual-close popup at startup (see
# VersionPopup) and in the window title. Remove the popup once things are stable.
APP_VERSION   = "0022-rev97  (2026-10-10)"

# The long change log lives HERE, not in APP_VERSION - and that split is
# itself rev81's bug fix. APP_VERSION used to BE this text: one unbroken
# single-line string of ~38 000 characters. Every label that showed
# "Version " + APP_VERSION laid it out as a single line, so the About box
# (a plain QLabel, no word-wrap) opened tens of thousands of pixels wide,
# and the startup pop-up (label with word-wrap, no scroll bar) opened
# several screens tall. It also wrote 38 KB into the log on every start.
#
# RULE FROM NOW ON: APP_VERSION is the SHORT build marker - it is what goes
# in labels, window titles, the log and bug reports. APP_HISTORY is the long
# text and may ONLY appear in a wrapped, SCROLLING box (VersionHistoryDialog).
# When you add a rev, put the new entry at the front of _HISTORY_LATEST and
# bump APP_VERSION - do not grow APP_VERSION itself again.
_HISTORY_LATEST = (
    "0022-rev97  (2026-10-10)  A LINK FROM ANOTHER PROGRAM NO LONGER STARTS A STRAY SECOND WHYBROWSE WHEN THE OPEN ONE IS ELEVATED. Reported: clicking AD in I_am_game started a NEW WhyBrowse where passwords and logins never worked, instead of using the open one. ROOT CAUSE (two halves): Tower starts WhyBrowse with the Admin flag, so the running copy is ELEVATED, and a normal (un-elevated) caller could neither (a) open its single-instance mutex - CreateMutexW answered Access denied, which check_single_instance read as nobody running - nor (b) write into its link pipe, whose default permissions give other processes read only. So the hand-off failed, the caller believed it was the first copy and opened a second PRIMARY on the same cookie database. FIX: check_single_instance now treats Access denied on the mutex as already running (so the link goes down the pipe, or at worst into the linked secondary session), and the pipe is created with UserAccessOption so this account can write to it from any integrity level. Also: a copy that fails to listen no longer deletes the running copy's ipc.json when it closes. NOTE: the pipe fix only exists in a WhyBrowse started AFTER this rev - restart the open one once.   "
    "0022-rev96  (2026-10-08)  VIDEO DOWNLOADS ARE A QUEUE NOW, AND NO LONGER TIED TO THEIR WINDOW (DEL 12I). Reported: only one download at a time, so a slow one holds up everything behind it - at least one tab per download, or a task queue - and the window seemed to have to stay on top all the time. The cause was one and the same: the downloader was ONE worker owned by ONE dialog. A second address had to wait for the first, and closing the dialog (or quitting) killed the download. (1) A MediaQueue now belongs to the browser window. Every address you add becomes a line in a list (state, percent and speed, name, format); up to 3 run side by side (spin box Download at once, 1-8, saved as media_parallel) and the rest wait and start by themselves. Enter in the address box adds the line and empties the box, so you can paste the next one at once. (2) Closing the dialog only hides it; the downloads go on and a toast appears on the browser when each finishes or fails. The menu entry shows how many are going. Quitting the browser with downloads running asks first. (3) The dialog is no longer owned by the browser window, so it can go behind it, be minimised or moved to another screen, and it has a taskbar button of its own. (4) Per line: Stop, Try again (yt-dlp continues the half-finished file), Remove, Clear finished; click a line to read its yt-dlp output. A duplicate of a line that is still queued or running is refused. Stop now kills the whole process tree (taskkill /T) - the single-file yt-dlp.exe starts a child and ffmpeg is another, so terminate() on the parent alone used to leave them running. List formats runs as a line of its own and never waits for a free slot.  "
    "0021-rev95  (2026-10-02)  HIDE AND BLOCK A WHOLE DOMAIN, NOT ONE SUB-ADDRESS AT A TIME (DEL 52). Reported: a DuckDuckGo page full of adress.hk-r.se, allaproffs.hk-r.se and hittat.hk-r.se - three lines for one site, after a fourth had already been blocked the same way. A link only ever shows you the sub-address, so that is all the menus offered; what you mean is the domain it hangs off. (1) THE BLOCK QUESTION now asks WHICH PART of the address: the one you right-clicked (still the default, because blocking a whole domain such as a blog host by accident is the worse mistake), every level in between, or the WHOLE registered domain, e.g. hk-r.se with every sub-address. It stops at the registered domain on purpose - se or co.uk as a block would take a whole country along (base_domain knows the two-part endings). The text under it, including the count of open tabs that are about to close, follows the choice. (2) THE SAME QUESTION carries a tick box 'Also keep it out of history and suggestions', which runs the existing keep-out-of-history rule on the chosen domain in the same step - what is already stored is removed at once. (3) HIDE FROM SEARCH RESULTS (link right-click) gets a second line aimed at the domain above, so one click hides every sub-address from Google, DuckDuckGo, Bing and the rest; the match in the page already counted sub-domains, only the menu could not name the parent. (4) KEEP OUT OF HISTORY AND SUGGESTIONS (page menu and the address bar's Suggestions menu) likewise offers the whole domain. (5) THE LISTS TIDY THEMSELVES: adding hk-r.se to the junk list, the search-hide list or the history list folds in the narrower lines it now covers (adress.hk-r.se, hittat.hk-r.se...) and a sub-address that a wider line already covers is not added again; the toast says how many lines were folded in. The menu actions of these entries also swallow the checked flag Qt may pass to a slot, so it can never be mistaken for the domain.  "
    "0021-rev94  (2026-09-28)  THE TWO NAV ARROWS GREW A RIGHT-CLICK, AND A PAGE MAY NO LONGER SCROLL YOU BACK (DEL 51). Three things asked for in one go. (1) RIGHT-CLICK THE BACK ARROW = the FIRST page of this tab, in one step instead of tapping Back a dozen times. First means the first REAL one: our blank new-tab page and about:blank are skipped by name, because landing on an empty page is not going back anywhere - what you land on is whatever opened the tab, the bookmark you clicked or the search results you came in through. It names where it went in a toast, and says so plainly when you are already there. (2) RIGHT-CLICK THE FORWARD ARROW = a COPY of the page you are on, in a new tab beside this one, and you land in the copy - so you can click on from there and still have the original sitting where you left it. THE CATCH THAT HAD TO BE SOLVED FIRST: Qt sends no mouse events at all to a DISABLED widget, and the Forward arrow is disabled on nearly every page you ever look at - which is exactly when a copy-this-page is most useful. So Forward is no longer disabled; it is DIMMED (a [wbdim] stylesheet rule, plus a new blend() that fades text towards its own background so it works in a light theme too, which darkening alone cannot), it looks the same as before, and a left-click with nothing forward now says so instead of doing nothing silently. (3) KEEP MY PLACE. Reported: 'titt som tatt, nar jag oppnar/gar till sida, och skrollar, sa drar fonstret sig till specifik plats - som att det inte har laddat fardigt och MASTE borja pa speciell plats'. That is precisely what it is: a page is not finished when it first appears - late stylesheets, fonts, adverts and lazy images keep arriving for seconds, and they bring scroll calls with them (a framework restoring a saved position, a #fragment applied late, a banner scrolling itself into view, an ad slot landing). They all fire AFTER you started reading. The new rule is about who asked LAST, not who is right: once YOU have scrolled a page, the page does not get to move you. A DocumentCreation script (it must wrap window.scrollTo, scrollBy, scrollIntoView and the documentElement.scrollTop setter before the page can take a reference to them) plus a watchdog on the scroll event for jumps the engine makes on its own. Four things keep it from breaking real sites: only the MAIN page scroll is guarded, so a chat that scrolls to the newest message or a spreadsheet grid is never touched; a jump you ASKED for still happens (within 0.4 s of your wheel/key, within 1.2 s of a click, and a smooth-scroll animation keeps its pass once let through, so wheel-jacking one-page sites still scroll); a route change in a web app (pushState/popstate/hashchange) counts as a NEW page so it can land at the top where it belongs; and it gives up after six corrections rather than flicker forever against a site that means it. WhyBrowse own scrolls buy a free pass with window.__wbScrollOK (the scroll-lock release, split-view sync scrolling). The same script also publishes window.__wbUserScrolled, which finally stops the two features that were themselves guilty of this: 'go to last position' retries at 0.4/1.2/2.5 s after load and 'jump to a word' for about 4 s - exactly the window in which you start reading - and both now stand down the moment you scroll. On by default; Settings - Performance, per site under Exceptions for this site, and in the Troubleshoot list so it can be bisected like every other feature.  "
    "0021-rev93  (2026-09-14)  YOUR SHORTCUTS NOW WIN, AND SIX OF THEM HAD BEEN QUIETLY LOSING (DEL 45/45d). Reported: 'jag vill spara en imdb-soksida som 'imdb'... nar jag skriver imdb sa blir det automatiskt imdb.com vilket jag inte vill. Mina shortcuts ska ha foretrade.' They were supposed to - _resolve_typed_url has always checked the keyword table first. The damage was done one step earlier, by the thing that was meant to HELP. _keyword_inline_suggest completes a typed keyword to the target's bare host as you type, so 'y' becomes 'y|outube.com' - fine when the shortcut points at a front page, and a lie when it points anywhere deeper. Worse, the lie came true: the box then read 'imdb.com', so on Enter there was no longer a keyword 'imdb' to match and the URL guess took over. MEASURED IN HIS OWN settings.json, not guessed: six shortcuts were being silently downgraded to a front page this way, every single time - c (claude.ai, losing one specific chat), p (predb.me, losing a long filtered search), b (boardgamegeek.com, losing /geekmail), t (tradera.com, losing /my/purchases), v (vinted.se, losing the inbox) and imdb. Every one of them because the host happens to start with the keyword; the ones that worked - a, o, gelf, nar - worked only because their host does NOT. FIX: the inline completion now fires only when the target really is the site's front page (is_root_target), where host and target are the same place. For a deeper target what you typed is left exactly as typed, the exact-keyword match takes it from there, and the destination is shown in the STATUS BAR instead - readable without changing what Enter does. Plus the escape hatch he asked for by name: a TRAILING DOT means 'I mean the domain, not my shortcut', so imdb. is imdb.com while imdb is your search page. Two more things in the same corner: a new shortcut now defaults to the whole first domain label ('imdb', not 'i') because three or four letters is the useful length, and the shortcut list shows where each one REALLY goes (imdb.com/find/?q=...), not just the host it shares with nothing. SECOND REPORT, same two boxes: typing 'i' handed back a column of links from an evening's browsing. The completer matches on CONTAINS, so one letter matches nearly every page ever visited. Three ways out were discussed and his own reasoning picked the third, which is right: a browser that remembers nothing looks like it is hiding something, one that never heard of a single site looks like nothing at all. So: right-click any page -> 'Keep <site> out of history & suggestions'. From that moment nothing from that domain is written to history or offered in any of the three address boxes - and what is already stored is removed on the spot, because otherwise the next letter you type hands it straight back. Entries you marked PROTECTED are left alone and the toast says how many, since deleting those from under a different switch is not this feature's business. Sub-domains count. The list is managed from the address bar's right-click menu (Suggestions & private domains), which also carries the other idea from the same conversation: suggestions do not start until you have typed 3 letters (settable 1-5). That gate is hidden in the same event as the pop-up is shown - QLineEdit's own completer slot runs first, ours runs immediately after - so nothing is ever painted and nothing flickers. Finally, a typed line that names no site at all cannot be reached by a per-domain rule, so the small boxes' right-click list now removes ONE line at a time instead of only offering to clear the lot.  "
    "0021-rev92  (2026-09-14)  RIGHT-CLICK A PAGE, BLOCK THE SITE, AND IT NEVER COMES UP AGAIN (DEL 21I). Asked for: a right-click on a page to BLOCK it outright, so it can never come up - for the sites that force new pages on you that you never asked for and do not want. THE GAP, and it is not that the machinery was missing: the junk list has done exactly this since DEL 21I. It refuses a blocked site's navigation, and closes the tab if the tab existed only for it. The trouble was WHERE IT LIVED. To reach it you right-clicked the page, opened 'Troubleshoot this page', opened 'Popups & junk sites' inside that, and picked 'JUNK SITE - block ... and close this tab': three sub-menus deep, under a heading you only open when something is BROKEN - which a pop-up farm working exactly as its owner intended is not. The junk list was empty; the feature had been there for weeks and had never once been used. FIX, in three parts. (1) The page right-click menu now carries 'BLOCK <site> - never open it again' as an entry of its own, and a link carries 'BLOCK <domain> - never let it open again', so a link you can already see is junk can be blocked without opening it first. One question before it happens - it is permanent and per-site - and that question names the way back out (Troubleshoot - Popups & junk sites - Junk sites and popup rules...), because a site you blocked and forgot is indistinguishable from a site that is broken, three weeks later. It also says how many open tabs it is about to close, and it closes ALL of them, not only the one you right-clicked. (2) THE HALF THAT WAS GENUINELY MISSING: the junk list only ever guarded main-frame navigation, so a blocked site could still run inside a page you DO want - as an iframe, a script, a beacon - which for a pop-up farm is the whole business. The list is now handed to the network interceptor as well (AdblockInterceptor.junk_domains), checked ABOVE the ad blocker's own early return: blocked means blocked with the ad blocker switched off, in Plain mode, and on a site that has an adblock exception. Human-verification widgets are never touched, so this can never loop a page back to 'Verify you are human'. (3) The master switch junk_autoclose turns the entire list off, and with it off blocking a site would have reported success and done nothing - the one failure mode this must not have - so blocking switches it back on and says in the toast that it did. One more thing fell out of this: a page-menu entry added in a new version used to be appended at the very BOTTOM of a menu you had arranged yourself, under 'Arrange this menu...' and under your own sub-menus, which is the one place a new feature is never seen (it is where Copy image, Save image as, unlock-scroll and the torrent entries have been sitting ever since they arrived). PAGE_MENU_NEAR now names the entry a newcomer belongs beside, and normalise_page_menu_layout puts it straight after that one wherever it sits in your arrangement, falling back to the old append when the neighbour is not there.  "
    "0021-rev91  (2026-09-09)  A HALF A DOZEN TABS TO REACH ONE VINTED SETTING - THE SWITCH THAT DID IT, AND WHY IT COULD NOT BE FOUND (DEL 42c). Reported: click an ad in the LOCKED Vinted tab and you land in the unlocked part, which is right; but click the ad's owner THERE and that opens a new tab too, and clicking on from there breeds six to twelve tabs that should all have been the same one - \"and it did do that, at least before the move to X:\". NOT A LOCK FAULT, and not the move either. It is the DEL 42 switch \"links open in a new tab by default\", read straight out of his live settings.json: links_open_new_tab was TRUE while links_newtab_off_v1 was ALSO true - so the one-time migration that turns it off for existing users had already run and something turned it back on afterwards, and a marker can only fire once. On top of that open_link_default was \"new_tab_go\", so every plain link click made a new tab AND jumped to it, which is what turns one navigation into a stack of tabs. The stale C: copy of settings.json had it on as well, which is how we know it pre-dates the move. THREE THINGS DONE. (1) Forced OFF once more behind a NEW marker (links_newtab_off_v2). A choice made after that is never touched again - a saved setting must beat a code default, which is precisely why v1 could not do the job twice. (2) It now has a real TICK BOX in Settings -> \"Startup & tabs\", with the plain words for what it does. Until now that switch lived ONLY as a checkable row on a link's right-click menu: nothing anywhere showed its state, there was no way to find it when you wanted it off, and a stray click while a link menu was open was enough to turn it on - which is the most likely way it happened. (3) The two places that READ it both fell back to True when the key was missing, while DEFAULT_SETTINGS says False; a settings file without the key therefore got the eager behaviour the default exists to prevent. Both now say False. AND A SECOND, SEPARATE FAULT FOUND WHILE PROVING THE FIRST ONE, WHICH WAS SILENTLY KILLING LOCK 3 / 3+ / PINNED ALTOGETHER. The lock block opens with a diagnostic log line, and that line called int(nav_type). PyQt6 6.11 hands NavigationType out as a plain enum.Enum, NOT an IntEnum, so int() on it raises TypeError - and the line sits inside the big try/except that ends in 'pass', so the exception was swallowed and execution jumped clean over every lock rule to the ordinary handler. A locked tab therefore let links load in place, which is the exact opposite of what a lock is for, and nothing was printed anywhere to say so. Measured, not guessed: driven on a real page standing on a Vinted item, lock 3 and pinned both produced NO new tab before the fix and the right one after it. A diagnostic that kills the feature it was added to explain is about as bad as it gets; it now asks for .value with the member itself as the fallback. UNCHANGED ON PURPOSE, because he asked for it: \"Open link in new tab\" from the right-click menu, middle-click, a bookmark set to open in a new tab, and lock 3 / 3+ / pinned all still make a new tab whatever this switch says. Only the plain left-click changed back to what a browser normally does. FOUND WHILE WRITING THIS ENTRY, AND FIXED WITH IT: the version-history box has been showing rev85 to rev91 as ONE unbroken wall of text. The splitter rev81 added breaks a paragraph at 'end of sentence, WHITESPACE, revNN' - but the entries are separate string literals joined with nothing between them, so the text really reads '...normally does.' with the next entry's own '0021-revNN  (date)' heading welded straight on to the full stop, and no gap for it to find. (Written with NN on purpose - spelling the real number here would tear this very sentence out into a heading of its own, which is the same trap the splitter's own comment warns about.) Every entry written since rev82 missed its own heading; the older text does carry the spaces, which is why the fault stayed hidden at the bottom of the list. The space is now optional (\\s* instead of \\s+) - 39 paragraphs became 45, and no future entry can lose its heading by being written the same way as the last one."
    "0021-rev90  (2026-09-09)  THE EMPTY 'NEW' TAB THAT CAME WITH EVERY LINK CLICKED IN A BGG GEEKMAIL (DEL 42b). Reported: click a link in the boardgamegeek.com inbox and you get TWO tabs - first an empty 'New' one, and under it the page you actually asked for. Seen once or twice before elsewhere, never on BGG. ROOT CAUSE, and it was ours, not the site's. A link with target=\"_blank\" makes Chromium ask createWindow() for somewhere to put it, and WhyBrowse answers with a fresh tab - correct so far. What is NOT obvious, and had to be measured in the engine rather than guessed, is what happens next: the opener page gets NO acceptNavigationRequest at all, and the BRAND-NEW page receives the navigation as NavigationTypeLinkClicked with is_main_frame=True and its own url() still empty. That is character for character what a plain link-click on an ordinary page looks like - so DEL 42 ('a link-click opens in a new tab so it is never a guess where it lands') fired on the tab that had just been created FOR that very link, handed the address to yet ANOTHER tab, and left the first one blank for good. FIX: createWindow() marks the page it hands back, and the first main-frame navigation on a marked page loads where it is. The mark is cleared the instant it is used, so only that first navigation is exempt and every later link in the tab behaves exactly as before; lock 3 / 3+ / pinned rules are untouched from the second navigation on. WHY BGG AND NOT EVERY SITE: it needs target=\"_blank\". A site that opens links with window.open in JavaScript produces NavigationTypeOther, which DEL 42 never matched, so those sites never showed the fault - which is exactly why it looked random and rare until a site he reads every day turned out to use the plain HTML form."
    "0021-rev89  (2026-09-09)  THE TWO SMALL BOXES NOW REMEMBER WHAT YOU TYPED - ONE SHARED LIST FOR BOTH (DEL 45c). Reported, after the move to X:: 'text blir aldrig kvar i adressfaltet, sa om sokningen blir dalig sa far jag skriva om hela, inte bara delar' - and the suggestion was a small history collected from BOTH the 'New tab' and 'This tab' boxes. THE GAP: emptying those two boxes on Enter is deliberate and stays that way (that is what lets you type the next address without selecting the old one first), but nothing anywhere kept the TEXT. The big address bar keeps the URL you landed on, which is no help at all when the thing you want back is the query 'imdb passenger' that produced a bad page - by then the bar says https://www.google.com/search?q=imdb+passenger and the words are buried in it. So a search that came out slightly wrong had to be typed again from the first letter. FIX, three ways in, all reading ONE list. (1) UP / DOWN ARROW, shell-style: press Up in either box to walk back through what you have typed, Down to walk forward, and Down past the top hands back the half-finished line you were on when you started walking - so a glance at an older search costs you nothing. The line arrives EDITABLE with the cursor at the end, which is the entire point: change the one word that was wrong and press Enter. (2) RIGHT-CLICK either box for a '(Recent - both boxes)' submenu with the last 20, newest first; picking one puts it in the box WITHOUT navigating, so you can still edit it before Enter. Cut/Copy/Paste stay where they were, underneath. (3) The list is SHARED between the two boxes on purpose - 'New tab' and 'This tab' are the same habit and you should not have to remember which one you used - and it survives a restart (settings key 'typed_history', newest first, no duplicates, capped at 60). Same submenu clears it. What is NOT recorded: an empty box, and a magnet/torrent link (those have their own window). The big address bar is untouched. WHY THIS IS NOT THE ADDRESS COMPLETER: that popup suggests pages you have VISITED, drawn from history and bookmarks - it can only ever offer 'imdb.com', never the words 'imdb passenger', because a search that gave a bad page is not a page you kept. This list is what you TYPED, which is the thing you want to edit."
    "0021-rev88  (2026-09-05)  A SLEEP DELAY PER SITE, AND THE WAY BACK IN THAT rev87 HAD CLOSED. Asked, after rev87: how many minutes is it, does it hit the Claude I talk to in a browser tab, and should a domain be able to carry its own number of minutes? It was five minutes (checked once a minute, so five to six in practice), it DID hit claude.ai, and yes. (1) HOW IT HIT IT. A background tab is Discarded after five idle minutes, which kills its render process: a prompt typed but not sent is gone from the page - the 7-day draft safety net has the last snapshot from while the tab was in front, but nothing types it back into a ProseMirror composer - and an answer still being written loses its live stream. Five minutes is nothing when you set something going and look at another tab. claude.ai, chatgpt.com and chat.openai.com are therefore on the built-in skip list now, beside chat and video. (2) SLEEP DELAY, PER TAB OR PER DOMAIN. New submenu under 'Not auto-sleep', on both the tab menu and the domain menu: use the general delay, or 5 / 15 / 30 min / 1 / 2 / 4 h. Stored as the domain rule 'sleepmin' (and per tab as _sleep_min, which is saved with the tab), read live by the new _sleep_delay_min(); _sleep_tick now works the delay out PER TAB instead of using one number for the whole window. Setting a delay restarts that tab's idle clock, so it does not sleep a second later because it had already been idle. (3) THE GAP rev87 LEFT, which this question exposed. Turning the feature round left only an opt-OUT - so a site on the built-in skip list could never be made to sleep at all, no matter what you did. A Sleep delay set BY HAND now beats that list (and the pinned-tab exemption), so every site can be sent either way: tick 'Not auto-sleep' to keep one loaded for good, or give it a number of minutes to make it sleep after all. The one thing no number overrides is sound actually playing right now."
    "0021-rev87  (2026-09-05)  AUTO-SLEEP TURNED ROUND, AND THE TWO SETTINGS THAT WERE QUIETLY EATING THE MEMORY. Reported: WhyBrowse climbs to a third of all RAM and the machine locks up at over 90%; sleeping idle tabs must simply BE what happens, so rename the switch to 'Not auto-sleep', mirror every choice, and have it start OFF on everything new. Done - and looking for it turned up why the memory grew in the first place, which was not the setting at all. (1) THE TURNAROUND. There used to be TWO boxes saying one thing: 'Auto-sleep' (opt IN, per tab or per domain) and its opposite 'Keep awake' (opt OUT). Both are gone, replaced by one box, 'Not auto-sleep', on the tab right-click menu, the domain menu and the profiles overview (the column is now 'No sleep'). Every idle background tab sleeps; the box is the exception and it starts empty on every new tab and every new domain. A saved 'autosleep' domain rule now says nothing new, so the four you had (shein, postnord, dhl, blocket) are dropped once, behind a marker, so a rule you set AFTER this is never touched again. Pinned tabs sleep too now - a slept pinned tab reloads to the page you pinned - with one tick in Settings to exempt them again. (2) THE REAL LEAK: OTHER PROFILES' TABS WERE NEVER SWEPT. 'Keep other profiles' tabs loaded' is on by default, so every profile you visit leaves its pages FULLY loaded in live_views for the rest of the session - but the sleep timer only ever walked the visible tab bar. Five profiles visited meant five profiles' worth of pages held in memory, immune to the very feature meant to stop that, and nothing in the window showed it. The timer now walks those too; they are background tabs by definition and sleep on the same idle clock. (3) 'KEEP BACKGROUND TABS FULLY ACTIVE' WAS ON, AND IT SWITCHES OFF CHROMIUM'S OWN MEMORY MANAGEMENT. It passes --disable-renderer-backgrounding, --disable-background-timer-throttling, --disable-backgrounding-occluded-windows and turns off IntensiveWakeUpThrottling - i.e. every hidden tab keeps running its timers and keeps its memory as if you were looking at it. That was added for a big Google Sheet that felt asleep; with auto-sleep now on by default it is redundant, so it is turned OFF once (same marker) and the Settings line now says plainly what it costs. Turn it back on there if you miss it. (4) WHAT NO LONGER GETS A FREE PASS. The built-in never-sleep list used to include Google Docs, Sheets, Drive, Slides, Script and Calendar - exactly where the memory sits, and they all save as you go. They sleep now. What is left is what sleeping would actually cost you: chat and mail, and video sites where a reload puts you back at 00:00. On top of that a tab is asked LIVE whether it is making sound (recentlyAudible), so a paused YouTube tab may sleep while the one you left playing may not. (5) NOT THE ONE-FOLDER BUILD. Going from one-file to one-folder changed startup, not memory: one-file unpacks ~171 MB to %TEMP% on every launch and runs a second process, so if anything it cost MORE. What it changed is that WhyBrowse now starts fast enough to be left open all day, which is when all three faults above have time to add up."
    "0021-rev86  (2026-09-01)  GOOGLE WOULD NOT LET A NEW PROFILE SIGN IN - ""'COULDN'T SIGN YOU IN, THIS BROWSER OR APP MAY NOT BE SECURE' (NEW DEL 50). Reported: five profiles work, the sixth cannot get into Drive - after the password Google refuses and offers only Try again. That five work and one does not is itself the clue: a profile that is ALREADY signed in stays signed in (we force persistent cookies), so it is the fresh SIGN-IN that Google blocks, not the browsing. Two answers were built, because the first is not guaranteed and the second is. FIRST, THE ENGINE STOPPED CONTRADICTING ITSELF. Measured, not guessed: the user-agent string said Chrome/140 while the sec-ch-ua header sent alongside it said only \"Not=A?Brand\";v=\"24\", \"Chromium\";v=\"140\" - a real Chrome sends a third brand, \"Google Chrome\". A server sees that mismatch on the very first request, before any of our injected JavaScript has run, which is why no amount of polishing the user-agent string could ever reach it. Two more of the same kind: window.chrome existed but was an EMPTY object (no app, csi, loadTimes or runtime - one of the oldest embedded-browser tells there is), and QtWebEngine sent NO Accept-Language header at all, which is also why navigator.languages was the bare ['sv'] instead of a real browser's ordered list. All three are now fixed, and deliberately from ONE source: the same brand list builds the Sec-CH-UA headers and overwrites navigator.userAgentData, so the header and the JavaScript cannot drift apart. Switch: Settings -> Privacy and blocking -> 'Present a complete Chrome identity'; it stands down automatically if you set a custom user agent by hand, since Chrome hints beside a Firefox user-agent would be the very contradiction this removes. SECOND, AND THE ONE THAT IS CERTAIN: menu -> 'Bring a Google sign-in over from Firefox'. Sign in to Google in Firefox, pick that Firefox profile and one WhyBrowse profile, and the finished session is copied across - Google's check is never run at all. Firefox is the source because its cookie store is a plain readable file; Chrome and Edge are deliberately not offered, their cookies have been sealed with app-bound encryption since Chrome 127. The dialog reads every Firefox profile once at startup (17 of them here, 0.08 s) and labels each one 'signed in to Google' or not, so you are not choosing blind between identical hex names, and the Import button names the target profile in full - the other profiles' logins must not be lost to a mis-click. THE MEASUREMENT THAT MADE IT WORK, KEEP IT: QWebEngineCookieStore.setCookie() is SILENTLY DISCARDED on a profile whose store has never had a live page - 26 cookies sent, 0 stored, no error and no Cookies table on disk; loadAllCookies() does not wake it, and merely constructing a page is not enough either, it has to have loaded something. That is exactly the case here, since the profile Google refuses is usually not the one on screen - the first version of this reported a cheerful 'imported 26 cookies' while writing nothing at all. It now gives the target profile a throwaway page first, and counts what the store says it ACCEPTED rather than what we handed it, so the number you are shown is the number that really landed. Verified end to end against the real Firefox profile: all 26 cookies on disk with the right host, path, secure and http-only flags, including the three __Host- ones that Chromium rejects outright if they are given a domain."
    "0021-rev85  (2026-08-31)  THE GREEN 'DONE' BOX IN TRADERA THAT NEVER WENT AWAY, AND THE MISSING SCROLLBAR - ONE AND THE SAME FAULT, AND IT WAS OURS. Reported: (1) after finishing a sale or booking postage, Tradera's little green confirmation box stays on screen until you press Refresh, even though Tradera means it to disappear by itself after a few seconds; (2) now and then a page comes up with no scrollbar at all, and the parts further down the page never arrive - again, only Refresh helps. ROOT CAUSE, MEASURED IN THE ENGINE, NOT GUESSED: the 'Stop animations & movement' setting (on by default, because blinking and moving things are unpleasant to look at) injected the rule *{animation:none; transition:none; animation-play-state:paused}. Those spellings do not SHORTEN an animation, they DELETE it - and a deleted animation never reaches its end, so the browser never fires the 'animationend' / 'transitionend' signals. Any site that finishes a piece of work in those signals therefore never finishes it. Tradera does exactly that, twice over: the green box hides itself with an animation that waits four seconds and then fades ('animation: fade .3s 4s forwards'), so frozen it simply sits there for ever; and a Tradera dialog fades its dark backdrop out and then, at the END of that fade, removes the backdrop and gives the page its scrolling back - so frozen, the page keeps the scroll lock the dialog put on it, which is precisely 'no scrollbar and nothing below the fold'. A reload was the only escape because a fresh page starts with no leftovers. FIX: the freeze rule no longer deletes anything. It sets the DURATION to one thousandth of a second and the repeat count to one, and it never touches the animation's name, its fill mode or its delay. Nothing moves - a blink, a pulse or a spinner is over before a single frame is drawn, exactly as before - but every animation and transition now properly starts AND ends, so the site's own clean-up runs on time. The delay is deliberately left alone: 'show this toast for four seconds' is Tradera's decision, and now it is honoured instead of ignored. Verified in this browser's own engine: with the old rule the green box was still there after five seconds and the page was still locked; with the new rule both are gone, while a blinking element and a spinner measurably do not move. SECOND, SEPARATE FAULT FOUND WHILE TESTING - the automatic scroll rescue had a blind spot. It only ever inspected <html> and <body>, but a modern site (Tradera and anything else built with Next.js) parks its scroll lock on its OWN full-height wrapper just inside <body> instead. That wrapper then clips the document down to a single screen, so the rescue's first question - 'is this page taller than the window?' - answered NO on exactly the page that was stuck, and it gave up before it started. The right-click 'Get scrolling back' already knew about this shape; the automatic guard did not, which is why it never rescued you on its own. It now looks two levels down from <body> as well, and only at elements that fill the screen AND are genuinely clipping something - so an ordinary app layout that scrolls in an inner pane, and a real dialog that is still open and means its lock, are both left alone. Both of those were re-tested and neither is touched.  "
    "0021-rev84  (2026-08-30)  THREE THINGS FROM THE FIRST LOOK AT rev83: THE TORRENTS WINDOW SAT PERMANENTLY IN FRONT OF THE BROWSER, IT NEEDED A 'CLOSE WHEN FINISHED' SWITCH, AND THE SETTINGS PAGE STILL CHANGED SETTINGS WHEN YOU SCROLLED PAST THEM.  (1) 'Torrentfonstret hamnar ovanfor whybrowse sa att det blir svart att anvanda.' Root cause, and it is a Windows rule rather than a mistake in the layout: a window that HAS a parent window is kept above that parent by the window manager, always, whatever you click. The Torrents window was a QDialog with the browser as its parent, so it could never go behind - exactly like a modal box that refuses to get out of the way. FIX: it is created with NO parent and with the plain Window flag, which makes it an ordinary window - it goes behind WhyBrowse when you click the browser, it has its own taskbar button, and Alt+Tab treats it like any other window. The browser still closes it on the way out, so nothing is left running with no window to show it. It also remembers its own size and position now, like every other window in the program.  (2) 'Auto close when finished' - asked for, added, and in two places: a tick-box in the Torrents window itself (saved the moment you tick it) and the same switch in Settings, Torrents. It only ever closes a window that had something RUNNING in it - opening the window on a list of already-finished torrents can never make it shut in your face - and it waits a couple of seconds after the last one finishes so you can see that it did.  (3) 'Jag rakar fortfarande andra olika settings nar jag skrollar med mus... for jag ser ingen skrollbar.' TWO separate faults, both fixed, and the second one is the one that was actually doing the damage. FIRST: the scrollbar. It used the shared style - a dark handle on a transparent groove, and only present while scrolling - which on a page as crowded as Settings is genuinely easy to miss. It is now always visible, wider (18 px), sitting in a groove you can see, with the accent colour on the handle, still on the LEFT edge where rev82 put it. SECOND, the real damage: Qt's drop-downs, number boxes and sliders all answer the mouse wheel by CHANGING THEIR VALUE. Scrolling from the top of Settings to the bottom therefore silently rewrote every combo box the pointer crossed on the way down. The new WheelGuard redirects the wheel to the scroll area's own scrollbar instead, so the wheel scrolls the page and changes nothing at all on the way past - deliberately with no exceptions, not even for a control that has keyboard focus, because 'the wheel never edits anything' is only worth something as a rule if there is nothing to remember. Values are still changed by clicking, typing or the arrow keys. Measured afterwards: a wheel tick over the startup drop-down, the temp-tab number box and the scroll-speed slider leaves all three untouched and moves the page 180 px each time.   "
    "0021-rev83  (2026-08-30)  TORRENT AND MAGNET LINKS ARE ACTED ON INSTEAD OF IGNORED (NEW DEL 49). Asked for: copying a magnet link should lead somewhere - download it straight away, into either the ordinary download folder or a separate torrent folder (X:\\), with a setting for whether that happens automatically, on a question, or not at all. THE GAP: a magnet: link is not a file. Nothing is stored behind it and there is no address to fetch - it is a 40-character fingerprint plus a hint about who might have it, which is why clicking one in ANY browser looks like it does nothing: Chromium cannot do anything with the scheme and silently drops it. Fetching the actual files means speaking BitTorrent, which a browser does not do. FIX, in three parts. (1) The link is now RECOGNISED everywhere it can turn up: clicked on a page (intercepted in acceptNavigationRequest before anything else touches it), pasted into any of the three address boxes, COPIED anywhere at all (a clipboard watch - the case that was actually asked about; magnet links only, since an https address ending in .torrent is copied for all sorts of reasons and a magnet link only ever for one), handed to WhyBrowse by another program (the instant hand-off in DEL 01b now accepts magnet: too, so it reaches the window that is already open instead of starting a second browser), or right-clicked ('Torrent this link'). A .torrent FILE address counts as the same thing, including one that only gives itself away by its mime type (application/x-bittorrent from a '/download.php?id=123' URL) - that is caught in the download handler and diverted, so it stops landing in the ordinary Downloads folder. (2) Three things can then happen to it, chosen per link in the pop-up or once and for all in Settings: DOWNLOAD IT HERE with a built-in engine - libtorrent, the same engine qBittorrent and Deluge are built on, wired up with pause/resume/remove, live speed, peers and seeds, ETA, speed limits, and a Torrents window (menu, or the page right-click menu) that shows the lot; SAVE THE LINK as a small 'name.magnet' file in the torrent folder, which is all a watch-folder-configured torrent program needs; or OPEN IN MY TORRENT PROGRAM, the hand-off other browsers do. (3) Where and whether: a separate torrent folder (default X:\\) or the normal download folder, and ask / automatic / ignore. The pop-up carries both, so 'always do this' answers the question once and never asks again. DETAILS THAT MATTER: the torrent session is created on FIRST USE, never at startup, so a launch that never meets a torrent pays nothing for this; an unfinished torrent survives a restart (the list is saved, and each torrent's own description is cached, so a resume does not have to find the swarm all over again just to learn what it is); a finished torrent is PAUSED, not silently left uploading, unless 'keep seeding' is turned on; UPnP is OFF by default because libtorrent's UPnP shutdown waits for the router and blocks for ~20 seconds - measured - which would have made CLOSING the browser take 20 seconds, and the setting says so in as many words; and a torrent with no live peers downloads nothing, which the window states plainly ('looking for the torrent info…') rather than pretending to work. The built-in engine needs libtorrent (pip install libtorrent) - without it the other two routes still work, and the pop-up says which is which instead of failing quietly.   "
    "0021-rev82  (2026-08-29)  SETTINGS: THE SCROLLBAR MOVED TO THE LEFT, AND THE PAGE STOPPED BEING WIDER THAN THE SCREEN. Two things, one window. First the one that was asked for: the vertical scrollbar in Settings now sits on the LEFT edge, right where the eye already is, instead of far out on the right. Second, the reason it was far out at all. Measured, not guessed: the Settings body demanded 2330 pixels of width. A checkbox cannot wrap its own label - it asks the layout for the full width of one unbroken line - so a single long row such as 'Let \"Verify you are human\" checks through (when a site shows a bot check, temporarily look like plain Chrome)' set the width of the entire page, a horizontal scrollbar appeared under everything, and the window had to be dragged out far past the edge of the monitor before a row could be read. Combo boxes did the same thing (a combo is as wide as its longest ITEM) and so did two long buttons sitting side by side. FIX: wrap_wide_controls() runs once, after the page is built, and breaks long checkbox and button labels onto several lines (Qt does honour a newline in those, even though it will not wrap them for you), turns real word-wrap on for long plain labels, and lets a combo be narrow while its drop-down still shows every entry in full. A second pass, fit_wide_rows(), handles the rows where each control is fine on its own but the row is not - a wrapped checkbox next to a button. Widest row left: 638 px, so the window opens at 700 and the horizontal scrollbar never appears. Also: the scroll area had a stylesheet of its own that replaced the shared one, which on Windows leaves the scrollbar groove with no handle to grab - it now keeps scrollbar_qss().  "
    "0021-rev81  (2026-08-22)  FIVE THINGS: THE ABOUT BOX WAS WIDER THAN THE SCREEN, 'LOADING… 80%' NEVER WENT AWAY, A DOWNLOAD THAT CLASHES WITH A FILE YOU ALREADY HAVE NOW ASKS WHAT TO DO (DEL 46), RIGHT-CLICKING A PICTURE FINALLY OFFERS COPY/SAVE IMAGE (DEL 47), AND A PAGE THAT GETS STUCK WITH NO SCROLLBAR UNSTICKS ITSELF (DEL 48).  (1) THE POP-UP WIDER THAN THE MONITOR, ALL TEXT ON ONE LINE. Root cause: this very string. APP_VERSION was not a version - it was the whole change log, one unbroken single-line string about 38 000 characters long, and About showed it with a plain QLabel that has no word-wrap. A QLabel asks the layout for the width of its longest line, the layout obliges, and the dialog opens tens of thousands of pixels wide with its Close button somewhere off in the dark. The startup version/cookie pop-up hit the same string from the other side: its label DOES wrap, so instead of one endless line it became a window several screens TALL, with no scroll bar. The same 38 KB was also written into the log file on every single start and pasted into every bug report. FIX: APP_VERSION is now the short build marker only ('0021-rev81  (2026-08-22)') and the long text moved to APP_HISTORY, which may only ever be shown in a wrapped, SCROLLING box - the new 'Version history' window, reachable from About and from the startup pop-up. Belt and braces: fit_to_screen() clamps a window to the monitor it is on, and it is wired to the application's focus-window signal, so ANY dialog that asks to be bigger than the screen from now on is pulled back inside it instead of opening off-edge.  (2) 'LOADING…' THAT HANGS ABOUT, ALWAYS ENDING AT 80%. Not a slow page - a status bar that was never cleared. loadProgress was connected as a bare 'self.on_load_progress' with no idea WHICH tab it came from, unlike every neighbouring signal, which all bind their view. So any background tab - an auto-refresh tab, a watched page, a link opened behind - wrote its progress into the one shared status bar; and on_load_finished only clears that bar for the tab you are LOOKING at. A background tab therefore left its last progress number sitting there for the rest of the session with nothing left to clear it. Why always 80: the progress text is drawn only for 0 < p < 100, because 100 arrives together with loadFinished and would flash for a frame, so the last number you ever see is the highest step Chromium reported below 100 - and Chromium's steps are coarse, so it is nearly always the same number. 80% did not mean 80% done, it meant 'this is where the counter stopped being drawn'. FIX: loadProgress binds its view like everything else and background tabs never touch the status bar; the message now reads 'Loading… 80%  ·  12s' with a once-a-second elapsed clock, so a page still working is visibly different from one that has stalled; switching tabs shows THAT tab's state and wipes any stale one; and a finished load clears it. Genuinely slow loads are still slow - but you can now see which is which.  (3) SAVING A FILE YOU ALREADY HAVE - 'Backup old, overwrite' (DEL 46). Asked for: saving the same program again and again gave WhyBrowse.py, WhyBrowse (1).py, WhyBrowse (2).py … which is safe but turns into housekeeping. Downloads used to resolve a clash silently, always by adding a number. Now, when the incoming file clashes, a pop-up offers the same three choices File_manager gives: BACK UP THE OLD ONE AND TAKE ITS NAME (the old file is renamed Backup<CODE>-<name> using the very same backup_codes.json pool File_manager uses, so codes never collide between the two programs and repeated backups of one program never overwrite each other), SAVE WITH A NUMBER (what it always did), or OVERWRITE WITHOUT A BACKUP. Two kinds of clash are detected, and the second is the point: an EXACT name match, and a name that is only a copy-suffix away from one you have - 'WhyBrowse (3).py' arriving next to 'WhyBrowse.py' is recognised as the same file, so 'back up and take its name' hands you a clean WhyBrowse.py and keeps the old one. (A 1-3 digit suffix only, so 'Report (2024).pdf' is left alone.) Nothing is destroyed before the new file has actually landed: the old file is moved aside first and only deleted once the download reports Completed - if it fails or is cancelled, the old file is put straight back. 'Always do this' on the pop-up stores the choice per profile, and Settings → Downloads has the same setting with a fourth option, Ask (the default), to turn the question back on.  (4) 'HAR INGEN COPY IMAGE-ALTERNATIV?' - NO, AND IT NEVER HAD (DEL 47). Right-clicking a picture offered nothing at all: no Copy image, no Save image as, no image address. Root cause: BrowserView.contextMenuEvent replaces Chromium's own context menu outright with show_page_menu(), and the replacement only ever asked ONE question about what was under the cursor - 'is there a link here?'. Chromium knew perfectly well what had been clicked all along (lastContextMenuRequest carries mediaType and mediaUrl) and the engine actions existed (CopyImageToClipboard, DownloadImageToDisk); they were simply never asked for. FIX: four new rows on a picture - Copy image, Save image as…, Copy image address, Open image in a new tab - plus Copy video / audio address when the thing under the cursor is a video or a sound. A <canvas> is handled honestly: it has no address of its own, so it gets Copy image and Save image as only (Chromium still hands over the pixels) and the two address rows stay away rather than appearing and doing nothing. Saving an image goes through the ordinary download path, so the download folder and the DEL 46 same-name question apply to it as well. All five rows are normal page-menu entries, so they can be moved, grouped or hidden in '⚙ Arrange this menu…' - and because normalise_page_menu_layout() appends ids the catalogue has but a saved arrangement does not, an existing page_menu.json picks them up automatically instead of silently missing the new feature.  (5) NO SCROLLBAR, DEAD MOUSE WHEEL, ONLY REFRESH HELPS (DEL 48). Reported on Tradera, profile 4: the page suddenly could not be scrolled at all and a reload was the only way back. A site stops the page behind a pop-up from scrolling (overflow:hidden on html/body, or the position:fixed 'iOS trick') and lifts that when the pop-up closes - so if the pop-up is hidden or removed by anything OTHER than the site's own close handler (our nag/cookie hider, the pop-up killer, an element you zapped, or the site's own script losing its place), nobody ever lifts the lock. WhyBrowse already had THREE unlock snippets - in the cookie auto-accepter, the pop-up killer and the YouTube ad-block - and all three shared two faults, both MEASURED rather than guessed. First, each only ran inside its own feature: the cookie one only when auto-accept was switched on, and even then only for about 7 seconds after load, so a lock applied later met nothing at all. Second, all three tested getComputedStyle(el).overflow === 'hidden', and overflow is a SHORTHAND - measured in this engine, body{overflow:hidden} reads back as 'hidden' and is caught, but body{overflow-y:hidden} reads 'auto hidden', body{position:fixed} reads 'visible' and body{overflow:clip} reads 'clip', so the three commonest spellings of a scroll lock walked straight past all of them. FIX: one general guard (SCROLL_GUARD_SCRIPT) that reads overflow-Y rather than the shorthand, watches html and body with a MutationObserver plus a 700 ms tick for as long as the page is open, and releases the lock. It is deliberately cautious: it acts only when the page really is taller than the window AND one hit-test at the centre of the screen finds no visible full-screen overlay - because a real, visible dialog is SUPPOSED to stop the page behind it - and it needs two consecutive ticks so a modal that is still opening is never fought. It never touches overflow-X (sites hide sideways scrolling on purpose; the old code forced the shorthand to auto and handed the page a horizontal scrollbar it never asked for), it restores the scroll position the iOS trick parks in a negative top instead of jumping you to the top, and after 8 releases on one page it stops rather than flicker against a site that means it. Two measurements shaped the code and are worth keeping: a body pinned with position:fixed leaves the flow, so documentElement.scrollHeight collapses to one screen AND body's own scrollHeight also reports one screen - only getBoundingClientRect().height tells the truth, and without asking it the guard concluded 'nothing to scroll' on exactly the page that was stuck. There is also a manual override that needs no reload: right-click the page -> 'Get scrolling back (unlock this page)', which releases unconditionally (even under a visible modal, because by then you have decided) and also lifts a lock parked on a full-height wrapper just inside body. Global switch in Settings -> Performance, per-site switch in 'Exceptions for this site'.   "
)

_HISTORY_OLDER = "0021-rev80  (2026-08-14)  ADDRESS SHORTCUTS (DEL 45) - TYPE 'b', LAND ON BOARDGAMEGEEK.COM. Asked: type in the New tab / This tab / main address box and have a short keyword jump straight to a chosen site - 'b' -> boardgamegeek.com, 'bl' -> blocket.se, 't' -> tradera.com. THE GAP: the address completer already sourced from history + bookmarks, but that is a fuzzy 'contains' match over everything you have ever visited - typing 'b' surfaces every candidate with a b in it, not one deterministic site, and there was no way to bind a specific short keyword to a specific site at all. FIX: right-click the address bar -> 'Add a shortcut for THIS page...' to bind a keyword to the page you are on (pre-filled with its first letter, e.g. 'b' for boardgamegeek.com); manage/rename/remove them all from the same menu's 'Address shortcuts' submenu. Typing a saved keyword in ANY of the three address boxes (New tab, This tab, the main bar) now inline-completes the site the instant it matches exactly - 'b' becomes 'b|oardgamegeek.com' (| = the auto-completed part, pre-selected) - so Enter/Tab accepts it and typing straight over the selection (one more letter, making 'bl') swaps to whatever THAT keyword points at instead; a bare Enter right after typing just the keyword works too even before the inline completion visually lands, since the exact-keyword check runs again at Enter time. The New tab box also gained the general history/bookmark suggestion popup it was missing before. Conflicting keyword? It asks before overwriting.   rev79  (2026-08-13)  PIN IS NOW STRICTLY PER-TAB - THE DOMAIN-WIDE PIN RULE IS GONE. Reported symptom: opening a link from an already-pinned tab (which correctly stays put and sends the link to a NEW tab instead) kept handing that new tab a pin too, so every extra tab on the same site had to be un-pinned by hand. ROOT CAUSE: 'Pin' could be set two ways - per tab (📌 in the THIS TAB menu) and per domain (📌 in the THIS DOMAIN menu, 'any tab that visits this domain'). The domain version was meant for a single always-open tab like WhatsApp Web, but on a browsing-heavy site like Vinted it fought the very feature meant to protect a pinned tab: a link click was correctly sent to a fresh tab, that fresh tab correctly landed on the same domain, and the domain rule then pinned it anyway - a domain-scoped 'no auto-pin for a tab you opened from a link' guard already existed but the domain rule could still catch it through paths the guard did not cover (typed addresses, bookmarks, session restore). FIX: the per-domain Pin option is removed from the THIS DOMAIN menu entirely (Auto-refresh/Lock/Auto-sleep domain rules are unchanged); any 'pin' left over in an old settings.json is stripped on load and can never re-apply. Pinning several different tabs of the same site is now always a deliberate, one-click-per-tab action - never done FOR you.  rev78  (2026-08-12)  PLAIN MODE NOW REALLY TURNS OFF SAVED POP-UP-KILL RULES + A TROUBLESHOOT SHORTCUT FOR IT. Reported symptom: an old pop-up-kill rule saved for one site's cookie box (Facebook, DEL 21L) can end up matching something unrelated later, since these sites reuse generic class names - an ad in the feed opened, showed its picture and text for a blink, then got auto-clicked/removed by the stale rule, leaving the page unresponsive to typing or reading. THE BUG: _content_cfg() zeroes elementHide/adblock/cosmetic for Plain mode (clean_mode), but _apply_popupkill - the function that runs saved pop-up/element-hide rules on every load via on_load_finished, plus continuously via a MutationObserver and a 2s interval - never checked clean_mode at all, so Plain mode's own tooltip promise ('turns off ALL blocking/scripts') was not true for these rules specifically. _apply_popupkill now returns immediately when _clean_active() is true, so Plain mode actually stops them. ALSO ADDED, right where the problem is found: right-click a page -> 🔧 Troubleshoot this page -> 🚫 Popups & junk sites now has a checkable '🧹 Turn OFF ALL pop-up-block / element-hide rules, everywhere (Plain mode)' row at the bottom - the same global clean_mode switch as the toolbar 🧹 button and the burger-menu entry, just placed directly in the menu where someone chasing this exact symptom is already looking, instead of only in Settings or the top-level burger menu.  rev77  (2026-08-11)  PROFILE-SWITCH TIMING + PROFILES OVERVIEW IMPROVEMENTS. (1) A profile switch that takes many seconds with 0% CPU showing is an I/O stall somewhere, not slow computation, and a plain 'refresh' button would not fix that - so switch_profile now breaks itself into named laps and logs any lap over 0.15s to Helpfiles/0---Empty/whybrowse_log.txt (SLOW STEP lines), plus a toast if the whole switch took over 3s. Next time it happens, the log names the exact step (engine build/cookie copy, bookmarks+history disk save, applying privacy, rebuilding the bookmarks bar, restoring tabs, etc.) instead of having to guess - worth checking whether the profile folders sit inside a cloud-synced folder (OneDrive/Dropbox) or get scanned by antivirus on every write, both classic causes of 'plenty of free RAM, 0% CPU, still slow'. (2) Profiles overview (DEL 41) now has a STICKY column legend (Pin/Refresh/Lock/Sleep/Awake) fixed at the very top of the window, outside the scroll area, so it never scrolls away no matter how many profiles you scroll past. (3) Each profile's own column header is now clickable: click 'Sleep' (or Pin/Refresh/Lock/Awake) on one profile's header row to set that flag ON for every tab in THAT profile at once, click again to clear it from all of them - no more ticking every row by hand to e.g. put a whole profile to sleep.  rev76  (2026-08-10)  RETURNING TO A SLEPT/AUTO-REFRESH TAB SHOWED NOTHING NEW UNTIL A MANUAL CTRL+R - two real bugs, both now fixed - + PER-SITE SCROLL SPEED. (1) WAKING A TAB NEVER ACTUALLY RELOADED IT: _wake_tab's normal path (used whenever setLifecycleState(Discarded) had succeeded) only flipped the page back to Active and ASSUMED becoming visible again would make Chromium reload it on its own - it never called reload() itself. Measured live: that assumption does not reliably hold in this QTabWidget/QStackedWidget setup, so a slept tab showed the exact same stale page with nothing forcing new content in, needing a manual Ctrl+R every time - and since on_tab_changed checks sleep BEFORE auto-refresh (if asleep: wake / elif auto-refresh: reload), a tab that had BOTH Auto-sleep and Auto-refresh on had its one refresh opportunity swallowed by the wake branch, which then did nothing either. _wake_tab now explicitly calls reload() itself after restoring Active - one harmless extra request if Chromium already reloaded on its own, the actual fix if it didn't. (2) AUTO-REFRESH SILENTLY SKIPPED ON PROFILE SWITCH: switch_profile detaches every tab then re-adds the target profile's tabs one by one; Qt sets currentIndex to 0 the instant the FIRST one is re-added, so by the time switch_profile calls setCurrentIndex(want_idx) to land on the actually-wanted tab, that index is very often ALREADY 0 - and Qt's currentChanged (which on_tab_changed listens on, the ONLY place the wake/auto-refresh check lives) does not fire when setCurrentIndex is given the value it already holds. switch_profile now calls on_tab_changed() directly whenever setCurrentIndex() turns out to have been a no-op, so a profile return gets exactly the same treatment as clicking a different tab by hand - still ONLY on return, never on a timer while you're sitting on the tab looking at it. (3) PER-SITE SCROLL SPEED: right-click a page -> Exceptions -> \"Scroll speed here\" gives ONE site its own mouse-wheel multiplier (Off/1.1/1.5/2.0/2.4/3.0/4.0/5.0x), stacked on TOP of the global Settings -> Performance scroll speed (e.g. global 1.3x times site 2.4x = 3.12x on that site only) and applying even when the global speed is left at native 1.0x. Stored per host in site_overrides[host][\"scroll_speed_mult\"]; read live by the existing wheel-event handler, no reload needed.  rev75  (2026-08-08)  CLICKING A LINK IN ANOTHER PROGRAM IS NO LONGER SLOW. Measured cause, from your own log: a link from F(re)email made Windows start a SECOND WhyBrowse, which loaded Qt and Chromium in full (and as the one-file .exe also unpacked ~200 MB into a temp folder) only to push the address down the local pipe to the window already on screen and quit - see 'Forwarded URL to running instance, exiting' at 07:11:14. All of that work happened before the forwarding code was even reached. The hand-off now runs FIRST, at the very top of the file, using nothing but the standard library (DEL 01b): if a WhyBrowse is already listening the URL goes straight in and the process exits in a few milliseconds, never importing Qt at all; if nobody answers we start up exactly as before. The running instance also writes the name of its pipe to Helpfiles/WhyBrowse/ipc.json (removed on close), so other programs no longer have to reproduce an md5 of the folder path to find it - F(re)email now opens mail links through that file with no process launched at all. Both sides must run at the same privilege level: a browser started as administrator will refuse a link from a program that was not (Windows integrity rules), and F(re)email says so plainly instead of failing quietly.  rev74  (2026-08-03)  BANDCAMP COVERS - fixed for real (the log settled it). YOUR log proved it: on a fresh load 'promoted=34', then 13 min later 'promoted=22 forced=0' - i.e. 22 covers had been RESET back to the /img/0.gif placeholder (it IS a src-revert; the earlier decode/bitmap theory was wrong). Bandcamp resets off-screen covers to a placeholder to save memory every time you scroll away or leave and return, and the old fixes only re-promoted for 20s then LOST. NEW APPROACH: each cover's real URL is remembered on the element (data-wb-real), and a permanent, cheap MutationObserver restores the real src the INSTANT Bandcamp flips one back to a placeholder - it reacts to src changes only, never loops, and is installed ONLY on pages that actually have lazy images (so Gmail/Vinted/etc. pay nothing). Verified live: after force-resetting 25 covers to the placeholder, all 25 were restored within 250ms automatically. rev73  (2026-08-03)  BANDCAMP COVERS - force RE-DECODE on return + measure. Honest status: I could not reproduce the background->foreground toggle in testing (the test tab is always hidden), so earlier fixes were partly guesses. MEASURED this round: after a promote, firing scroll/resize/visibility does NOT revert covers to the placeholder - so the failure is NOT a src-revert. The remaining cause is the OTHER kind: a backgrounded tab has its decoded image bitmaps dropped by Chromium while src + naturalWidth stay intact, so on return the covers look blank but nothing in the DOM shows it and a plain promote is a no-op. FIX: promote() now handles BOTH - (A) placeholder/stale src -> set real URL; (B) src already real but naturalWidth<2 -> bounce src to re-fetch; PLUS a new decodeAll() calls img.decode() on every real cover on load and on every tab-return (no re-download, no flash) to force a repaint of dropped bitmaps. The log now records 'eager-images: host=… promoted=P forced=F' so we can SEE which case fires on the real machine. rev72  (2026-08-03)  BANDCAMP COVERS SURVIVE TAB-SWITCH-AND-BACK. rev71 kept covers on a fresh load and after sleep, but they still went blank when you left the (still-live) tab and came straight back: Bandcamp RE-LAZIES its off-screen covers back to a placeholder when the tab is hidden then shown, and rev71's helper had already torn down after 20s. FIX: (1) LAZY_IMAGES_JS now installs a PERSISTENT visibilitychange + pageshow listener (once per page, never removed) that re-promotes and re-arms the short catch-up window every time the page becomes visible again; (2) WhyBrowse re-promotes on the Python side too whenever you switch TO a live tab (on_tab_changed), as a guaranteed backup. Verified live on issusbarn.bandcamp.com: after force-resetting 34 covers to the placeholder, the 600ms catch-up interval restored all 34 on its own within a second. rev71  (2026-08-03)  BANDCAMP COVERS AFTER SLEEP + self-sustaining lazy-loader. rev70 fixed the FIRST load (log confirmed 'promoted=34'), but covers vanished again ~10 min later. Cause: AUTO-SLEEP. An idle tab is discarded after ~5 min; when refocused Qt reloads it, but the _asleep bookkeeping flag could still be set when that reload's load-finished fired, so eager-images (and restore-scroll / find-word) early-returned and did nothing - silently, no log line. FIX (three layers): (1) a completed load now CLEARS a stale _asleep flag first thing, so wake-reloads reliably re-run the post-load steps; (2) LAZY_IMAGES_JS is now self-sustaining - after the immediate promote it installs a MutationObserver + 600ms interval + scroll handler (once per page, self-tears-down after 20s) so late/cold renders after a wake, infinite-scroll grids and re-lazied covers are all caught, not just what exists at load time; (3) verified live on issusbarn.bandcamp.com: 10 -> 44 real cover URLs, promoted=34. rev70  (2026-08-03)  BANDCAMP COVERS (real fix) + resilient on_load. The lazy-image promoter (eager_lazy_images, rev62) kept 'stopping' on issusbarn.bandcamp.com - only the first ~8 covers showed. ROOT CAUSE: on_load_finished ran ~10 post-load steps with NO per-step guard, and a silent exception in the login/autofill chain (which runs BEFORE eager-images) aborted the whole method, so eager-images never ran. Now every post-load step runs independently (each in its own try/except); a failing step is NAMED in the log (Helpfiles/0---Empty) instead of vanishing, and eager-images runs FIRST so nothing upstream can block it. _run_eager_images now logs 'eager-images: host=… promoted=N' when it promotes anything, to confirm it fired. This is durable across visits (unlike merely re-ordering one call). rev69  (2026-08-03)  LOCK LEVEL 3+ (right-click a tab -> Lock -> '3+'): browse freely WITHIN one domain (all of tradera.com, incl. www./m./shop. subdomains) in the SAME tab, and only a link to ANOTHER domain opens a new tab. It is stricter than Lock 3 (still ignores bookmark clicks + address bars, red X), just friendlier about same-site links. 3+ OVERRIDES PIN: on a tab that is both pinned and 3+, same-domain links still open in this tab and only other domains open a new tab (so a pinned home tab can be browsed within its own site). Setting it now shows a clear 'level 3+' toast, and every locked-tab navigation is written to the log (lines 'lock-nav:' / 'lock3+ nav:') so a 'stayed vs new tab' report can be settled from the log. rev68  (2026-08-02)  FEEDBACK. (1) REMOVED the Vinted pinned-search chips (\"Search Vinted for…\", DEL 21M): each chip ran a plain /catalog?search_text= with NO category filter, so it returned everything that matched the words, not just the board games wanted - useless for that purpose. Gone from Vinted pages, the page right-click menu, Help and the feature index; the settings key is dropped and any 'vinted_pins' left in a saved page_menu.json is self-healingly ignored (normalise_page_menu_layout only keeps ids the program still has). (2) SAVED WORDS / SNIPPETS now have their OWN toolbar button (📝, in the CP cluster). Click it and the menu shows the words for the ACTIVE PAGE and for ALL SITES right at the top - click one and it drops into the focused field (fallback to the page's search box, same as the right-click menu) - followed by 'Save a new word…' (this page / this profile / all sites) and 'Manage saved words…'. Same store as the page right-click menu, so both stay in step; 'This profile' words appear only when there are any, keeping the common case tidy. Help mode + the feature index know the new button. (3) The bulk-upload progress button (📤, just before CP) was double the width it needed - it only ever shows a short '📤 3/8' count while a run is live - so it was trimmed from 58 to 46 px to tighten the row. rev67  (2026-08-01)  THE TEMP TAB (DEL 44) + PER-BOOKMARK OPEN MODE. One tab set aside for pages you only want to LOOK at: opening something 'in temp' REUSES that tab instead of breeding a new one. It sits at the top of the strip under the pinned block, marked 🕒. THE RULE THAT MAKES IT SAFE: nothing lands there by itself - only a bookmark whose own default you set to Temp, the page menu's '🕒 Open link in the TEMP tab', the address bar's right-click, or a 'same tab' open that a LOCKED/pinned tab would otherwise have turned into yet another tab (the user's 'Locked override = in same → Temp'). Ordinary in-page links keep following the normal rules, so clicking item after item on Tradera/Vinted can never queue up in the temp tab overwriting itself - the exact worry this design answers. Settings ▸ The temp tab: on/off, how many temp tabs take turns (1-9, so the last N survive), keep-them-on-restart, and the locked→temp rule. A temp tab you PIN or LOCK is never reused (that is how you rescue one), or un-tick '🕒 Temp tab' in its right-click menu. OPEN MODE PER BOOKMARK: same / new / temp, chosen per bookmark (right-click it on the bar ▸ '⚙ A plain click on this one opens…') over a global default that now lives BOTH in Settings and on the address bar's right-click menu ('🔖 Bookmarks open, by default…'); the old per-item same_tab flag is read as 'same' so nothing changed for existing bookmarks. rev66  (2026-08-01)  THE PAGE RIGHT-CLICK MENU IS YOURS TO ARRANGE (DEL 43). That menu had grown to ~50 entries in a hardcoded order with no way to touch it. Now every entry has a stable id and is collected as an (id, builder) pair instead of being written straight into the QMenu, and a layout engine lays them out following YOUR saved arrangement: drag any row up or down, make your OWN sub-menus ('folders') and drag entries into them, add or remove separator lines, and park what you never use in a Hidden bin (nothing is ever deleted). Editor = right-click a page -> '⚙ Arrange this menu…' (bottom) or Settings -> 'The page right-click menu'; it reuses the bookmark tree's move-the-real-item drag-drop, plus ▲▼ / 'Move into…' for people who would rather not drag, a Preview, and Factory order. Three things keep it from ever breaking: entries that only apply sometimes (link actions with no link under the cursor, Vinted pins off Vinted, 'un-hide' with nothing hidden) are never collected at all, so they keep the place you gave them and the separators around them collapse automatically - no stray double lines, no empty sub-menus; an entry that exists in the program but is missing from your saved arrangement (i.e. added by a LATER version) is appended at the bottom instead of vanishing; and '⚙ Arrange this menu…' can be moved anywhere but never hidden, so the way back can't be lost. Saved as Helpfiles/WhyBrowse/page_menu.json. rev65  (2026-08-01)  VINTED PINNED SEARCHES (DEL 21M). Vinted's 'recent searches' list is newest-first, so a new search jumps to the top and pushes the ones you actually reuse (Las Vegas, Santiago, Bandu, ...) down and off the list - and Vinted has no way to pin one. WhyBrowse now draws its OWN small row of pinned-search chips directly UNDER Vinted's search field, always visible; click a chip to run that search (it opens /catalog?search_text=..., the plain Vinted search URL, so it never depends on Vinted's own dropdown scripting). Manage them from the page right-click menu -> '📌 Pinned searches...' (add / remove / reorder, Enter adds); changes apply to every open Vinted tab at once. Works on any Vinted country domain. Verified live against vinted.se: the row lands under the search field and the catalog search URL loads the right results. rev64  (2026-08-01)  AUCTION CLOCK ONLY IN THE LAST 3 MINUTES. The bottom-right auction panel now stays HIDDEN until the auction is inside its closing window (<= 180 s left) AND still running - '8 days left' and 'ended X ago' were irrelevant. It re-checks every tick, so it pops up on its own the moment the clock drops under 3 minutes and disappears once the auction is over. New setting auction_show_within_s (default 180; 0 = always show). A MANUAL Troubleshoot -> 'run auction clock here' still shows immediately whatever the time left (showWithin=0), so you can confirm it works. Closing the panel with its X keeps it closed for that page. rev63  (2026-08-01)  FEEDBACK FIXES. (1) TOO MANY NEW TABS: 'links open in a new tab by default' (DEL 42) is now OFF by default and force-flipped OFF once for existing users (marker links_newtab_off_v1) - an ordinary in-page link click (e.g. moving between pages inside PayPal) now STAYS in the same tab like a normal browser. SAVED links (bookmark bar / favourites) still open in a new tab via their own bar_open_new_tab setting, and target=_blank / window.open / a locked or pinned tab still open new tabs. Re-enable per link from its right-click menu if you ever want the old behaviour. (2) INERA ERROR PAGE THAT KEPT COMING BACK: Inera's login IdP redirects an expired session to idp...inera.se/_error?status=412 'No HTTP session'; that dead address was being saved as an open tab and reopened on every restart, multiplying across profiles. Such session-expired '_error' interstitials are now never saved into last_tabs, never restored on startup or profile-switch, and a one-shot cleanup (is_dead_restore_url / _scrub_dead_saved_tabs) strips any already stored in EVERY profile so they stop reappearing from the next launch. rev62  (2026-07-26)  FEEDBACK FIXES. (1) BANDCAMP-style covers that were blank past the first few now load: 'eager lazy images' promotes data-src/data-original placeholders to real images (verified: 8→39 covers on the user's page). Per-site toggle in page right-click → Exceptions; global setting eager_lazy_images. (2) PDF mouse-wheel works again on direct .pdf pages (the two-scrollbar catalogues): the custom scroll-speed no longer eats the wheel over the pdfium viewer. (3) LINKS OPEN IN A NEW TAB BY DEFAULT (DEL 42): right-click a link → '🆕 Open links in a NEW tab by default' + '↩ …except links to <domain> (same tab)'; a locked/pinned tab still forces a new tab (overrules 'same'). Honours open_link_default for stay-vs-go. (4) SNIPPETS: starred words now sit directly on the page menu as '📝 Insert: …' rows (as many as you star, no '+N more'); the submenu holds every word in folders with ⭐ marks. Comma-split box now defaults OFF and remembers your choice (so 'Lyrics by X, everything by Y' stays ONE snippet); added an ✎ Edit button to fix existing ones. rev61  (2026-07-25)  PROFILES OVERVIEW + BUG REPORTER + SMALL FIXES. (1) 📊 Profiles overview / stats (☰ menu, DEL 41): a dashboard of every live profile's tabs with one-click Pin / Auto-refresh / Lock / Auto-sleep / Keep-awake, plus per-tab memory & CPU and a running total (memory/CPU need the optional psutil package; hidden if absent). Works across background profiles too, since their tabs are kept alive. (2) 🐞 Report a bug / log this (Ctrl+Shift+D, DEL 40): the browser now keeps a rolling activity trail (which profile, which page, each load ok/fail, tab & profile switches); press the button while a page misbehaves (e.g. Tradera showing only a few ads and not scrolling), add a comment, and a report (.txt + .json, NO passwords/cookies) is saved to Helpfiles/WhyBrowse/bug_reports for later diagnosis. (3) Low-vision 🔎 button now asks to confirm before turning ON (re-flows every tab), with a Don't-ask-again box (re-enable in its right-click menu). (4) Saved words: ⭐ pin several favourites to the very top of the page right-click menu, above the This-site folder, with ▲▼ ordering. (5) Help window (and every styled dialog) now has a real draggable scrollbar thumb - styling a scroll area without styling QScrollBar had hidden the handle on Windows. rev60  (2026-07-19)  POP-UP KILLER FOR BOXES INSIDE THE PAGE (DEL 21L) - the Vinted advert after a shipping label, the subdl video box. This is what was actually wanted earlier and was NOT covered: the DEL 21I popup guard only stops a site opening new TABS, and no new-tab rule can touch a box drawn inside the page - which is why the feature could not be found. Right-click - Kill a pop-up box, click the offending box, then choose: REMOVE IT (never appears again on that site) or CLICK ITS OWN X FOR ME (still appears for a blink, but its close button is pressed, so the page runs its own tidy-up and anything depending on a proper close still works). Two things a plain element-hide got wrong and this fixes: an overlay is a full-screen BACKDROP with the box inside it and it LOCKS PAGE SCROLLING, so hiding only the box leaves a dark sheet over a page you cannot scroll - exactly the reported went-black-but-did-not-go-away behaviour; removing now takes the outermost full-screen overlay ancestor and unlocks scrolling with it. And these boxes appear long AFTER load, on an action, so rules are re-applied by a MutationObserver instead of once at load. QR SAFETY: if the picked description matches more than one element, removing is refused outright and only click-its-X is offered - a sloppy match would otherwise take the shipping-label QR with it, the same class of mistake that once hid an Amazon checkout QR. Verified in the engine against a Vinted-shaped page (QR modal + advert overlay + scroll lock): picker selects the overlay ROOT not the clicked text, finds the X, and in BOTH modes the advert goes, the QR stays visible and scrolling is restored. Every rule is listed in the same right-click menu with one-click undo, per rule or per site. rev59  (2026-07-19)  HELP MODE (DEL 21K) + A HELP AUDIT. Press F1 (or the ? button) and the browser explains itself: hover a toolbar button, menu entry, bookmark or field and a panel names what it is, where it lives and what it does, with More for the full text - which stays expanded as you move along so you can read down a row of buttons. Esc leaves. The panel never takes focus, so browsing keeps working. Nothing is written twice: it shows the controls own tooltip and looks up the matching FEATURE_INDEX entry, the same list Ctrl+Shift+F searches, so the two cannot drift apart.  THE AUDIT (asked: is Help updated with everything? answer was NO): 13 real gaps found and filled - profile 99, pin a tab, Tookmarks, Copymarks, quick links, scroll-position memory, crash recovery + message drafts, the bot-check report, engine update, default-browser registration, custom page size, and single-instance link forwarding. 75 entries -> 87.  Two matching bugs found by testing the lookup against the real tooltips rather than assuming: (1) plurals missed their entry - Blocked popups did not match popup guard, so a hovered control landed on an unrelated feature; (2) this and page are the commonest words in these tooltips AND appear in a dozen feature names, so on their own they decided the match. Stop-words fix that, but removing this then made the two address boxes collide, since THIS tab vs NEW tab is literally all that separates them - so the 22 toolbar controls are now mapped EXACTLY and fuzzy matching only covers what cannot be mapped (menus, bookmarks, dialogs). Every mapping is verified at build time to point at a widget that exists and a feature entry that exists. rev58  (2026-07-19)  BULK UPLOAD (DEL 21J) - for posting adverts on BoardGameGeek, where images go up one at a time. The clicking was never the real cost: the file dialog restarts from scratch every time, so the same folder has to be found and the next picture picked out of it, over and over. Right-click - Upload SEVERAL files here, pick every picture ONCE, and the file dialog never opens again - each time the page asks for a file the next one in the queue is handed over by the completely normal route, so the site cannot tell the difference. It also presses the sites own add-image control between files so a batch runs unattended. MEASURED, NOT ASSUMED: a scripted element.click() does NOT open the picker - the click event fires, the page sees it, and chooseFiles is never called, because Chromium demands real user input. A QMouseEvent posted to view.focusProxy() DOES drive it (the same focusProxy trap the find-bar hit). So JavaScript only scrolls the control into view and reports WHERE it is, and the click happens in Python, scaled by the tabs zoom factor. Tested end to end in this engine: 3 of 3 files sent automatically both with a visible file input AND with a hidden input behind a label. If no control can be found the queue waits for your click - you still never see the dialog. If the input takes several files the whole queue goes in one step. A 📤 3/8 button lists whats queued, sends the next now, skips one, changes the wait between files, or stops. The queue is tied to the site it started on (verified: another site cannot consume it) and is never saved to disk. rev57  (2026-07-19)  JUNK SITES + POPUP GUARD (DEL 21I) - for the subdl.com video box whose Close button opens a togglevpn.org advert tab. Chromium does not stop that, because a popup opened from a CLICK counts as user-requested. Two tools. (1) JUNK SITES: a listed address is refused everywhere and the tab CLOSES ITSELF if it existed only to show it; add one while standing on the junk page (right-click - Troubleshoot - Popups and junk sites - JUNK SITE) and it blocks plus closes in one go. Subdomain-aware (togglevpn.org covers ads.togglevpn.org) but verified NOT to match lookalikes: nottogglevpn.org and togglevpn.org.evil.com both stay allowed. (2) NO NEW TABS FROM THIS SITE: set on the site you are READING (subdl.com), so the junk tab is never created whatever address it would have used - the stronger rule, since it survives the advertiser changing domain. NO BLOCK IS SILENT: a 🚫 button appears in the toolbar with a per-tab count and lists WHERE each blocked popup wanted to go, offering open-it-anyway, junk-that-address, and allow-popups-here - so a page that genuinely needed the popup can be excepted instead of looking broken. That address is learned by handing Chromium a viewless probe page that records the destination and REFUSES it in the same breath, so the junk site never receives a single request (verified live). Both lists in one window off the 🚫 button; popups can also be blocked everywhere by default with per-site exceptions. rev56  (2026-07-19)  PROFILE 99 FAVOURITES - switch to it and your whole starred list IS the bookmarks bar, each link painted in the colour of the account it belongs to and each one still opening AS that account. Two logins on the same site sit side by side, labelled by account (the address alone cannot tell them apart). WHY IT LENDS LOGINS INSTEAD OF HOLDING THEM: a profile IS a cookie jar, and two accounts on one site cannot share a jar - tradera.com can only be logged in as one of them at a time - so a profile physically containing every account's logins is not possible; that is how logins work, not a shortcoming here. Profile 99 keeps no logins of its own and lends each link the jar it came from, which gives the thing actually wanted: one place with everything, each item signed in as the right account, several accounts of one site open at once in one window. Its bookmarks are GENERATED from favourites.json on every rebuild and never written to disk (right-clicking one edits the FAVOURITE, not a throwaway bookmark); a favourite saved as -whichever profile is active- falls back to the startup profile there rather than profile 99's own empty jar; a NEW address typed in profile 99 has no account to guess and so opens signed out. Toggle it in the profile menu - deleting it never touches your favourites. rev55  (2026-07-19)  FAVOURITES ARE NOW SOMEWHERE YOU CAN SEE THEM: starring a page put it in a list reachable ONLY from the burger menu, so it felt like nothing happened. There is now a **star Favourites (n)** button at the LEFT END OF THE BOOKMARKS BAR (right-click the bar to hide it), a full **Favourites window on Ctrl+Shift+B** - search, rename, reorder, change which login a link opens with, open a whole login group at once - and the confirmation toast now names where the link went. Your 3 existing favourites (Vinted + 2x Tradera) were saved correctly all along.  AUCTION CLOCK - the Tradera bid that bounced at \"8 seconds left\": a site countdown runs on YOUR clock, so it can be wrong invisibly (measured live here: this PC is ~0.95 s AHEAD of Traderas server, so every Tradera countdown flatters you by a second, before adding a 130 ms trip for the bid itself; a page restored from cache starts counting from an old \"now\"; a tick-based timer loses time whenever the renderer is busy). Auction pages now get their own panel bottom-right built from the auctions ABSOLUTE end time in the pages own data plus a measured offset to the AUCTION SITE'S OWN server clock (HEAD -> Date header, corrected for round-trip). It shows the true time left, **Bid before HH:MM:SS** (end minus your margin minus the measured ping), the end time it settled on spelled out, and a red warning naming how many seconds the pages own countdown is out. TESTED against two live Tradera auctions: the naive \"soonest end time on the page\" approach - which is what an obvious implementation does - picked a RELATED item and was 2 minutes and 3 hours wrong respectively, so the end time is tied to the item id in the address instead; both then matched exactly. Also found: Tradera displays only \"Slutar 19 jul 22:10\" when the auction really runs to 22:10:38. Margin 20 s, per-site on/off under right-click -> Troubleshoot -> Auction clock.  rev54  (2026-07-19)  TWO BUGS FOUND IN THE LOG OF YOUR OWN RUNS: (1) the new human-check helper FIRED ON ORDINARY SITES - it matched any page merely containing a captcha widget (an invisible reCAPTCHA sits in most login forms), so it silently switched the ad blocker and third-party-cookie blocking off for boardgamegeek.com and dancovershop.se. It now requires a real INTERSTITIAL (Cloudflare challenge container / unmistakable title / challenge wording) AND a nearly empty page, and whatever it does change can be undone in one click: Troubleshoot -> \"Restore normal blocking on N relaxed sites\" (use it to put those two sites back). (2) \"Chrome version fetch failed: HTTP Error 400\" on EVERY startup - the version API rejects the filter parameter that was being sent, which is why the cached version froze at 136 and made the user-agent lie in the first place. Fixed and verified live (latest stable = 151). Since a healthy QtWebEngine is normally ~11 majors behind Chrome, the honesty threshold moved 6 -> 20 so the everyday gap never restarts the lying.  rev53: ENGINE UPDATE FIXED: the pip button really did hang on \"Running...\" for ever - the worker thread reported back with QTimer.singleShot, which has no event loop to run on off the GUI thread, so the result never arrived. It now reports over a Qt signal (always delivered) and times out. The pip command is shown in a SELECTABLE field with a Copy button, and there is a \"Create updater (.bat)\" button that writes a double-clickable Update_engine.bat - the route that actually works, because Windows will not let pip replace the engine's DLLs while the running program has them open (which is why an in-app update usually failed anyway). Both duplicate pip runners (Settings + engine dialog) replaced by one shared panel.  rev52: USER-AGENT NOW TELLS THE TRUTH - the real cause of the predb.me loop: WhyBrowse rewrote the Chrome version in the user-agent to a value refreshed from Google at most once a month, so a stale 136 made a Chromium 140 engine advertise itself as Chrome 136 while still exposing every Chrome 140 API. Bot checks feature-detect the engine and compare; a version that does not match the feature set is a hard fail. It now reports the engine's REAL version and only claims a newer one when the engine is 6+ majors behind (the case the bump was added for). Plus: a user-agent field in Settings -> Privacy, and right-click -> Troubleshoot -> \"What this page sees about me\" (user agent, client hints, real engine version, can-set-cookie, WebGL, time zone) which names what looks wrong.  rev51: \"VERIFY YOU ARE HUMAN\": verification providers (Cloudflare Turnstile, hCaptcha, reCAPTCHA, Arkose, DataDome) are now exempt from the cookie filter, the ad blocker and the cosmetic scripts; navigator.userAgentData is kept in step with the spoofed user-agent string (they disagreed, which alone flags you as a bot); and the first time a site shows a human-check wall, the blocking features are turned off FOR THAT SITE and the page reloads once (Settings -> Privacy, or right-click -> Troubleshoot -> \"Stuck on Verify you are human\").  FALSE \"didn't load\" POP-UP FIXED: Chromium reports load-failure for superseded navigations and aborted sub-resources, so the panel appeared over pages that rendered a moment later - it now waits 1.2s, checks the load is still the current one, and asks the page whether it actually has any content before saying anything.  rev50: PER-SITE UPLOAD FOLDERS: picking a file to upload now starts in the folder YOU set for that site (Chromium always reused the last folder used anywhere - why a site with files on B: kept opening on C:), with a favourites quick-pick pop-up, Browse..., and 'make this the site's folder'. Downloads unchanged (still one folder). Esc now closes Google Sheets' own find box.  rev49: Favourites remember WHICH LOGIN each link opens with (a favourite bound to another profile/container opens as that account WITHOUT switching profile - so several Gmail accounts sit in one window); same URL can be starred once per login; ⭐ menu groups favourites by login + 'Add using login…' picker.  Pin is now strictly PER TAB (no more auto-unpin; a pinned tab sends different-document navigation to a NEW tab so it never drifts - fixes Vinted).  paymentSafe cosmetic check is host+path (PAYMENT_PATH_HOSTS, e.g. sellpy.se/checkout) and reads one source of truth from Python.  rev48: IMDb trailers play (IMDb exempted from the network ad-blocker + freeze-script, since blocking amazon-adsystem/demdex made its player error out).  rev47: CONTAINER TABS - several accounts of the same site (e.g. 2 Gmail / 2 ChatGPT) open at once in ONE window with separate logins, no profile switching (right-click a tab -> Containers); default-browser links open in the ALREADY-RUNNING WhyBrowse (new tab, profile 1) via a local pipe; global Favourites shared by all profiles; top saved word sits directly on the page right-click menu; StartMenuInternet registration for Windows Default apps"

APP_HISTORY   = _HISTORY_LATEST + _HISTORY_OLDER


def version_history_text():
    """APP_HISTORY split into one paragraph per rev, so it can be READ.

    The log is one run-on line. An entry starts with 'revNN' followed by either
    a date in brackets or a colon (both spellings are in there), and it always
    begins a new sentence - so the break is: end of sentence, then revNN, then
    '(' or ':'. That last condition is what keeps a mid-sentence mention like
    'the promoter (eager_lazy_images, rev62) kept stopping' from being torn out
    into a heading of its own.

    rev91: the space between two entries is now OPTIONAL. The old \\s+ demanded
    one, and the entries in _HISTORY_LATEST are separate string literals that
    are concatenated with nothing between them - so the text really reads
    '...normally does.0021-rev90  (...' with no gap at all. Every entry added
    since rev82 therefore failed to start a paragraph, and the whole of
    rev85..rev91 came out as ONE wall of text at the top of the history box -
    exactly the unreadability rev81 split this up to cure. The older text
    (rev84 downwards) does have the spaces, which is why it looked fine."""
    try:
        parts = re.split(r"(?<=[.!?])\s*(?=(?:\d{4}-)?rev\d+\b\s*[:(])", APP_HISTORY)
        return "\n\n".join(p.strip() for p in parts if p.strip())
    except Exception:
        return APP_HISTORY

DEFAULT_HOME  = "https://www.google.com"
SEARCH_URL    = "https://www.google.com/search?q={}"   # {} = url-encoded query

SEARCH_ENGINES = [
    ("Google",        "https://www.google.com/search?q={}"),
    ("Bing",          "https://www.bing.com/search?q={}"),
    ("DuckDuckGo",    "https://duckduckgo.com/?q={}"),
    ("Yahoo",         "https://search.yahoo.com/search?p={}"),
    ("Brave",         "https://search.brave.com/search?q={}"),
    ("Ecosia",        "https://www.ecosia.org/search?q={}"),
    ("Startpage",     "https://www.startpage.com/search?q={}"),
    ("Kagi",          "https://kagi.com/search?q={}"),
    ("Perplexity",    "https://www.perplexity.ai/search?q={}"),
    ("Yandex",        "https://yandex.com/search/?text={}"),
    ("Baidu",         "https://www.baidu.com/s?wd={}"),
    ("Wikipedia (EN)","https://en.wikipedia.org/w/index.php?search={}"),
    ("Wikipedia (SV)","https://sv.wikipedia.org/w/index.php?search={}"),
]

# ---- Theme colors (defaults = dark). Editable in Settings > Appearance. ----
# These module-level names are read when building every stylesheet, so the
# active theme is applied simply by overwriting them (see apply_theme_dict).
# Each one is written out plainly so it is trivial to change by hand too.
C_BAR_BG      = "#202637"     # toolbar / tab strip / status bar background
C_BAR_FG      = "#e8edf6"     # toolbar text
C_BTN_BG      = "#2b344b"     # navigation button background
C_BTN_BG_HOV  = "#39456a"     # navigation button hover
C_BTN_FG      = "#e8edf6"     # navigation button text
C_ADDR_BG     = "#11151f"     # address bar background
C_ADDR_FG     = "#ffffff"     # address bar text
C_ACCENT      = "#39c6da"     # accent (teal, matches the icon)
C_ACCENT_FG   = "#0c1018"     # text on accent
C_ACCENT_HOV  = "#5ad6e8"     # accent button hover
C_TAB_BG      = "#1a1f2e"     # unselected tab background
C_TAB_SEL     = "#2b344b"     # selected tab background
C_TAB_FG      = "#c5cee0"     # unselected tab text
C_TAB_FG_SEL  = "#ffffff"     # selected tab text
C_BORDER      = "#39456a"     # input borders
C_STATUS_FG   = "#9aa6bf"     # status bar text
C_NEWTAB_BG   = "#11151f"     # blank new-tab page background
C_NEWTAB_FG   = "#e8edf6"     # blank new-tab page text
C_TOAST_BG    = "#1f8a4c"     # success toast background (green)
C_TOAST_FG    = "#ffffff"     # success toast text

# Names that make up a swappable theme (toast colors stay fixed)
THEME_KEYS = [
    "C_BAR_BG", "C_BAR_FG", "C_BTN_BG", "C_BTN_BG_HOV", "C_BTN_FG",
    "C_ADDR_BG", "C_ADDR_FG", "C_ACCENT", "C_ACCENT_FG", "C_ACCENT_HOV",
    "C_TAB_BG", "C_TAB_SEL", "C_TAB_FG", "C_TAB_FG_SEL", "C_BORDER",
    "C_STATUS_FG", "C_NEWTAB_BG", "C_NEWTAB_FG",
]

THEME_PRESETS = {
    "Dark": {
        "C_BAR_BG": "#202637", "C_BAR_FG": "#e8edf6", "C_BTN_BG": "#2b344b",
        "C_BTN_BG_HOV": "#39456a", "C_BTN_FG": "#e8edf6", "C_ADDR_BG": "#11151f",
        "C_ADDR_FG": "#ffffff", "C_ACCENT": "#39c6da", "C_ACCENT_FG": "#0c1018",
        "C_ACCENT_HOV": "#5ad6e8", "C_TAB_BG": "#1a1f2e", "C_TAB_SEL": "#2b344b",
        "C_TAB_FG": "#c5cee0", "C_TAB_FG_SEL": "#ffffff", "C_BORDER": "#39456a",
        "C_STATUS_FG": "#9aa6bf", "C_NEWTAB_BG": "#11151f", "C_NEWTAB_FG": "#e8edf6",
    },
    "Light": {
        "C_BAR_BG": "#e9ebf0", "C_BAR_FG": "#1a1d24", "C_BTN_BG": "#d8dce6",
        "C_BTN_BG_HOV": "#c4cad8", "C_BTN_FG": "#1a1d24", "C_ADDR_BG": "#ffffff",
        "C_ADDR_FG": "#11151f", "C_ACCENT": "#1796a8", "C_ACCENT_FG": "#ffffff",
        "C_ACCENT_HOV": "#20b3c7", "C_TAB_BG": "#dfe3ec", "C_TAB_SEL": "#ffffff",
        "C_TAB_FG": "#41485a", "C_TAB_FG_SEL": "#11151f", "C_BORDER": "#b8c0d0",
        "C_STATUS_FG": "#5a6478", "C_NEWTAB_BG": "#f6f7fb", "C_NEWTAB_FG": "#222831",
    },
    "White": {
        "C_BAR_BG": "#ffffff", "C_BAR_FG": "#1a1a1a", "C_BTN_BG": "#f0f0f3",
        "C_BTN_BG_HOV": "#e2e2ea", "C_BTN_FG": "#1a1a1a", "C_ADDR_BG": "#ffffff",
        "C_ADDR_FG": "#000000", "C_ACCENT": "#1796a8", "C_ACCENT_FG": "#ffffff",
        "C_ACCENT_HOV": "#20b3c7", "C_TAB_BG": "#f2f2f5", "C_TAB_SEL": "#ffffff",
        "C_TAB_FG": "#555555", "C_TAB_FG_SEL": "#000000", "C_BORDER": "#cccccc",
        "C_STATUS_FG": "#666666", "C_NEWTAB_BG": "#ffffff", "C_NEWTAB_FG": "#222222",
    },
}


def current_theme():
    """Snapshot the active theme colors as a dict."""
    return {k: globals()[k] for k in THEME_KEYS}


def apply_theme_dict(theme):
    """Overwrite the module-level color names from a theme dict."""
    if isinstance(theme, dict):
        for k, v in theme.items():
            if k in THEME_KEYS and isinstance(v, str) and v:
                globals()[k] = v


def scrollbar_qss(handle=None, handle_hover=None):
    """A visible, draggable scrollbar style.

    NOTE: the moment you set ANY stylesheet on a QAbstractScrollArea
    (QTextBrowser / QListWidget / QTreeWidget / QScrollArea), Qt stops
    drawing the *native* scrollbar handle on Windows -- you get the groove
    but no thumb to grab. So every styled scroll area must also style
    QScrollBar, which is exactly what this returns. Reuse it everywhere."""
    hnd = handle or shade(C_ADDR_BG, 55)
    hnh = handle_hover or C_ACCENT
    return (
        "QScrollBar:vertical{background:transparent;width:14px;margin:0;}"
        "QScrollBar::handle:vertical{background:%(h)s;min-height:34px;"
        "border-radius:5px;border:3px solid transparent;background-clip:padding;}"
        "QScrollBar::handle:vertical:hover{background:%(hh)s;}"
        "QScrollBar::add-line:vertical,QScrollBar::sub-line:vertical{height:0;}"
        "QScrollBar::add-page:vertical,QScrollBar::sub-page:vertical{background:transparent;}"
        "QScrollBar:horizontal{background:transparent;height:14px;margin:0;}"
        "QScrollBar::handle:horizontal{background:%(h)s;min-width:34px;"
        "border-radius:5px;border:3px solid transparent;background-clip:padding;}"
        "QScrollBar::handle:horizontal:hover{background:%(hh)s;}"
        "QScrollBar::add-line:horizontal,QScrollBar::sub-line:horizontal{width:0;}"
        "QScrollBar::add-page:horizontal,QScrollBar::sub-page:horizontal{background:transparent;}"
        % {"h": hnd, "hh": hnh})


class WheelGuard(QObject):
    """The mouse wheel scrolls the PAGE - it never changes the control the
    pointer happens to be passing over.

    Qt's drop-downs, number boxes and sliders all answer the wheel by changing
    their VALUE. On a long settings page that means scrolling from top to
    bottom silently rewrites every combo box the pointer crosses on the way -
    reported as "I keep changing settings by accident when I scroll". The fix
    is not to make the controls ignore the wheel (then scrolling would simply
    stop dead over them), but to redirect that wheel event to the scroll area's
    own scrollbar, which is where the user was aiming in the first place.

    Deliberately unconditional: it applies even when the control has keyboard
    focus, because "the wheel never edits anything" is a rule that is worth
    something only if there are no exceptions to remember. The value is still
    changed by clicking, typing, or the arrow keys.
    """

    def __init__(self, scroll_area):
        super().__init__(scroll_area)
        self.area = scroll_area

    def eventFilter(self, obj, ev):
        try:
            if ev.type() == QEvent.Type.Wheel:
                bar = self.area.verticalScrollBar()
                if bar is not None:
                    QApplication.sendEvent(bar, ev)
                return True                     # never reaches the control
        except Exception:
            pass
        return False

    def protect(self, root, types=None):
        """Install on every value-carrying control inside `root`."""
        types = types or (QComboBox, QSpinBox, QSlider)
        for kind in types:
            for w in root.findChildren(kind):
                w.installEventFilter(self)
        return self


def dialog_qss():
    """Stylesheet for pop-up dialogs, built from the ACTIVE theme so they follow
    Dark / Light / White instead of being hardcoded dark. Child widgets inherit
    it; a dialog can still override specific widgets after setting this."""
    return scrollbar_qss() + (
        "QDialog{background:%(bg)s;color:%(fg)s;}"
        "QLabel{color:%(fg)s;background:transparent;}"
        "QCheckBox{color:%(fg)s;}QRadioButton{color:%(fg)s;}QGroupBox{color:%(fg)s;}"
        "QLineEdit,QPlainTextEdit,QTextEdit,QSpinBox,QComboBox{background:%(in)s;color:%(infg)s;"
        "border:1px solid %(bd)s;border-radius:6px;padding:5px;}"
        "QListWidget,QTreeWidget,QTextBrowser{background:%(in)s;color:%(infg)s;"
        "border:1px solid %(bd)s;border-radius:6px;}"
        "QListWidget::item,QTreeWidget::item{padding:4px;}"
        "QListWidget::item:selected,QTreeWidget::item:selected{background:%(acc)s;color:%(accfg)s;}"
        "QComboBox QAbstractItemView{background:%(in)s;color:%(infg)s;"
        "selection-background-color:%(acc)s;selection-color:%(accfg)s;}"
        "QScrollArea{border:none;background:%(bg)s;}"
        "QPushButton{background:%(btn)s;color:%(btnfg)s;border:none;padding:6px 14px;border-radius:6px;}"
        "QPushButton:hover{background:%(hov)s;}"
        % {"bg": C_BAR_BG, "fg": C_BAR_FG, "in": C_ADDR_BG, "infg": C_ADDR_FG,
           "bd": C_BORDER, "acc": C_ACCENT, "accfg": C_ACCENT_FG,
           "btn": C_BTN_BG, "btnfg": C_BTN_FG, "hov": C_BTN_BG_HOV})


def wrap_text_to_px(text, fm, room):
    """Break a one-line label into lines that each fit `room` pixels."""
    lines, cur = [], ""
    for word in (text or "").split(" "):
        trial = word if not cur else cur + " " + word
        if fm.horizontalAdvance(trial) <= room or not cur:
            cur = trial
        else:
            lines.append(cur)
            cur = word
    if cur:
        lines.append(cur)
    return "\n".join(lines)


def wrap_wide_controls(root, max_px=560):
    """Stop a settings page from demanding a screen-and-a-half of width.

    A QCheckBox cannot word-wrap: its minimumSizeHint is the FULL one-line
    width of its label, and QScrollArea(widgetResizable=True) honours that.
    So a single long checkbox label made the whole Settings body 2330 px
    wide (measured), which put a horizontal scrollbar under everything and
    meant the window had to be dragged out far wider than the screen before
    a row could be read.

    Qt DOES honour explicit newlines in a checkbox label, so break those by
    hand. Plain QLabels get real word-wrap instead, so they still reflow
    when the window is made bigger."""
    for w in root.findChildren(QWidget):
        try:
            if isinstance(w, QCheckBox):
                t = w.text()
                if not t or "\n" in t:
                    continue
                fm = w.fontMetrics()
                # the indicator and its spacing sit outside the label (~26 px)
                room = max(220, max_px - 26)
                if fm.horizontalAdvance(t) > room:
                    w.setText(wrap_text_to_px(t, fm, room))
            elif isinstance(w, QComboBox):
                # A combo asks for the width of its LONGEST ITEM. The popup
                # still shows every entry in full, so let the closed box be
                # narrow instead of stretching the whole page.
                w.setSizeAdjustPolicy(
                    QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon)
                w.setMinimumContentsLength(14)
            elif isinstance(w, QPushButton):
                t = w.text()
                room = max(160, max_px // 2 - 20)
                if t and chr(10) not in t and \
                        w.fontMetrics().horizontalAdvance(t) > room:
                    w.setText(wrap_text_to_px(t, w.fontMetrics(), room))
            elif isinstance(w, QLabel) and not w.wordWrap():
                if w.minimumSizeHint().width() > max_px:
                    w.setWordWrap(True)
        except Exception:
            pass
    lay = root.layout()
    if lay is not None:
        lay.activate()
        fit_wide_rows(lay, max_px)


def fit_wide_rows(lay, max_px, depth=0):
    """Second pass for wrap_wide_controls: a ROW can still be too wide when
    every control in it is fine on its own -- a wrapped checkbox sitting next
    to a button, a label next to a combo. Shrink the widest wrappable control
    in the row until the row fits, then move on."""
    if depth > 3:
        return
    for i in range(lay.count()):
        item = lay.itemAt(i)
        row = item.layout()
        if row is None:
            continue
        if not isinstance(row, QHBoxLayout):
            fit_wide_rows(row, max_px, depth + 1)
            continue
        for _ in range(6):
            over = row.minimumSize().width() - max_px
            if over <= 0:
                break
            widest, ww = None, 0
            for j in range(row.count()):
                cw = row.itemAt(j).widget()
                if isinstance(cw, (QCheckBox, QPushButton, QLabel)):
                    cwidth = cw.minimumSizeHint().width()
                    if cwidth > ww:
                        widest, ww = cw, cwidth
            if widest is None or ww <= 180:
                break
            try:
                if isinstance(widest, QLabel):
                    if widest.wordWrap():
                        break          # already as narrow as it can get
                    widest.setWordWrap(True)
                else:
                    pad = 26 if isinstance(widest, QCheckBox) else 24
                    room = max(120, ww - over - 10 - pad)
                    flat = " ".join(widest.text().split())
                    widest.setText(wrap_text_to_px(
                        flat, widest.fontMetrics(), room))
            except Exception:
                break
            row.activate()


def dim_fg():
    """A muted secondary text colour for the current theme (hints, captions)."""
    return C_STATUS_FG


def contrast_fg(hexcol):
    """Return black or white, whichever reads better on the given color."""
    try:
        h = hexcol.lstrip("#")
        r, g, b = int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)
        return "#000000" if (0.299 * r + 0.587 * g + 0.114 * b) > 150 else "#ffffff"
    except Exception:
        return "#ffffff"


def shade(hexcol, delta):
    """Lighten (delta>0) or darken (delta<0) a hex color by an amount 0..255."""
    try:
        h = hexcol.lstrip("#")
        rgb = [max(0, min(255, int(h[i:i+2], 16) + delta)) for i in (0, 2, 4)]
        return "#%02x%02x%02x" % tuple(rgb)
    except Exception:
        return hexcol


def blend(c1, c2, t=0.5):
    """Mix two hex colours: t=0 is c1, t=1 is c2. Used for a "dimmed" text
    colour that works in a light theme as well as a dark one - shade() alone
    cannot, because darkening a dark theme's text makes it BLACKER, not
    fainter. Fading towards the button's own background always reads as off."""
    try:
        a, b = c1.lstrip("#"), c2.lstrip("#")
        out = []
        for i in (0, 2, 4):
            x, y = int(a[i:i+2], 16), int(b[i:i+2], 16)
            out.append(max(0, min(255, int(round(x + (y - x) * t)))))
        return "#%02x%02x%02x" % tuple(out)
    except Exception:
        return c1

# ---- Donation / contact links (the user's real links) ----
REVOLUT_URL   = "https://revolut.me/lars72oeh"
PAYPAL_URL    = "https://paypal.me/issusbarn"
WISE_URL      = "https://wise.com/pay/me/larsdenniso"


# ============================================================================
#  DEL 03 - PATHS  (always relative to the program; works as .py and as .exe)
#  Helpfiles/                  -> root for all helper files
#  Helpfiles/WhyBrowse/           -> settings, bookmarks, history, browser profile
#  Helpfiles/0---Empty/        -> logs only
# ============================================================================
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__)))


PROGRAM_HOME_AWARE = True   # Tower checks for this before offering the swap


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

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

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


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

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


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


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


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

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


_HUB_PY_ROOTS = None


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

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

    So a RELATIVE entry ("1---Musik\\Py") is the intended shape: it is
    resolved against every root in _py_folders, and it survives the move too.
    An absolute one is still honoured - it is his tree - but it is on him."""
    global _HUB_PY_ROOTS
    if _HUB_PY_ROOTS is not None:
        return _HUB_PY_ROOTS
    found = []
    for root in _my_app_roots():
        f = os.path.join(root, "Helpfiles", "DefaultHub", "defaults.json")
        try:
            if os.path.isfile(f):
                with open(f, encoding="utf-8") as fh:
                    found = (json.load(fh) or {}).get("py_roots") or []
                break
        except Exception:
            pass                       # unreadable or half-written: automatic
    try:
        _HUB_PY_ROOTS = [str(x).strip() for x in found if str(x).strip()]
    except Exception:
        _HUB_PY_ROOTS = []
    return _HUB_PY_ROOTS


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

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


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

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


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

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

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

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

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


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


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




def app_base_dir():
    r"""Directory the program keeps its data in, as .py and as frozen .exe.

    A one-folder build lives in the build directory
    (B:\0---Burn\0---Util\0---Mina_program\WhyBrowse\WhyBrowse.exe). Taking
    the base from sys.executable there means bookmarks, history, profiles and
    the vault are looked for beside the .exe, found missing, and written fresh
    on the build drive - the browser starts as if it had never been used.
    So a frozen build uses PROGRAM_HOME whenever that folder really holds this
    program's data, and only falls back to the .exe's folder when it does not
    (a genuinely portable copy on another machine).

    Running the .py is deliberately left alone: it follows the script, which is
    what keeps a copy under test from reading - or writing - his live data.
    """
    return _program_home()


BASE_DIR    = app_base_dir()

# ---- Travel copy: are we running out of an encrypted .wbtrav file? ----------
#
# See DEL 07D for the whole story. Short version: a travel copy is ONE
# encrypted file next to the .py, for use on a computer that is not yours. When
# one is present, DATA_DIR is redirected to a temporary folder that is deleted
# when the browser closes — which in one move redirects the Chromium profile,
# the cookies, the cache, the history and the log with it.
#
# That redirection is the entire security model, and it is not cosmetic:
# QtWebEngine stores its cookies as PLAINTEXT in profile/Cookies (there is no
# encrypted_value in that table), so a password box in front of the window
# would protect nothing at all. What is not carried cannot be read.
_TRAVEL_SUFFIX     = ".wbtrav"
_TRAVEL_TMP_PREFIX = "WhyBrowse_travel_"


def _find_travel_pack():
    """Path of the travel file to run from, or '' for an ordinary install."""
    import glob as _glob
    for folder in (BASE_DIR,
                   os.path.join(BASE_DIR, "Helpfiles", APP_NAME)):
        try:
            hits = sorted(_glob.glob(os.path.join(folder, "*" + _TRAVEL_SUFFIX)))
        except Exception:
            continue
        if hits:
            return hits[0]
    return ""


def _sweep_old_travel_dirs():
    """Delete working folders left by a travel session that crashed. They hold
    only our own temporary data, and one forgotten in %TEMP% on someone else's
    machine is exactly what a travel copy exists to prevent."""
    import shutil as _sh
    import tempfile as _tf
    try:
        root = _tf.gettempdir()
        for name in os.listdir(root):
            if name.startswith(_TRAVEL_TMP_PREFIX):
                _sh.rmtree(os.path.join(root, name), ignore_errors=True)
    except Exception:
        pass


_TRAVEL_PACK = _find_travel_pack()
_TRAVEL_MODE = bool(_TRAVEL_PACK)
_TRAVEL_DIR  = ""
if _TRAVEL_MODE:
    import tempfile as _tf_boot
    _sweep_old_travel_dirs()
    _TRAVEL_DIR = _tf_boot.mkdtemp(prefix=_TRAVEL_TMP_PREFIX)

HELP_DIR    = os.path.join(BASE_DIR, "Helpfiles")
DATA_DIR    = _TRAVEL_DIR if _TRAVEL_MODE else os.path.join(HELP_DIR, APP_NAME)
LOG_DIR     = os.path.join(_TRAVEL_DIR, "log") if _TRAVEL_MODE \
    else os.path.join(HELP_DIR, "0---Empty")
PROFILE_DIR = os.path.join(DATA_DIR, "profile")
CACHE_DIR   = os.path.join(DATA_DIR, "cache")

SETTINGS_FILE  = os.path.join(DATA_DIR, "settings.json")
BOOKMARKS_FILE = os.path.join(DATA_DIR, "bookmarks.json")
HISTORY_FILE   = os.path.join(DATA_DIR, "history.json")
NEWTAB_FILE    = os.path.join(DATA_DIR, "newtab.html")
WATCH_CACHE_FILE = os.path.join(DATA_DIR, "watch_cache.json")   # Update-Scanner page text
SCROLL_POS_FILE  = os.path.join(DATA_DIR, "scroll_positions.json") # "remember scroll position" opt-in sites
FORM_MEMORY_FILE = os.path.join(DATA_DIR, "form_memory.json")   # remembered form fields per host
DRAFTS_FILE      = os.path.join(DATA_DIR, "message_drafts.json") # live-saved message drafts (7-day)
PAGE_MENU_FILE   = os.path.join(DATA_DIR, "page_menu.json")     # YOUR arrangement of the page right-click menu (DEL 43)
# Written while we are running, deleted when we close: the name of the local
# pipe other programs can push a link into (see DEL 01b and _publish_ipc_file).
# Its whole purpose is that a caller never has to GUESS the name.
IPC_FILE         = os.path.join(DATA_DIR, "ipc.json")
USERSCRIPTS_DIR  = os.path.join(DATA_DIR, "userscripts")        # user add-ons (.js/.css)
KBD_LAYOUTS_DIR  = os.path.join(DATA_DIR, "keyboard_layouts")   # extra on-screen-keyboard layouts (.json)
MEDIA_TOOLS_DIR  = os.path.join(DATA_DIR, "tools")             # yt-dlp.exe / ffmpeg live here
BUGREPORT_DIR    = os.path.join(DATA_DIR, "bug_reports")       # saved bug reports (DEL 40)
# ---- Torrents / magnet links (DEL 49) ----
# The LIST of torrents (so an unfinished one survives a restart) and a copy of
# each torrent's own description, which is what makes a resume instant instead
# of "find someone who can tell me what this magnet even is" all over again.
# The downloaded FILES never live here - they go to your torrent folder.
TORRENTS_FILE    = os.path.join(DATA_DIR, "torrents.json")
TORRENT_META_DIR = os.path.join(DATA_DIR, "torrent_meta")
LOG_FILE       = os.path.join(LOG_DIR, "whybrowse_log.txt")
# Shared with File_manager ON PURPOSE (same file, same folder): the used
# Backup<CODE> letters per filename. "Back up the old one" on a download
# (DEL 46) draws from the same pool as File_manager's Backup-rename, so
# backing up WhyBrowse.py from either program can never produce two files
# with the same Backup<CODE>-WhyBrowse.py name.
BACKUP_CODES_FILE = os.path.join(HELP_DIR, "redigerare", "backup_codes.json")

# ---- Multi-profile storage ----
PROFILES_DIR        = os.path.join(DATA_DIR, "profiles")          # per-profile dirs
SHARED_BOOKMARKS    = os.path.join(DATA_DIR, "bookmarks_shared.json")
# ---- Favourites: ONE global collection, shared by EVERY profile ----
#  Unlike per-profile bookmarks, this file lives in DATA_DIR (not inside any
#  profile folder), so a favourite you add from ANY profile shows up in ALL
#  profiles. Right-click a bookmark (or a page) -> "Add to Favourites" copies
#  it here; open them from  ☰ menu -> ⭐ Favourites.
FAVOURITES_FILE     = os.path.join(DATA_DIR, "favourites.json")
# The auto-built "Favourites" profile (badge 99). It is a VIEW of the starred
# list, not a place logins are stored - see DEL 21H for why that distinction
# matters and how each link still opens with its own account.
FAV_PROFILE_ID      = "favourites"

for _d in (HELP_DIR, DATA_DIR, LOG_DIR, PROFILE_DIR, CACHE_DIR, PROFILES_DIR,
           KBD_LAYOUTS_DIR, MEDIA_TOOLS_DIR, BUGREPORT_DIR):
    try:
        os.makedirs(_d, exist_ok=True)
    except Exception:
        pass

# Set once in main() from check_single_instance(), BEFORE Browser() is built.
# True when another WhyBrowse process already holds this same Helpfiles
# folder (e.g. an older build you kept open). See profile_paths() below.
IS_SECONDARY_INSTANCE = False


def profile_paths(pid, force_primary=False):
    """Storage paths for a profile id. The 'default' profile reuses the
    original folders so existing cookies/logins/bookmarks are never lost.

    If ANOTHER WhyBrowse instance already has this same Helpfiles folder
    open (IS_SECONDARY_INSTANCE), THIS instance's Chromium 'storage'/'cache'
    are redirected to separate '..._secondary' folders instead - two live
    Chromium engines must never point at the same on-disk cookie database at
    once, or logins get corrupted/lost. Bookmarks and history stay shared
    (plain JSON files we read/write ourselves, never locked by Chromium, so
    sharing them is safe). See Browser._snapshot_all_cookie_stores() /
    _replay_cookie_snapshot() for how a secondary instance still inherits
    the primary's current logins despite the separate storage folder.

    Pass force_primary=True to always get the PRIMARY paths regardless of
    IS_SECONDARY_INSTANCE (used for the shared cookie hand-off file, which
    always lives in the primary's folder so it's easy to find from either
    side)."""
    secondary = IS_SECONDARY_INSTANCE and not force_primary
    if pid == "default":
        return {
            "storage":   os.path.join(DATA_DIR, "profile_secondary") if secondary else PROFILE_DIR,
            "cache":     os.path.join(DATA_DIR, "cache_secondary") if secondary else CACHE_DIR,
            "bookmarks": BOOKMARKS_FILE,
            "history":   HISTORY_FILE,
        }
    base = os.path.join(PROFILES_DIR, pid)
    return {
        "storage":   os.path.join(base, "profile_secondary" if secondary else "profile"),
        "cache":     os.path.join(base, "cache_secondary" if secondary else "cache"),
        "bookmarks": os.path.join(base, "bookmarks.json"),
        "history":   os.path.join(base, "history.json"),
    }


# ============================================================================
#  DEL 04 - CRASH CATCHER AND DIAGNOSTICS
# ============================================================================
def log_line(text):
    """Append a timestamped line to the log file (never raises)."""
    try:
        stamp = time.strftime("%Y-%m-%d %H:%M:%S")
        with open(LOG_FILE, "a", encoding="utf-8") as f:
            f.write("[{}] {}\n".format(stamp, text))
    except Exception:
        pass


# *************** DEL 56 - CRASH LOOP BREAKER ("the BGG geekmail loop") *****************
# ToDo (2026-11-15): boardgamegeek.com crashed its renderer (exit 0x80000003, a Chromium
# breakpoint) ~1.5 s after every load, and the old handler reloaded the tab after every
# crash - forever. This is the pure decision part (no Qt, so it can be tested alone):
#   crash 1 inside 30 s  -> "reload"  (one crash is often a fluke)
#   crash 2              -> "cache"   (clear the HTTP cache, then reload. FOUND 2026-11-15: a copy
#                                      of the issusbarn profile crashed boardgamegeek.com with a
#                                      plain engine, no WhyBrowse code at all; deleting the cache
#                                      folder - or clearHttpCache() on the live profile - cured it)
#   crash 3              -> "safe"    (reload with EVERYTHING WhyBrowse adds to that site
#                                      switched off: injected scripts, post-load JS,
#                                      header rewriting, scroll capture)
#   crash 4              -> "reload"
#   crash 5              -> "giveup"  (stop reloading, show an error page, offer the system browser)
#   a crash within 10 min after a give-up -> "quiet" (no reload at all)
# Safe mode doubles as a bisect: if the page then stays up, WhyBrowse's own additions are the
# cause (log line "crash-ladder: ... HELD"); if it still crashes, it is the engine or the site
# ("... STILL CRASHED"). Safe mode is session-only on purpose.
class CrashLadder:
    WINDOW = 30.0        # seconds: crashes further apart than this count as separate
    QUIET = 600.0        # seconds of "no auto reload" after a give-up

    def __init__(self):
        self.state = {}

    def _st(self, host):
        return self.state.setdefault(host, {"times": [], "total": 0, "safe": False,
                                            "base": 0, "gaveup": 0.0,
                                            "cache_at": 0.0, "cbase": 0})

    def record(self, host, now=None):
        now = time.time() if now is None else now
        st = self._st(host)
        st["times"] = [t for t in st["times"] if now - t <= self.WINDOW]
        st["times"].append(now)
        st["total"] += 1
        if st["gaveup"] and now - st["gaveup"] < self.QUIET:
            return "quiet"
        n = len(st["times"])
        if n == 1:
            return "reload"
        if n == 2:
            if not st["cache_at"] or now - st["cache_at"] > self.QUIET:
                st["cache_at"] = now
                st["cbase"] = st["total"]
                return "cache"
            return "reload" if st["safe"] else "safe"
        if n == 3:
            return "reload" if st["safe"] else "safe"
        if n == 4:
            return "reload"
        st["gaveup"] = now
        return "giveup"

    def cache_verdict(self, host):
        """'held' = no crash since the cache was cleared."""
        st = self._st(host)
        return "held" if st["total"] == st["cbase"] else "failed"

    def mark_safe(self, host):
        st = self._st(host)
        st["safe"] = True
        st["base"] = st["total"]

    def is_safe(self, host):
        return bool(self.state.get(host, {}).get("safe"))

    def restart(self, host):
        """'Try without...' pressed by hand: a fresh crash window, and no automatic
        escalation to safe mode (that would hide which of YOUR switches mattered)."""
        st = self._st(host)
        st["times"] = []
        st["gaveup"] = 0.0
        st["safe"] = True
        st["base"] = st["total"]
        st["cache_at"] = time.time()         # the cache rung is not part of YOUR bisect

    def verdict(self, host):
        """'held' = no crash since safe mode began, else 'failed'."""
        st = self._st(host)
        return "held" if st["total"] == st["base"] else "failed"


def get_launch_url():
    """Return the URL Windows handed us on the command line (sys.argv[1]),
    or None.

    When WhyBrowse is the default browser, clicking a link elsewhere makes
    Windows launch us as e.g.  WhyBrowse.py "https://example.com/page"  (see
    the launch_cmd built in set_default_browser_windows(), which registers
    exactly that "%1" pattern). Previously nothing ever read that argument,
    so the URL was silently discarded and a normal empty/restored window
    opened instead - clicking a link appeared to do nothing."""
    for a in sys.argv[1:]:
        a = a.strip().strip('"')
        if not a or a.startswith("-"):
            continue
        if a.startswith(("http://", "https://", "file://", "magnet:")):
            return a                      # magnet: is handled by DEL 49
        if os.path.isfile(a) and a.lower().endswith(".torrent"):
            return a                      # a .torrent file opened with WhyBrowse
        if os.path.isfile(a) and a.lower().endswith((".htm", ".html")):
            return "file:///" + a.replace("\\", "/")
        if "." in a and " " not in a:
            # bare host like "www.example.com" passed without a scheme
            return "https://" + a
    return None


def get_launch_profile():
    """Return the profile asked for on the command line, or None.

    Another program can say WHICH login a link should open with:

        WhyBrowse.exe --profile=gotanetreserv "https://tradera.com/..."

    The value is matched against a profile's id OR its name (case-
    insensitively), so callers can use whichever they know. get_launch_url()
    already skips arguments beginning with "-", so this flag is invisible to
    the URL detection and old behaviour is untouched when it is absent.

    Added for F(re)email: mail arriving at one Gmail account should open its
    links with the browser login that belongs to that account, instead of
    always landing in profile 1."""
    for a in sys.argv[1:]:
        a = a.strip().strip('"')
        for prefix in ("--profile=", "-profile=", "/profile="):
            if a.lower().startswith(prefix):
                val = a[len(prefix):].strip()
                if val:
                    return val
    return None


def install_crash_handler(app_ref=None):
    """Route uncaught exceptions to the log and a readable dialog."""
    def hook(exc_type, exc_value, exc_tb):
        tb = "".join(traceback.format_exception(exc_type, exc_value, exc_tb))
        log_line("UNCAUGHT EXCEPTION\n" + tb)
        try:
            box = QMessageBox()
            box.setIcon(QMessageBox.Icon.Critical)
            box.setWindowTitle(APP_NAME + " - Unexpected error")
            box.setText("Something went wrong, but the browser tried to keep "
                        "running.\n\nA full diagnostic report was saved to:\n"
                        + LOG_FILE)
            box.setDetailedText(tb)
            box.exec()
        except Exception:
            sys.__stderr__.write(tb)
    sys.excepthook = hook


def check_single_instance():
    """Windows-only: detect whether another WhyBrowse process is already
    running against this SAME Helpfiles folder.

    Two live Chromium engines must never point at the same on-disk cookie
    database at once - that is exactly what corrupts/loses logins, and is
    the #1 cause of 'I have to log in again every time I test a new
    version'. Rather than warning and blocking, this just reports the fact:
    main() uses it to route THIS instance's Chromium storage to a separate
    'secondary' folder (see IS_SECONDARY_INSTANCE / profile_paths()), while
    a live cookie hand-off (see _snapshot_all_cookie_stores /
    _replay_cookie_snapshot on Browser) keeps it logged in to whatever the
    other, already-open instance currently has.

    Returns (mutex_handle, already_running). The handle MUST be kept alive
    for the app's lifetime (letting it get garbage-collected releases the
    lock early, which would defeat this check for the next launch)."""
    if platform.system() != "Windows" or ctypes is None:
        return None, False
    try:
        mutex_name = "Global\\WhyBrowse_" + hashlib.md5(
            BASE_DIR.encode("utf-8")).hexdigest()
        handle = ctypes.windll.kernel32.CreateMutexW(None, False, mutex_name)
        err = ctypes.windll.kernel32.GetLastError()
        already_running = (err == 183)  # ERROR_ALREADY_EXISTS
        # ERROR_ACCESS_DENIED (5) and no handle: the mutex EXISTS but belongs to
        # an ELEVATED WhyBrowse (Tower starts it with the Admin flag) and this
        # un-elevated process may not even open it.  That used to read as "nobody
        # is running", so a link clicked in I_am_game / F(re)email started a
        # whole second PRIMARY instance on the same cookie database - the
        # 'my logins never work in the new window' bug (2026-10-10).
        if not handle and err == 5:
            already_running = True
        return handle, already_running
    except Exception:
        return None, False


# ---- Single-instance URL forwarding (local pipe) ---------------------------
#  When WhyBrowse is already running and you click a link elsewhere (we're the
#  default browser), we DON'T want to launch a whole second WhyBrowse. Instead
#  this new process hands the URL to the already-open one over a local pipe and
#  quits; the running instance opens it (in profile 1) and comes to the front.
def ipc_pipe_name():
    """A stable local-pipe name, unique to THIS Helpfiles folder (so two copies
    of WhyBrowse in different folders don't cross-talk)."""
    try:
        return "WhyBrowse_ipc_" + hashlib.md5(BASE_DIR.encode("utf-8")).hexdigest()
    except Exception:
        return "WhyBrowse_ipc"


def forward_url_to_running_instance(url, timeout_ms=1500, profile=None):
    """Try to hand `url` to an already-running WhyBrowse over the local pipe.
    Returns True if the running instance accepted it (so this process should
    just exit), False if nobody was listening (so we start normally).

    WIRE FORMAT — deliberately backward-compatible: the message is still just
    the URL, unless a profile was asked for, in which case it becomes

        profile<TAB>url

    An older running instance receiving that would treat the whole thing as a
    URL and fail to open it, so the tab is only added when a profile is
    actually requested; a plain URL behaves exactly as it always did."""
    if not url:
        return False
    try:
        sock = QLocalSocket()
        sock.connectToServer(ipc_pipe_name())
        if not sock.waitForConnected(timeout_ms):
            return False
        payload = ("%s\t%s" % (profile, url)) if profile else url
        sock.write(payload.encode("utf-8"))
        sock.flush()
        sock.waitForBytesWritten(timeout_ms)
        # Bytes are now in the pipe; the OS buffers them for the server even
        # after we disconnect, so no need to wait for a reply.
        sock.disconnectFromServer()
        if sock.state() != QLocalSocket.LocalSocketState.UnconnectedState:
            sock.waitForDisconnected(timeout_ms)
        return True
    except Exception as e:
        log_line("forward_url error: %s" % e)
        return False


# ============================================================================
#  DEL 05 - SETTINGS STORE  (remembers everything between runs)
# ============================================================================
DEFAULT_SETTINGS = {
    "window": {"x": None, "y": None, "w": 1200, "h": 800, "maximized": False},
    "home_url": DEFAULT_HOME,
    "zoom": 1.0,
    "page_zoom_overrides": {},        # profile_id -> {"by_host":{host:zoom}, "by_url":{url:zoom}}
                                      # MANUAL sizes saved by hand (see ZoomSizeDialog); these
                                      # always win over the normal Ctrl+scroll zoom above and
                                      # persist until removed by hand.
    "restore_session": True,
    "last_tabs": [DEFAULT_HOME],
    "search_engine": SEARCH_URL,
    # ---- New behaviour ----
    "startup_mode": "restore",        # "restore" | "home" | "blank"
    "new_tab_mode": "blank",          # "blank" | "home"
    # ---- Privacy / blocking ----
    "adblock_enabled": True,
    "adblock_extra": [],              # user-added domains to block
    "hide_search_ads": True,          # hide sponsored "ad" results on search engines
    "https_upgrade": True,            # open http:// links over https:// (fall back if it fails)
    "https_exceptions": [],           # hosts where https failed once - keep them on http
    "block_third_party_cookies": True,
    "freeze_animations": True,        # stop blinking carets / animations (default ON)
    "freeze_default_v2": True,         # one-time migration marker (force the above ON once)
    "freeze_js_animations": False,    # kill rAF loop globally (breaks YouTube/Google) - OFF
    "freeze_js_persite_v1": True,      # migration: force the global one OFF (it's per-site now)
    "youtube_adblock": True,          # built-in YouTube ad skipper/hider (youtube.com only)
    "imdb_reference": True,           # rewrite IMDb /title/ttNNN/ → /reference/ layout
    "keep_profile_tabs_alive": True,  # keep other profiles' tabs loaded (no reload on switch)
    "check_engine_updates": True,     # at startup, check PyPI for a newer PyQt6-WebEngine
                                       # (the Chromium engine WhyBrowse runs on) and toast if found
    # Latest stable Chrome version fetched from Google's VERSIONHISTORY API.
    # Used by _effective_user_agent() to keep the UA string current without
    # manual edits.  Updated at most once every 30 days (background thread,
    # never blocks startup).  Only the MAJOR version number is stored.
    "cached_chrome_major": 136,        # last known latest stable Chrome major version
    "cached_chrome_version_date": 0,   # unix timestamp of last successful fetch
    "restore_scroll": False,          # global default for "go to last position" (per-site opt-in)
    # ---- UPLOAD folders (downloads are separate: profile save_dir/save_dirs) ----
    # Chromium's upload picker opens wherever you last picked a file ANYWHERE, so
    # a site whose files live on B: kept starting on C:. These make the START
    # folder a per-site choice, with a favourites quick-pick popup.
    "upload_dirs": {},                # host -> folder the upload picker starts in
    "upload_favs": [],                # [{"name","path"}] favourite upload folders
    "upload_last": "",                # last folder actually used (fallback)
    "upload_recent": [],              # DEL 54: last folders files were picked from (newest first)
    "upload_site_last": {},           # DEL 54: host -> {"dir", "t"} last folder used on that site
    "upload_picker": "own",           # DEL 54: own = WhyBrowse picker with a recent-folders column | windows
    "upload_start": "profile",        # DEL 59: picker opens in the profile's default folder | "site" = site's last folder
    "upload_ask": "unset",            # show the chooser popup: unset|always|never
                                      #   unset  = only when the site has no folder
                                      #   always = every upload (site folder pre-picked)
                                      #   never  = go straight to the picker
    "sheet_remember_cell": True,      # Google Sheets: return to the last active cell on (re)load
    "sheet_lastcell": {},             # sid -> {gid: cell} last active cell per sheet-tab
    "stay_signed_in": True,           # while a Google/MS tab is open, never block 3p cookies
                                      # (stops Sheets/Drive going blank + repeated re-login)
    "user_agent": "",                 # custom UA ("" = auto: modern Chrome, no QtWebEngine token)
    "chrome_identity": True,          # DEL 50: send the "Google Chrome" Sec-CH-UA brand,
                                      # fill in window.chrome and navigator.languages, so the
                                      # engine stops contradicting its own user-agent
                                      # (that contradiction is what Google's sign-in reads as
                                      #  "this browser or app may not be secure").
                                      # Ignored while a CUSTOM user_agent is set.
    "accept_language": "",            # "" = ACCEPT_LANGUAGE; Qt sends NO such header on its own
    "scroll_guard": True,             # release a page stuck with no scrollbar / dead wheel
                                      # (DEL 48; per-site: site_overrides[host]["scroll_guard"])
    "keep_scroll": True,              # once YOU have scrolled a page, it may not scroll you
                                      # back while it finishes loading
                                      # (DEL 51; per-site: site_overrides[host]["keep_scroll"])
    "scroll_speed": 1.0,              # mouse-wheel scroll distance multiplier (1.0 = native)
                                      # per-site EXTRA multiplier on top of this lives in
                                      # site_overrides[host]["scroll_speed_mult"] (right-click
                                      # page -> Exceptions -> Scroll speed here)
    "eager_lazy_images": True,        # load data-src/data-original images at once (fixes Bandcamp covers)
    "bar_open_new_tab": True,         # bookmark-bar links open in a NEW tab by default
    "form_memory": False,             # AUTO-remember form fields (off = only fields you save by hand)
    "draft_save": True,               # live-save message drafts (7-day safety net, viewable)
    "search_block_domains": [],       # hidden from search-engine result pages
    "native_find_domains": [          # sites where Ctrl+F is passed to the page
        "docs.google.com",
        "sheets.google.com",
        "slides.google.com",
        "notion.so",
        "airtable.com",
        "figma.com",
    ],
    "page_watches": [],               # Update-Scanner: pages watched for changes
    "tab_position": "left",           # "top" (horizontal) or "left" (vertical, compact)
    "tab_chars": 15,                  # fixed width of LEFT tabs, in characters
    "tab_width_px": 0,                # custom dragged width of LEFT tabs (0 = use chars)
    "tab_first_word_only": False,     # show only the first word of a page's title
    "bookmarks_position": "top",      # "top" (horizontal row) or "right" (vertical panel)
    "bookmark_indent": 0,             # leading spaces before each bookmark-bar label
    "site_macros": {},                # host -> {"steps":[...], "auto":bool} recorded macros
    "site_quicklinks": {},            # host -> [{"name","url"}] saved sub-pages for that site
    "userscripts_disabled": [],       # filenames of user add-ons turned off
    "bookmark_use_counts": {},        # url -> how many times opened (for "most used" sort)
    "bookmark_duplicate_mode": "ask", # what to do when bookmarking a URL that already exists:
                                      #   "ask"       – popup: shows where it is, asks what to do
                                      #   "allow"     – silently add a duplicate to the bar
                                      #   "deny"      – silently do nothing (old behaviour)
    "bookmark_manager_autosave": False,  # auto-save on every change in the bookmark manager
    "tab_autosleep_min": 5,           # idle delay before a background tab sleeps (min)
    "auto_sleep_all": True,           # auto-sleep is the DEFAULT for every idle background tab
                                      # (rev87). Opt a tab OUT with "Not auto-sleep".
    "sleep_pinned_too": True,         # pinned tabs sleep as well (they reload to the same URL)
    "tab_autorefresh_min": 5,         # min. time since last refresh before an AUTO-REFRESH tab
                                      # is allowed to reload again on focus (min)
    "keep_bg_active": False,          # keep background tabs unthrottled (MUCH more memory/CPU;
                                      # needs restart). Off = Chromium may throttle idle tabs.
    "domain_tab_rules": {},           # host -> {autorefresh,lock,nosleep,sleepmin} defaults
    "address_keywords": {},           # keyword (lowercase) -> url - type the keyword
                                      # anywhere you type an address and land there
    "tab_names": {"by_host": {}, "by_url": {}},   # saved custom names for sites/pages
    "hide_nag_banners": True,         # cookie banners + donation/nag bars
    "auto_accept_cookies": True,      # click "accept" on consent pop-ups + unlock scroll
    # When a site shows a "Verify you are human" wall (Cloudflare Turnstile,
    # hCaptcha...), turn the features that break such a check off FOR THAT SITE
    # once, then reload - otherwise the check can loop forever (e.g. predb.me).
    "challenge_auto_relax": True,
    # Sites where the above actually fired, so it can be undone in one click
    # (Troubleshoot → "Restore normal blocking…").
    "challenge_relaxed_hosts": [],
    "disable_passkeys": True,         # force password login instead of passkeys
    "fix_google_login": True,         # flatten Google's skew-prone sign-in box
    "clean_mode": False,              # run as a plain browser: NO blocking/scripts
    "open_link_default": "new_tab_stay",  # favourite "open link" shown mid & bottom of right-click menu
                                          # "new_tab_stay" = open in new tab, stay here
                                          # "new_tab_go"   = open in new tab, go there
    # ---- Links open in a NEW tab by default (DEL 42) ----
    # DEFAULT OFF: a plain in-page link click stays in the SAME tab (normal
    # browser behaviour). It was ON, which spawned a brand-new tab on every
    # navigation of a site like PayPal. SAVED links (bookmark bar / favourites)
    # still open in a new tab via their own setting (bar_open_new_tab); this
    # switch only governs ordinary links clicked ON a page. It has its own tick
    # box in Settings -> "Startup & tabs" (rev91), and the same tick is repeated
    # on a link's right-click menu.
    "links_open_new_tab": False,          # left-click a link -> stay in the same tab
    "links_newtab_off_v1": False,         # one-time migration marker (force the above OFF once)
    "links_newtab_off_v2": False,         # rev91: forced OFF a SECOND time - see load_settings()
    "links_same_tab_domains": [],         # exceptions: links to these hosts open in the SAME tab
                                          # (a LOCKED / pinned tab still forces a new tab regardless)
    # ---- The TEMP tab (DEL 44) ----
    # One tab (or a few) set aside for "I just want to look at this" pages, so
    # opening things doesn't breed tabs. NOTHING lands there by itself: only a
    # bookmark you set to "temp", the right-click "Open link in the temp tab",
    # or a "same tab" open that a LOCKED/pinned tab would otherwise have turned
    # into yet another tab. In-page links (Tradera/Vinted item after item) keep
    # following the normal rules, so they can never queue up in the temp tab and
    # overwrite each other.
    "temp_tab_enabled": True,
    "temp_tab_slots": 1,                  # how many temp tabs cycle before the oldest is reused
    "temp_tab_restore": True,             # keep temp tabs (as temp) after a restart
    "temp_locked_override": True,         # locked/pinned + "open in same tab" -> temp tab
    "open_bookmark_default": "",          # "" = follow bar_open_new_tab; else same|new|temp
    "translate_lang": "sv",               # target language for Google Translate (BCP-47 code)
    "site_overrides": {},             # host -> {feature_key: bool} per-site exceptions
    "sticky_rules": [],               # [{domain, selector}] freeze-to-top sections
    "freeze_rules": [],               # [{domain, selector}] elements frozen from moving
    # ---- Accessibility (low vision) ----
    "low_vision": False,              # bigger zoom + minimum font size
    "low_vision_zoom": 1.3,
    "low_vision_minfont": 18,
    "low_vision_ask": True,           # confirm before TURNING ON (re-flows every tab)
    "forced_colors": {"enabled": False, "bg": "#000000",
                      "fg": "#ffff00", "link": "#5fd0ff"},   # high-contrast scheme
    # ---- Password vault ----
    "vault_pin_enabled": True,        # extra security: require a 4-digit PIN
    "vault_autofill": True,           # auto-fill saved logins on matching pages
    "vault_autosave": True,           # offer to save a login after you submit one
    "vault_autolock": 0,              # seconds to auto-relock after unlock (0=off)
    "show_bookmarks_bar": True,       # Firefox-style row of bookmarks
    # ---- Favourites (see DEL 21F) ----
    "show_fav_bar_button": True,      # put the ⭐ Favourites drop-down on the bookmarks bar
    "fav_profile_enabled": True,      # auto-create the "99 Favourites" profile (DEL 21H)
    # ---- Popup guard + junk domains (DEL 21I) ----
    "popup_default": "allow",         # unlisted sites: "allow" | "block"
    "popup_policy": {},               # host -> "allow" | "block"  (per-site, wins)
    "junk_domains": [],               # hosts closed on sight, e.g. "togglevpn.org"
    "junk_autoclose": True,           # master switch for the junk list
    # ---- What the three address boxes SUGGEST (DEL 45d) ----
    "history_blocked_domains": [],    # never written to history, never suggested
    "suggest_min_chars": 3,           # no suggestion popup before this many letters
    # ---- In-page pop-up killer (DEL 21L) ----
    "popup_killers": {},              # host -> [{sel, mode, close_sel, label}]
    # ---- Bulk upload queue (DEL 21J) ----
    "bulk_autoadvance": True,         # try to re-open the site's picker by itself
    "bulk_advance_delay": 2500,       # ms to let an upload finish before the next
    # ---- Auction clock (see DEL 21G) ----
    "auction_clock": True,            # server-corrected countdown on auction pages
    "auction_margin_s": 20,           # "bid before" safety margin, in seconds
    "auction_show_within_s": 180,     # only SHOW the panel when <= this many seconds
                                      # remain (and still running); 0 = always show.
                                      # 8-days-left / already-ended pages stay silent.
    # (Vinted pinned searches were removed in rev68 — a plain /catalog?search_text=
    #  with no category filter returned everything, not just the board games wanted.)
    "auction_hosts": ["tradera.com", "ebay.com", "ebay.co.uk", "ebay.de",
                      "catawiki.com", "auctionet.com"],
    "element_hide_rules": [           # uBlock-style cosmetic hides {domain, selector}
        {"domain": "wikipedia.org", "selector": ".vector-column-end"},
    ],
    "spoof_location": {"enabled": False, "city": "Götene",
                       "lat": 58.5256, "lon": 13.4926},
    "location_recents": [{"name": "Götene", "lat": 58.5256, "lon": 13.4926}],
    # ---- Torrents & magnet links (DEL 49) ----
    #  A magnet link is not a file, so a browser normally does nothing with it.
    #  These decide what WhyBrowse does instead. See the DEL 49 header.
    "torrent_enabled": True,          # notice magnet: / .torrent links at all
    "torrent_mode": "ask",            # "ask" | "auto" | "ignore"
    "torrent_action": "download",     # "download" (built-in engine) | "savelink" | "client"
    "torrent_folder_mode": "custom",  # "custom" = the folder below | "downloads"
    "torrent_folder": "X:\\",         # the separate torrent folder
    "torrent_watch_clipboard": True,  # act when a magnet link is COPIED anywhere
    "torrent_resume_on_start": True,  # continue last session's unfinished torrents
    "torrent_seed_after": False,      # keep uploading after a download finishes
    "torrent_autoclose": False,       # close the Torrents window when all are done
    "torrent_window": {},             # its own size/position (x,y,w,h)
    "torrent_upnp": False,            # ask the router to open a port. OFF: libtorrent's
                                      # UPnP shutdown blocks ~20 s, i.e. closing WhyBrowse
                                      # would take 20 s. Downloading works without it.
    "torrent_port": 6881,             # the port the engine listens on
    "torrent_dl_limit_kbs": 0,        # download speed cap, KB/s (0 = no limit)
    "torrent_ul_limit_kbs": 0,        # upload speed cap, KB/s (0 = no limit)
    # ---- Appearance ----
    "theme": {},                      # empty = dark defaults; else THEME_KEYS dict
    # ---- Profiles (per-account; each its own cookies/logins/history/tabs) ----
    "profiles": [
        {"id": "default", "name": "Default", "color": "#39c6da", "badge": "1",
         "enabled": True, "shared_bookmarks": False, "last_tabs": []},
    ],
    "active_profile": "default",
    "default_profile": None,          # if set, ALWAYS starts on this profile
    # ---- Containers (separate logins WITHOUT switching profiles) ----
    #  A container is a lightweight, independent cookie store. A "container tab"
    #  runs on that store, so you can have e.g. two Gmail accounts open as two
    #  tabs in the SAME window (same profile) - each stays logged in on its own.
    #  Each entry: {"id": "ctr_xxxx", "name": "Work", "color": "#e08a3c"}.
    "containers": [],
}


def load_json(path, fallback):
    arc = _travel_protected_arc(path)
    if arc:
        # On the road these live in memory only, never on the host's
        # disk - see DEL 07D.
        data = _TRAVEL_STORE.get(arc)
        return fallback if data is None else data
    try:
        with open(path, "r", encoding="utf-8") as f:
            return json.load(f)
    except Exception:
        return fallback


def save_json(path, data):
    arc = _travel_protected_arc(path)
    if arc:
        _TRAVEL_STORE[arc] = data
        _travel_reseal()
        return True
    try:
        with open(path, "w", encoding="utf-8") as f:
            json.dump(data, f, indent=2, ensure_ascii=False)
        return True
    except Exception as e:
        log_line("save_json failed for {}: {}".format(path, e))
        return False


# ============================================================================
#  DEL 07D - MOVING TO ANOTHER COMPUTER  (full move · travel copy)
# ============================================================================
#
#  WHY THIS EXISTS
#  ---------------
#  The vault, and every saved profile login, are protected by Windows DPAPI —
#  one Windows user, one machine. Reinstalling Windows issues a NEW user SID,
#  so after a reinstall those are unreadable even on the same physical
#  computer. Copying Helpfiles\WhyBrowse across is therefore not a migration;
#  it is a migration minus every password, discovered far too late.
#
#  TWO MODES, AND THEY DIFFER IN WHAT THEY CARRY
#  ---------------------------------------------
#  FULL MOVE (.wbpack) — reinstalling Windows, or your own new machine.
#    Bookmarks, favourites, history, settings, userscripts, the vault, and the
#    Chromium profiles themselves (minus the caches, which are 3 GB of nothing
#    and rebuild themselves). Cookies included, so you arrive still logged in.
#    One passphrase; the vault is re-locked to the new machine on the way in.
#
#  TRAVEL COPY (.wbtrav) — a computer that is not yours. Bookmarks,
#    favourites, settings, userscripts and the vault. Nothing else, and in
#    particular NO cookies and NO history.
#
#    That last part is the whole point, and it is not caution for its own
#    sake. QtWebEngine writes its cookies as PLAINTEXT — profile/Cookies is an
#    ordinary SQLite file whose encrypted_value column is empty on every row.
#    Anyone who can see the folder can lift 2 000-odd live session cookies with
#    a free SQLite viewer and be signed in as you, without ever starting
#    WhyBrowse. A password prompt in front of the window would be a lock on a
#    door with no walls. So the cookies do not travel: the browser starts with
#    an empty profile, you sign in by hand for the session, and the profile
#    goes in the bin when you close it.
#
#    Without the master password there are no bookmarks and no vault — nothing
#    to show, rather than something hidden.

import base64
import hashlib
import hmac
import io
import zipfile

try:
    from cryptography.hazmat.primitives.ciphers.aead import AESGCM as _AESGCM
except Exception:                                   # pragma: no cover
    _AESGCM = None                                  # the stdlib path is used

_PACK_MAGIC = {"full": b"WBPACKv1", "travel": b"WBTRAVv1"}
_PACK_FRAME = 4 * 1024 * 1024


class PackError(Exception):
    """Anything wrong with a move file that is not a wrong password."""


class PackPassword(PackError):
    """The password does not open this file (or the file has been altered)."""


# ---- Keys ------------------------------------------------------------------
#  Two levels. The MASTER key comes from the password by scrypt, which is
#  deliberately slow, so a travel session derives it once and keeps it. Each
#  written FILE then gets its own key from the master plus 16 fresh random
#  bytes in the header — necessary because a travel copy is re-sealed every
#  time a bookmark changes, and the frame index is used as the AES-GCM nonce.
#  That is safe only while one key never encrypts two different streams.

def _pack_derive(password, salt, algo):
    pw = (password or "").encode("utf-8")
    if algo == "scrypt":
        return hashlib.scrypt(pw, salt=salt, n=2 ** 15, r=8, p=1, dklen=32,
                              maxmem=96 * 1024 * 1024)
    return hashlib.pbkdf2_hmac("sha256", pw, salt, 600000, 32)


def _pack_best_kdf():
    try:
        hashlib.scrypt(b"x", salt=b"y" * 16, n=2, r=8, p=1, dklen=32)
        return "scrypt"
    except Exception:
        return "pbkdf2"


def _pack_file_key(master, file_nonce):
    return hmac.new(master, b"wbfile" + file_nonce, hashlib.sha256).digest()


def _pack_keystream(key, nonce, n):
    out, ctr = bytearray(), 0
    while len(out) < n:
        out += hmac.new(key, nonce + ctr.to_bytes(4, "big"),
                        hashlib.sha256).digest()
        ctr += 1
    return bytes(out[:n])


def _frame_aad(index, last):
    return b"WB" + index.to_bytes(8, "big") + (b"\x01" if last else b"\x00")


def _frame_seal(key, index, last, data, cipher):
    aad = _frame_aad(index, last)
    if cipher == "aes-gcm":
        return _AESGCM(key).encrypt(index.to_bytes(12, "big"), data, aad)
    nonce = os.urandom(16)
    ct = bytes(a ^ b for a, b in
               zip(data, _pack_keystream(key, nonce, len(data))))
    tag = hmac.new(key, aad + nonce + ct, hashlib.sha256).digest()
    return nonce + tag + ct


def _frame_open(key, index, last, blob, cipher):
    aad = _frame_aad(index, last)
    if cipher == "aes-gcm":
        if _AESGCM is None:
            raise PackError(
                "This file was sealed with AES-GCM, but the 'cryptography' "
                "package is not installed here. Install it "
                "(pip install cryptography) and try again.")
        try:
            return _AESGCM(key).decrypt(index.to_bytes(12, "big"), blob, aad)
        except Exception:
            raise PackPassword("wrong password, or the file has been altered")
    if len(blob) < 48:
        raise PackError("The file is damaged.")
    nonce, tag, ct = blob[:16], blob[16:48], blob[48:]
    if not hmac.compare_digest(
            tag, hmac.new(key, aad + nonce + ct, hashlib.sha256).digest()):
        raise PackPassword("wrong password, or the file has been altered")
    return bytes(a ^ b for a, b in
                 zip(ct, _pack_keystream(key, nonce, len(ct))))


class _PackSink:
    """Write-only file object that seals everything written to it, so a 300 MB
    move is built straight into the ciphertext and never lands on disk as a
    plaintext copy first. zipfile is happy to write to an unseekable stream."""

    def __init__(self, fh, key, cipher):
        self._fh, self._key, self._cipher = fh, key, cipher
        self._buf = bytearray()
        self._index = 0
        self._count = 0

    def write(self, data):
        self._buf += data
        self._count += len(data)
        while len(self._buf) >= _PACK_FRAME:
            self._emit(bytes(self._buf[:_PACK_FRAME]), False)
            del self._buf[:_PACK_FRAME]
        return len(data)

    def tell(self):
        return self._count

    def flush(self):
        pass

    def _emit(self, chunk, last):
        blob = _frame_seal(self._key, self._index, last, chunk, self._cipher)
        self._fh.write(len(blob).to_bytes(4, "big"))
        self._fh.write(b"\x01" if last else b"\x00")
        self._fh.write(blob)
        self._index += 1

    def finish(self):
        self._emit(bytes(self._buf), True)
        self._buf = bytearray()


def _pack_begin(fh, mode, extra, password="", keymat=None):
    """Write the header; return (file_key, cipher, keymat)."""
    if keymat:
        master, salt, kdf = keymat
    else:
        kdf = _pack_best_kdf()
        salt = os.urandom(16)
        master = _pack_derive(password, salt, kdf)
    file_nonce = os.urandom(16)
    header = {
        "program": APP_NAME,
        "mode": mode,
        "version": 1,
        "created": time.strftime("%Y-%m-%d %H:%M:%S"),
        "machine": platform.node(),
        "kdf": kdf,
        "cipher": "aes-gcm" if _AESGCM is not None else "hmac-ctr",
        "salt": base64.b64encode(salt).decode("ascii"),
        "fkey": base64.b64encode(file_nonce).decode("ascii"),
    }
    header.update(extra or {})
    raw = json.dumps(header).encode("utf-8")
    fh.write(_PACK_MAGIC[mode])
    fh.write(len(raw).to_bytes(4, "big"))
    fh.write(raw)
    return (_pack_file_key(master, file_nonce), header["cipher"],
            (master, salt, kdf))


def _pack_read_header(fh, mode):
    magic = fh.read(8)
    if magic not in (_PACK_MAGIC["full"], _PACK_MAGIC["travel"]):
        raise PackError("This is not a WhyBrowse move file.")
    if mode and magic != _PACK_MAGIC[mode]:
        want = "full move" if mode == "full" else "travel copy"
        raise PackError("This is not a {} file.".format(want))
    hlen = int.from_bytes(fh.read(4), "big")
    if not 0 < hlen < 65536:
        raise PackError("The file header is damaged.")
    try:
        return json.loads(fh.read(hlen).decode("utf-8"))
    except Exception:
        raise PackError("The file header is damaged.")


def _pack_open_keys(header, password, keymat=None):
    kdf = header.get("kdf", "pbkdf2")
    salt = base64.b64decode(header.get("salt", ""))
    master = keymat[0] if keymat else _pack_derive(password, salt, kdf)
    fnon = base64.b64decode(header.get("fkey", "") or b"")
    return (_pack_file_key(master, fnon), header.get("cipher", "hmac-ctr"),
            (master, salt, kdf))


def _pack_frames(fh, key, cipher):
    """Yield each frame's plaintext, in order, verifying as it goes. A
    truncated or re-ordered file fails here instead of restoring halfway."""
    index = 0
    while True:
        raw_len = fh.read(4)
        if len(raw_len) < 4:
            raise PackError("The file ends too early - it is incomplete.")
        n = int.from_bytes(raw_len, "big")
        flag = fh.read(1)
        if n > 64 * 1024 * 1024 or len(flag) < 1:
            raise PackError("The file is damaged.")
        blob = fh.read(n)
        if len(blob) != n:
            raise PackError("The file ends too early - it is incomplete.")
        last = flag == b"\x01"
        yield _frame_open(key, index, last, blob, cipher)
        index += 1
        if last:
            return


# ---- What goes in ----------------------------------------------------------

def _pack_safe_arc(name):
    """Refuse a member name that would write outside the destination."""
    norm = (name or "").replace("\\", "/").lstrip("/")
    if not norm or norm.endswith("/"):
        return ""
    parts = [p for p in norm.split("/") if p not in ("", ".")]
    if not parts or any(p == ".." for p in parts) or ":" in parts[0]:
        return ""
    return "/".join(parts)


# Chromium rebuilds all of these by itself, and together they are about 3 GB
# of the 3.5 GB on disk. Carrying them would make a move that takes an hour
# and restores nothing you would notice.
_PACK_SKIP_DIRS = {
    "cache", "cache_secondary", "gpucache", "code cache", "shader_cache",
    "storage", "service worker", "service worker.old", "blob_storage",
    "dawngraphitecache", "dawnwebgpucache", "videodecodestats",
    "shared dictionary", "component_crx_cache", "optimization_guide_model_store",
}


def _pack_add_tree(zf, abs_dir, arc_prefix, on_file=None, prune=True):
    if not os.path.isdir(abs_dir):
        return
    for root, dirs, files in os.walk(abs_dir):
        if prune:
            dirs[:] = [d for d in dirs if d.lower() not in _PACK_SKIP_DIRS]
        for fn in files:
            full = os.path.join(root, fn)
            rel = os.path.relpath(full, abs_dir).replace("\\", "/")
            arc = "{}/{}".format(arc_prefix, rel)
            try:
                if fn.lower() == "vault.dat":
                    zf.writestr(arc, _vault_unwrap(open(full, "rb").read()))
                else:
                    zf.write(full, arc)
            except Exception as e:
                log_line("move: skipped {} ({})".format(full, e))
                continue
            if on_file:
                on_file(full)


def _vault_unwrap(blob):
    """Strip only the DPAPI layer off a vault.

    What is underneath is either plain JSON or the PIN-encrypted 'P1' blob,
    and the PIN layer is machine-independent — so a PIN-protected vault
    travels without the PIN ever being needed here, and still asks for it on
    the other side."""
    try:
        return _dpapi(blob, False)
    except Exception as e:
        log_line("vault unwrap failed ({}) - carried as-is".format(e))
        return blob


def _vault_rewrap(inner):
    """Lock a vault to THIS machine."""
    try:
        return _dpapi(inner, True)
    except Exception as e:
        log_line("vault rewrap failed: {}".format(e))
        return inner


def _pack_root_files(travel=False):
    """(abs_path, arcname) for the loose files in DATA_DIR."""
    names = ["settings.json", "bookmarks.json", "bookmarks_shared.json",
             "favourites.json", "page_menu.json", "newtab.html", "vault.dat"]
    if not travel:
        names += ["history.json", "watch_cache.json", "scroll_positions.json",
                  "form_memory.json", "message_drafts.json",
                  "crash_recovery.json"]
    return [(os.path.join(DATA_DIR, n), n) for n in names]


def _pack_write_root(zf, travel, on_file=None):
    for path, arc in _pack_root_files(travel):
        data = None
        if _TRAVEL_MODE and arc in _TRAVEL_PROTECTED_NAMES:
            held = _TRAVEL_STORE.get(arc)
            if held is not None:
                data = json.dumps(held, indent=2,
                                  ensure_ascii=False).encode("utf-8")
        if data is None and arc == "vault.dat":
            blob = _vault_blob_read(path)
            if blob:
                data = _vault_unwrap(blob)
        if data is None:
            if not os.path.isfile(path):
                continue
            with open(path, "rb") as f:
                data = f.read()
        zf.writestr(arc, data)
        if on_file:
            on_file(path)


# ---- Full move -------------------------------------------------------------

def _full_export(path, password, opts=None, progress=None):
    opts = opts or {}
    stats = {"files": 0, "bytes": 0}

    def _tick(_f=None):
        stats["files"] += 1
        if progress and stats["files"] % 40 == 0:
            progress(stats["files"])

    tmp = path + ".part"
    try:
        with open(tmp, "wb") as fh:
            key, cipher, _km = _pack_begin(fh, "full", {}, password=password)
            sink = _PackSink(fh, key, cipher)
            with zipfile.ZipFile(sink, "w", zipfile.ZIP_DEFLATED,
                                 compresslevel=6) as zf:
                _pack_write_root(zf, travel=False, on_file=_tick)
                _pack_add_tree(zf, USERSCRIPTS_DIR, "userscripts", _tick)
                _pack_add_tree(zf, KBD_LAYOUTS_DIR, "keyboard_layouts", _tick)
                if os.path.isfile(BACKUP_CODES_FILE):
                    zf.write(BACKUP_CODES_FILE, "shared/backup_codes.json")
                    _tick()
                if opts.get("profiles", True):
                    _pack_add_tree(zf, PROFILE_DIR, "profile", _tick)
                    _pack_add_tree(zf, PROFILES_DIR, "profiles", _tick)
            sink.finish()
        os.replace(tmp, path)
    except Exception:
        try:
            os.remove(tmp)
        except Exception:
            pass
        raise
    stats["bytes"] = os.path.getsize(path)
    log_line("Full move written: {} ({} files, {} bytes)".format(
        path, stats["files"], stats["bytes"]))
    return stats


def _full_import(path, password, progress=None):
    """Restore a .wbpack over this installation. Returns the file count."""
    scratch = os.path.join(DATA_DIR, "_incoming.zip")
    written = 0
    try:
        with open(path, "rb") as fh:
            header = _pack_read_header(fh, "full")
            key, cipher, _km = _pack_open_keys(header, password)
            with open(scratch, "wb") as out:
                for chunk in _pack_frames(fh, key, cipher):
                    out.write(chunk)

        with zipfile.ZipFile(scratch, "r") as zf:
            names = [n for n in zf.namelist() if not n.endswith("/")]
            for member in names:
                arc = _pack_safe_arc(member)
                if not arc:
                    log_line("move: refused member {!r}".format(member))
                    continue
                if arc == "shared/backup_codes.json":
                    target = BACKUP_CODES_FILE
                else:
                    target = os.path.join(DATA_DIR, *arc.split("/"))
                try:
                    os.makedirs(os.path.dirname(target), exist_ok=True)
                    raw = zf.read(member)
                    if os.path.basename(arc).lower() == "vault.dat":
                        # The one thing that changes on the way in: the vault
                        # is locked to THIS machine as it lands.
                        raw = _vault_rewrap(raw)
                    with open(target, "wb") as f:
                        f.write(raw)
                    written += 1
                except Exception as e:
                    log_line("move: could not write {} ({})".format(target, e))
                if progress and written % 40 == 0:
                    progress(written, len(names))
    finally:
        try:
            os.remove(scratch)
        except Exception:
            pass
    log_line("Full move imported from {} ({} files)".format(path, written))
    return written


# ---- Travel copy -----------------------------------------------------------
#
#  _TRAVEL_STORE holds what must never touch the host's disk: the settings,
#  the bookmarks, the favourites, the right-click menu arrangement — and, in
#  _TRAVEL_VAULTS, the password vaults. Everything else the running browser
#  needs is written into the temporary DATA_DIR and wiped on the way out.

_TRAVEL_PROTECTED_NAMES = {"settings.json", "bookmarks.json",
                           "bookmarks_shared.json", "favourites.json",
                           "page_menu.json"}
_TRAVEL_STORE = {}          # arcname -> parsed json
_TRAVEL_VAULTS = {}         # abs path -> DPAPI blob for THIS host, memory only
_TRAVEL_KEYMAT = None
_TRAVEL_READY = False


def _travel_protected_arc(path):
    """The arcname if this path is one of the memory-only files, else ''."""
    if not _TRAVEL_MODE:
        return ""
    name = os.path.basename(path or "")
    if name in _TRAVEL_PROTECTED_NAMES and \
            os.path.dirname(os.path.abspath(path or "")) == \
            os.path.abspath(DATA_DIR):
        return name
    return ""


def _vault_blob_read(path):
    """Read a vault blob — from memory on the road, from disk at home."""
    if _TRAVEL_MODE:
        return _TRAVEL_VAULTS.get(os.path.abspath(path))
    try:
        with open(path, "rb") as f:
            return f.read()
    except Exception:
        return None


def _vault_blob_write(path, blob):
    if _TRAVEL_MODE:
        _TRAVEL_VAULTS[os.path.abspath(path)] = blob
        _travel_reseal()
        return True
    try:
        os.makedirs(os.path.dirname(path), exist_ok=True)
        with open(path, "wb") as f:
            f.write(blob)
        return True
    except Exception as e:
        log_line("vault save failed: {}".format(e))
        return False


def _vault_blob_exists(path):
    if _TRAVEL_MODE:
        return os.path.abspath(path) in _TRAVEL_VAULTS
    return os.path.isfile(path)


def _travel_export(path, password="", keymat=None):
    """Write a .wbtrav: bookmarks, favourites, settings, userscripts, vault.
    No cookies and no history, ever."""
    count = 0

    def _tick(_f=None):
        nonlocal count
        count += 1

    tmp = path + ".part"
    try:
        with open(tmp, "wb") as fh:
            key, cipher, _km = _pack_begin(fh, "travel", {},
                                           password=password, keymat=keymat)
            sink = _PackSink(fh, key, cipher)
            with zipfile.ZipFile(sink, "w", zipfile.ZIP_DEFLATED,
                                 compresslevel=6) as zf:
                _pack_write_root(zf, travel=True, on_file=_tick)
                _pack_add_tree(zf, USERSCRIPTS_DIR, "userscripts", _tick)
                _pack_add_tree(zf, KBD_LAYOUTS_DIR, "keyboard_layouts", _tick)
                # Per-profile vaults, and nothing else from those folders.
                if _TRAVEL_MODE:
                    for abspath, blob in _TRAVEL_VAULTS.items():
                        rel = os.path.relpath(abspath, DATA_DIR)
                        rel = rel.replace("\\", "/")
                        if rel.startswith("profiles/"):
                            zf.writestr(rel, _vault_unwrap(blob))
                            _tick()
                elif os.path.isdir(PROFILES_DIR):
                    for pid in os.listdir(PROFILES_DIR):
                        v = os.path.join(PROFILES_DIR, pid, "vault.dat")
                        if os.path.isfile(v):
                            with open(v, "rb") as f:
                                zf.writestr("profiles/{}/vault.dat".format(pid),
                                            _vault_unwrap(f.read()))
                            _tick()
            sink.finish()
        os.replace(tmp, path)
    except Exception:
        try:
            os.remove(tmp)
        except Exception:
            pass
        raise
    log_line("Travel copy written: {} ({} items)".format(path, count))
    return count


def _travel_unlock(password):
    """Open the travel file we are running from.

    PackPassword means try again; anything else is a broken file."""
    global _TRAVEL_KEYMAT, _TRAVEL_READY
    with open(_TRAVEL_PACK, "rb") as fh:
        header = _pack_read_header(fh, "travel")
        key, cipher, keymat = _pack_open_keys(header, password)
        buf = io.BytesIO()
        for chunk in _pack_frames(fh, key, cipher):
            buf.write(chunk)
    buf.seek(0)
    with zipfile.ZipFile(buf, "r") as zf:
        for member in zf.namelist():
            arc = _pack_safe_arc(member)
            if not arc:
                continue
            raw = zf.read(member)
            if arc in _TRAVEL_PROTECTED_NAMES:
                try:
                    _TRAVEL_STORE[arc] = json.loads(raw.decode("utf-8"))
                except Exception:
                    # newtab.html and friends are not JSON; they go to disk.
                    pass
                else:
                    continue
            if os.path.basename(arc).lower() == "vault.dat":
                # Memory only. Wrapping it with the host's DPAPI here keeps
                # every existing code path working unchanged, and the blob is
                # never written where the host could get at it.
                _TRAVEL_VAULTS[os.path.abspath(
                    os.path.join(DATA_DIR, *arc.split("/")))] = \
                    _vault_rewrap(raw)
                continue
            target = os.path.join(DATA_DIR, *arc.split("/"))
            os.makedirs(os.path.dirname(target), exist_ok=True)
            with open(target, "wb") as f:
                f.write(raw)
    _TRAVEL_KEYMAT = keymat
    _TRAVEL_READY = True
    log_line("Travel copy unlocked ({})".format(os.path.basename(_TRAVEL_PACK)))
    return True


def _travel_reseal():
    """Write the travel file back, whenever anything protected changes."""
    if not (_TRAVEL_MODE and _TRAVEL_READY and _TRAVEL_KEYMAT):
        return
    try:
        _travel_export(_TRAVEL_PACK, keymat=_TRAVEL_KEYMAT)
    except Exception as e:
        log_line("Could not save the travel copy: {}".format(e))


def _travel_change_password(new_pw):
    global _TRAVEL_KEYMAT
    _travel_export(_TRAVEL_PACK, password=new_pw)
    with open(_TRAVEL_PACK, "rb") as fh:
        header = _pack_read_header(fh, "travel")
    _TRAVEL_KEYMAT = _pack_open_keys(header, new_pw)[2]
    log_line("Travel copy master password changed")


def _travel_shutdown():
    """Seal up, then leave nothing behind."""
    if not _TRAVEL_MODE:
        return
    try:
        _travel_reseal()
    except Exception:
        pass
    _TRAVEL_STORE.clear()
    _TRAVEL_VAULTS.clear()
    import shutil as _sh
    _sh.rmtree(_TRAVEL_DIR, ignore_errors=True)


if _TRAVEL_MODE:
    import atexit as _atexit_travel
    _atexit_travel.register(_travel_shutdown)


USERSCRIPT_README = """WhyBrowse user add-ons
======================
Drop .js or .css files in THIS folder to add your own tweaks - and share them
with others. They are injected into web pages automatically (works in the .exe
build too; this folder lives next to the program).

Limit an add-on to certain sites with a @match line near the top (optional):
    // @match blocket.se
    // @match tradera.com
For a .css file use a CSS comment:
    /* @match blocket.se */
No @match line = the add-on runs on EVERY site.

Examples:
  hide-stuff.css   ->   /* @match example.com */
                        .annoying-banner { display:none !important; }
  hello.js         ->   // @match example.com
                        console.log('my add-on ran');

Turn add-ons on/off inside WhyBrowse:  ☰ menu  ->  🧩 User add-ons.
Edit a file, then ☰ -> 🧩 User add-ons -> Reload add-ons.
"""


def load_userscripts():
    """Scan the userscripts folder for .js/.css add-ons (with optional @match)."""
    out = []
    try:
        os.makedirs(USERSCRIPTS_DIR, exist_ok=True)
        readme = os.path.join(USERSCRIPTS_DIR, "README.txt")
        if not os.path.isfile(readme):
            with open(readme, "w", encoding="utf-8") as f:
                f.write(USERSCRIPT_README)
        for fn in sorted(os.listdir(USERSCRIPTS_DIR)):
            low = fn.lower()
            if not (low.endswith(".js") or low.endswith(".css")):
                continue
            try:
                with open(os.path.join(USERSCRIPTS_DIR, fn), "r",
                          encoding="utf-8", errors="replace") as f:
                    code = f.read()
            except Exception:
                continue
            hosts = []
            for line in code.splitlines()[:30]:
                if "@match" in line:
                    m = line.split("@match", 1)[1].strip().strip("*/").strip()
                    m = m.replace("www.", "").strip()
                    if m:
                        hosts.append(m)
            out.append({"name": fn, "type": "css" if low.endswith(".css") else "js",
                        "hosts": hosts, "code": code})
    except Exception as e:
        log_line("userscripts load failed: %s" % e)
    return out


def load_settings():
    data = load_json(SETTINGS_FILE, {})
    merged = json.loads(json.dumps(DEFAULT_SETTINGS))  # deep copy
    if isinstance(data, dict):
        merged.update(data)
        # keep nested window dict complete
        win = dict(DEFAULT_SETTINGS["window"])
        win.update(data.get("window", {}))
        merged["window"] = win
        # One-time migration: de-animation is now ON by default. Flip it on once
        # for existing users (who may have it saved as False), then respect any
        # later manual choice via the marker key.
        if not data.get("freeze_default_v2"):
            merged["freeze_animations"] = True
            merged["freeze_default_v2"] = True
        # The rAF-loop kill is now PER-SITE (global-on broke YouTube/Google by
        # stopping their lazy content loading). Force the global switch OFF once.
        if not data.get("freeze_js_persite_v1"):
            merged["freeze_js_animations"] = False
            merged["freeze_js_persite_v1"] = True
        # "Links open in a new tab by default" (DEL 42) was too eager — every
        # in-page link on a site like PayPal spawned a fresh tab. It is now OFF
        # by default; force it OFF once for existing users who had it saved ON,
        # then respect any later manual choice via the marker.
        if not data.get("links_newtab_off_v1"):
            merged["links_open_new_tab"] = False
            merged["links_newtab_off_v1"] = True
        # rev91: and it was ON again. Measured in his live settings.json on
        # 2026-09-09 - links_open_new_tab True while links_newtab_off_v1 was
        # ALSO True, so the v1 migration had already run and something turned
        # it back on afterwards. Together with open_link_default "new_tab_go"
        # that means every plain link click made a new tab AND jumped to it,
        # which is the "click, new tab, click, new tab, half a dozen tabs to
        # reach one Vinted setting" report. Whether it was flipped by hand or
        # by an accidental hit on the checkable row in the link right-click
        # menu cannot be told after the fact, so it is forced OFF once more
        # behind its OWN marker. A choice made AFTER this runs is never
        # touched again - a saved setting must beat a code default, which is
        # exactly why the v1 marker could not do the job a second time.
        if not data.get("links_newtab_off_v2"):
            merged["links_open_new_tab"] = False
            merged["links_newtab_off_v2"] = True
        # Pin is now per-TAB only (rev79) - "pin" is no longer a per-domain
        # rule (see _apply_domain_rules), so any leftover "pin" entry from an
        # older settings file is stripped here and can never re-apply. Other
        # domain rules (autorefresh/lock/nosleep/sleepmin) are left untouched.
        dtr = merged.get("domain_tab_rules")
        if isinstance(dtr, dict):
            for h in list(dtr.keys()):
                d = dtr[h]
                if isinstance(d, dict) and d.pop("pin", None) is not None and not d:
                    dtr.pop(h, None)
        # rev87: auto-sleep turned round. It used to be opt-IN per tab/domain
        # ("Auto-sleep"); it is now the DEFAULT for every idle background tab
        # and what you set by hand is the opt-OUT ("Not auto-sleep" = nosleep).
        # So a saved "autosleep": true domain rule now says nothing new and is
        # dropped - keeping it would leave a tick box that looks like it does
        # something. Done ONCE, behind a marker, so a rule you set AFTER this
        # is never touched again (a saved setting must beat a code default).
        if not data.get("nosleep_invert_v1"):
            dtr = merged.get("domain_tab_rules")
            if isinstance(dtr, dict):
                for h in list(dtr.keys()):
                    d = dtr[h]
                    if not isinstance(d, dict):
                        continue
                    d.pop("autosleep", None)
                    if not d:
                        dtr.pop(h, None)
            # "Keep background tabs active" switches OFF Chromium's own memory
            # and timer throttling for every hidden tab - it is the single
            # biggest reason a long session climbs into gigabytes. With
            # auto-sleep now on by default it is also redundant, so it is
            # turned off once here. Settings -> Performance turns it back on.
            merged["keep_bg_active"] = False
            merged["nosleep_invert_v1"] = True
    return merged


# ============================================================================
#  DEL 06 - WINDOWS ICON HELPER
# ============================================================================
def ico_path():
    prog = os.path.splitext(os.path.basename(
        sys.executable if getattr(sys, "frozen", False) else __file__))[0]
    # For a frozen exe the icon may be named after the exe; for .py after the
    # script. Try the program name first, then the actual base name.
    candidates = [
        os.path.join(BASE_DIR, "Icons", APP_NAME + ".ico"),
        os.path.join(BASE_DIR, "Icons", prog + ".ico"),
    ]
    for c in candidates:
        if os.path.isfile(c):
            return c
    return None


def set_app_user_model_id():
    """Must be called BEFORE QApplication so the taskbar groups correctly."""
    if platform.system() == "Windows" and ctypes is not None:
        try:
            ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(APP_ID)
        except Exception:
            pass


def apply_window_icon(widget):
    p = ico_path()
    if p:
        try:
            widget.setWindowIcon(QIcon(p))
        except Exception:
            pass


# ---- Never let a window open bigger than the screen it is on (rev81) --------
#  One long un-wrapped label is all it takes: a QLabel asks the layout for the
#  width of its longest line, the layout obliges, and the dialog opens wider
#  than the monitor with its buttons off in the dark. (That is exactly what the
#  About box did while it was showing the whole change log - see APP_HISTORY.)
#  Fixing the label is the real fix; this is the safety net for the next one.
#  SLACK is deliberate: this only ever acts on a window that is genuinely
#  BIGGER than the monitor, never on one that merely fills it. A window you
#  sized yourself, or one hanging a few pixels over an edge, must be left
#  exactly where you put it - a browser that quietly re-sizes or re-positions
#  its own windows every time you click into them is worse than the bug.
_FIT_SLACK = 40          # px a window may exceed the screen before we step in


def fit_to_screen(widget, move_back=True):
    """Shrink `widget` to the screen it sits on if it is bigger than that
    screen. With move_back, also pull it back on-screen if it pokes out."""
    try:
        if widget is None or widget.isMaximized() or widget.isFullScreen():
            return
        scr = QApplication.screenAt(widget.frameGeometry().center()) \
            or QApplication.screenAt(widget.pos()) \
            or QApplication.primaryScreen()
        if scr is None:
            return
        geo = scr.availableGeometry()
        too_wide = widget.width() > geo.width() + _FIT_SLACK
        too_tall = widget.height() > geo.height() + _FIT_SLACK
        if too_wide or too_tall:
            widget.resize(min(widget.width(), geo.width()),
                          min(widget.height(), geo.height()))
        if not move_back:
            return
        x = min(max(widget.x(), geo.left()), max(geo.left(), geo.right() - widget.width()))
        y = min(max(widget.y(), geo.top()), max(geo.top(), geo.bottom() - widget.height()))
        if (x, y) != (widget.x(), widget.y()):
            widget.move(x, y)
    except Exception:
        pass


def install_screen_clamp(app):
    """Shrink any window that takes focus while being bigger than its monitor.

    Deliberately hung on focusWindowChanged rather than an application-wide
    event filter: a filter on QApplication is called for EVERY event of every
    object (mouse moves included), which is a real cost in a browser. This
    fires once per window activation and is free. It only ever RESIZES (and
    only past _FIT_SLACK) - moving a window the user placed themselves is not
    this function's business.
    """
    def _clamp(_win=None):
        try:
            fit_to_screen(QApplication.activeWindow(), move_back=False)
        except Exception:
            pass
    try:
        app.focusWindowChanged.connect(_clamp)
    except Exception:
        pass


# ============================================================================
#  DEL 46 - "I ALREADY HAVE THIS FILE"  (copy-suffix + Backup<CODE>- helpers)
# ----------------------------------------------------------------------------
#  Saving the same program over and over gives Foo.py, Foo (1).py, Foo (2).py...
#  Safe, but it turns into housekeeping. These helpers let a download recognise
#  that "Foo (3).py" IS "Foo.py" arriving again, and let the old copy be kept
#  as Backup<CODE>-Foo.py - the same convention, and the same code pool file,
#  that File_manager's "Backup-rename old" uses.
# ============================================================================
#  1-3 digits only: a copy suffix is small. A 4-digit group is far more likely
#  to be a year - "Report (2024).pdf" must NOT be read as a copy of Report.pdf.
_COPY_SUFFIX_RE   = re.compile(r"^(?P<base>.+?)[ _-]*\((?P<n>\d{1,3})\)$")
_BACKUP_PREFIX_RE = re.compile(r"^Backup[0-9A-Za-z]{3,4}-")
_BACKUP_CHARS     = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"


def strip_copy_suffix(name):
    """'WhyBrowse (3).py' -> 'WhyBrowse.py'.  Returns `name` unchanged when it
    carries no copy suffix, so callers can just compare the two."""
    stem, ext = os.path.splitext(name or "")
    m = _COPY_SUFFIX_RE.match(stem)
    if not m:
        return name
    base = m.group("base").rstrip(" _-")
    return (base + ext) if base else name


def _load_backup_codes():
    try:
        with open(BACKUP_CODES_FILE, "r", encoding="utf-8") as fh:
            data = json.load(fh)
        return data if isinstance(data, dict) else {}
    except FileNotFoundError:
        return {}
    except Exception as e:
        log_line("backup codes: could not read %s (%s)" % (BACKUP_CODES_FILE, e))
        return {}


def _save_backup_codes(data):
    try:
        os.makedirs(os.path.dirname(BACKUP_CODES_FILE), exist_ok=True)
        with open(BACKUP_CODES_FILE, "w", encoding="utf-8") as fh:
            json.dump(data, fh, indent=2, ensure_ascii=False)
    except Exception as e:
        log_line("backup codes: could not write %s (%s)" % (BACKUP_CODES_FILE, e))


def _next_backup_code(used):
    """A random 3-character code (0-9 A-Z) not already used for this filename."""
    for _ in range(2000):
        code = "".join(random.choice(_BACKUP_CHARS) for _ in range(3))
        if code not in used:
            return code
    while True:                                   # pool effectively full: widen
        code = "".join(random.choice(_BACKUP_CHARS) for _ in range(4))
        if code not in used:
            return code


def backup_rename(path):
    """Rename the existing file at `path` to  Backup<CODE>-<name>  in its own
    folder, so the incoming file can take the clean name. Returns the new path,
    or None if it could not be renamed (in which case the caller must NOT
    overwrite - there is nothing protecting the old file)."""
    try:
        folder = os.path.dirname(path)
        # Strip any Backup<CODE>- already on the name so repeated backups of one
        # program share a single code pool instead of nesting prefixes.
        key = _BACKUP_PREFIX_RE.sub("", os.path.basename(path))
        codes = _load_backup_codes()
        used = set(codes.get(key, []))
        for _ in range(50):
            code = _next_backup_code(used)
            new_path = os.path.join(folder, "Backup%s-%s" % (code, key))
            if not os.path.exists(new_path):
                break
            used.add(code)                        # on disk but not in the json
        else:
            return None
        os.rename(path, new_path)
        codes.setdefault(key, [])
        if code not in codes[key]:
            codes[key].append(code)
        _save_backup_codes(codes)
        log_line("backup-rename: %s -> %s" % (path, new_path))
        return new_path
    except Exception as e:
        log_line("backup-rename FAILED for %s: %s" % (path, e))
        return None


def _title_has_unread_count(title):
    """True if a page title carries an unread-message count like '(3) WhatsApp'
    or '(12) Messenger'. The parenthesised part must be ALL digits and > 0, so
    titles like '(beta) Foo' never trigger a notification."""
    t = (title or "").lstrip()
    if t.startswith("(") and ")" in t:
        inside = t[1:t.index(")")].strip()
        return inside.isdigit() and int(inside) > 0
    return False


def make_glyph_icon(ch, color="#9aa6bf", size=16):
    """Build a small QIcon from a single character/emoji, drawn in `color`.
    Used for inline QLineEdit actions (e.g. the address-bar select-all icon)."""
    try:
        pm = QPixmap(size, size)
        pm.fill(Qt.GlobalColor.transparent)
        p = QPainter(pm)
        p.setRenderHint(QPainter.RenderHint.Antialiasing)
        f = QFont("Segoe UI Emoji")
        f.setPixelSize(size - 2)
        p.setFont(f)
        p.setPen(QColor(color))
        p.drawText(pm.rect(), Qt.AlignmentFlag.AlignCenter, ch)
        p.end()
        return QIcon(pm)
    except Exception:
        return QIcon()


def set_default_browser_windows():
    """Register WhyBrowse as the default browser on Windows by writing the
    required registry keys under HKCU (no UAC prompt needed).

    What we register:
      • HKCU\\Software\\Classes\\WhyBrowse  — the ProgID with open command
      • HKCU\\Software\\RegisteredApplications\\WhyBrowse  — makes it show up
        in "Default apps"

    We deliberately DO NOT write the per-scheme UserChoice keys: Windows 8+
    hash-protects them, so writing them directly raises "Access is denied"
    (error 5) and aborts the whole registration. Instead the final "make it the
    default" pick is left to the user in Windows Settings → Default apps (the
    caller opens that page automatically right after this returns).

    Returns (ok: bool, message: str).
    """
    if platform.system() != "Windows":
        return False, "Only supported on Windows."

    try:
        import winreg
    except ImportError:
        return False, "winreg not available."

    try:
        # Build the open command:  python.exe "<script>" "%1"
        # For a frozen .exe it's just the exe itself.
        if getattr(sys, "frozen", False):
            launch_cmd = '"{}" "%1"'.format(sys.executable)
        else:
            launch_cmd = '"{}" "{}" "%1"'.format(sys.executable,
                                                  os.path.abspath(__file__))

        icon = ico_path() or ""

        # ── 1. Register the ProgID under HKCU\Software\Classes\WhyBrowse ────
        progid = "WhyBrowse"
        base = r"Software\Classes\{}".format(progid)

        def set_val(key_path, name, value):
            with winreg.CreateKeyEx(winreg.HKEY_CURRENT_USER, key_path,
                                    0, winreg.KEY_SET_VALUE) as k:
                winreg.SetValueEx(k, name, 0, winreg.REG_SZ, value)

        set_val(base, "",            APP_NAME)
        set_val(base, "FriendlyTypeName", APP_NAME + " HTML Document")
        if icon:
            set_val(base + r"\DefaultIcon", "", icon + ",0")
        set_val(base + r"\shell\open\command", "", launch_cmd)

        # Capabilities sub-key (required for RegisteredApplications)
        caps = base + r"\Capabilities"
        set_val(caps, "ApplicationName",        APP_NAME)
        set_val(caps, "ApplicationDescription", APP_TAGLINE)
        set_val(caps + r"\StartMenu",  "StartMenuInternet", APP_NAME)
        for scheme in ("http", "https"):
            set_val(caps + r"\URLAssociations",  scheme, progid)
        for ext in (".htm", ".html"):
            set_val(caps + r"\FileAssociations", ext,    progid)

        # ── 2. Tell Windows this app is registered ────────────────────────────
        set_val(r"Software\RegisteredApplications",
                APP_NAME,
                base + r"\Capabilities")

        # ── 3. Register as a StartMenuInternet client ─────────────────────────
        #  This is the CLASSIC "I am a web browser" registration. Without it,
        #  some Windows builds never offer the app in the http/https picker at
        #  all (which looks like "nothing is associated" when you click a link
        #  in Thunderbird). All under HKCU, so no admin/UAC prompt is needed.
        smi = r"Software\Clients\StartMenuInternet\{}".format(progid)
        set_val(smi, "", APP_NAME)
        if icon:
            set_val(smi + r"\DefaultIcon", "", icon + ",0")
        # StartMenuInternet's open command launches the browser itself (no URL).
        if getattr(sys, "frozen", False):
            plain_cmd = '"{}"'.format(sys.executable)
        else:
            plain_cmd = '"{}" "{}"'.format(sys.executable, os.path.abspath(__file__))
        set_val(smi + r"\shell\open\command", "", plain_cmd)
        set_val(smi + r"\Capabilities", "ApplicationName",        APP_NAME)
        set_val(smi + r"\Capabilities", "ApplicationDescription", APP_TAGLINE)
        if icon:
            set_val(smi + r"\Capabilities", "ApplicationIcon",    icon + ",0")
        set_val(smi + r"\Capabilities\StartMenu", "StartMenuInternet", progid)
        for scheme in ("http", "https"):
            set_val(smi + r"\Capabilities\URLAssociations",  scheme, progid)
        for ext in (".htm", ".html"):
            set_val(smi + r"\Capabilities\FileAssociations", ext,    progid)
        # And point RegisteredApplications at this client's Capabilities too.
        set_val(r"Software\RegisteredApplications",
                APP_NAME + " Browser",
                smi + r"\Capabilities")

        # NOTE: We intentionally STOP here. The per-scheme UserChoice keys
        # (…\FileExts\{ext}\UserChoice and …\UrlAssociations\{scheme}\UserChoice)
        # are hash-protected on Windows 8+; writing them directly fails with
        # "Access is denied" (error 5). The user makes the final pick in
        # Settings → Default apps, which the caller opens automatically.

        return True, (
            "WhyBrowse is now registered as a browser.\n"
            "FINISH IN WINDOWS (required — Windows won't let an app force this "
            "itself): in the Settings page that just opened, set the default for "
            "HTTP, HTTPS (and .htm/.html) to WhyBrowse. On Windows 11 you may "
            "need to search 'WhyBrowse' under each of those.\n"
            "After that, a link you click (e.g. in Thunderbird) opens in the "
            "WhyBrowse that is ALREADY running (new tab, profile 1) instead of "
            "starting a second copy. If none is running, it launches one."
        )

    except Exception as exc:
        return False, "Registry error: {}".format(exc)


# ============================================================================
#  DEL 07 - URL HELPERS  (smart "is this a URL or a search?")
# ============================================================================
def looks_like_url(text):
    t = text.strip()
    if not t:
        return False
    if " " in t:
        return False
    if t.startswith(("http://", "https://", "file://", "about:")):
        return True
    if t.startswith("localhost") or t.startswith("127.0.0.1"):
        return True
    # something.tld  (a dot, no spaces, and a plausible end)
    if "." in t and not t.endswith("."):
        return True
    return False


def pretty_target(url):
    """A saved shortcut's target written the way you would type it: no
    scheme, no www. 'https://www.imdb.com/find/?q=x' -> 'imdb.com/find/?q=x'."""
    s = (url or "").strip()
    for p in ("https://", "http://"):
        if s.lower().startswith(p):
            s = s[len(p):]
            break
    if s.lower().startswith("www."):
        s = s[4:]
    return s


def is_root_target(url):
    """True when a shortcut points at a site's FRONT PAGE and nothing deeper.

    This is the only case in which completing a typed keyword to the bare host
    tells the truth. For anything deeper - a search page, an inbox, one
    spreadsheet - the host is a different place than the shortcut, and writing
    it into the box makes the shortcut resolve to the host instead (see
    _keyword_inline_suggest, which is where that bug lived)."""
    p = pretty_target(url)
    if "?" in p or "#" in p:
        return False
    rest = p.split("/", 1)[1] if "/" in p else ""
    return rest.strip("/") == ""


def normalize_url(text, search_template):
    t = text.strip()
    if looks_like_url(t):
        if t.startswith(("http://", "https://", "file://", "about:")):
            return QUrl(t)
        return QUrl("https://" + t)
    # treat as a search query
    from urllib.parse import quote_plus
    return QUrl(search_template.format(quote_plus(t)))


# ============================================================================
#  DEL 07B - PRIVACY, BLOCKING, SPOOFING AND THE BLANK NEW-TAB PAGE
# ============================================================================

# ---- City presets for location spoofing (lat, lon) ----
CITY_PRESETS = {
    "Stockholm":  (59.3293, 18.0686),
    "Gothenburg": (57.7089, 11.9746),
    "Malmo":      (55.6050, 13.0038),
    "Oslo":       (59.9139, 10.7522),
    "Copenhagen": (55.6761, 12.5683),
    "Helsinki":   (60.1699, 24.9384),
    "London":     (51.5074, -0.1278),
    "Berlin":     (52.5200, 13.4050),
    "Amsterdam":  (52.3676, 4.9041),
    "Paris":      (48.8566, 2.3522),
    "New York":   (40.7128, -74.0060),
    "Los Angeles":(34.0522, -118.2437),
    "Tokyo":      (35.6762, 139.6503),
}

# ---- Built-in ad / tracker domains (the user can add more in Settings) ----
DEFAULT_ADBLOCK = [
    # ── Big ad networks / analytics ────────────────────────────────────────
    "doubleclick.net", "googlesyndication.com", "google-analytics.com",
    "googletagmanager.com", "googletagservices.com", "adservice.google.com",
    "adnxs.com", "amazon-adsystem.com", "scorecardresearch.com",
    "criteo.com", "criteo.net", "taboola.com", "outbrain.com",
    "pubmatic.com", "rubiconproject.com", "openx.net", "casalemedia.com",
    "moatads.com", "2mdn.net", "doubleverify.com", "quantserve.com",
    "adsrvr.org", "bidswitch.net", "smartadserver.com", "zedo.com",
    "advertising.com", "yieldmo.com", "teads.tv", "sharethrough.com",
    # ── More programmatic ad exchanges / SSPs ──────────────────────────────
    "adform.net", "adroll.com", "mathtag.com", "bluekai.com", "demdex.net",
    "everesttech.net", "serving-sys.com", "flashtalking.com", "rlcdn.com",
    "agkn.com", "crwdcntrl.net", "tapad.com", "exelator.com", "eyeota.net",
    "indexww.com", "33across.com", "contextweb.com", "sonobi.com",
    "triplelift.com", "yieldlab.net", "improvedigital.com", "gumgum.com",
    "districtm.io", "smaato.net", "adsafeprotected.com", "adingo.jp",
    # ── Mobile / app trackers & attribution ────────────────────────────────
    "applovin.com", "inmobi.com", "mopub.com", "chartboost.com",
    "unityads.unity3d.com", "vungle.com", "adcolony.com", "appsflyer.com",
    "adjust.com", "kochava.com", "branch.io", "braze.com",
    # ── Behaviour / session trackers ───────────────────────────────────────
    "hotjar.com", "mouseflow.com", "fullstory.com", "crazyegg.com",
    "addthis.com", "sharethis.com", "quantcast.com", "clarity.ms",
    # ── Push-notification spam ─────────────────────────────────────────────
    "onesignal.com", "pushengage.com", "pushcrew.com", "izooto.com",
    # ── Content-spam / "chumbox" / clickbait widgets ───────────────────────
    "revcontent.com", "mgid.com", "content.ad", "zergnet.com",
    "plista.com", "dianomi.com", "engageya.com", "adskeeper.com",
    # ── Pop-under / malvertising junk (the real "skit-domäner") ────────────
    "popads.net", "popcash.net", "propellerads.com", "propellerclick.com",
    "adsterra.com", "exoclick.com", "exosrv.com", "juicyads.com",
    "trafficjunky.com", "hilltopads.net", "clickadu.com", "admaven.com",
    "mybetterdeals.net", "trafficstars.com", "ad-maven.com", "adnium.com",
    "poptm.com", "onclickads.net", "adcash.com", "clksite.com",
]


# ---- The blank-but-useful new-tab page (lets you choose where to start) ----
NEW_TAB_HTML = """<!doctype html><html><head><meta charset="utf-8">
<title>New Tab</title>
<style>
  html,body{height:100%;margin:0;background:__BG__;color:__FG__;
    font-family:'Segoe UI',Arial,sans-serif;}
  .wrap{height:100%;display:flex;flex-direction:column;align-items:center;
    justify-content:center;}
  .logo{font-size:46px;font-weight:bold;color:__ACCENT__;margin-bottom:4px;}
  .tag{opacity:.55;font-size:13px;margin-bottom:26px;}
  form{width:min(620px,80vw);}
  input{width:100%;box-sizing:border-box;padding:14px 20px;font-size:16px;
    border-radius:26px;border:1px solid __BORDER__;background:__FIELD__;color:__FG__;
    outline:none;caret-color:__ACCENT__;}
  input:focus{border-color:__ACCENT__;}
  .hint{opacity:.4;font-size:12px;margin-top:14px;}
</style></head><body>
<div class="wrap">
  <div class="logo">WhyBrowse</div>
  <div class="tag">Type an address or search the web</div>
  <form onsubmit="return go(event)">
    <input id="q" autocomplete="off" placeholder="Search or enter address" autofocus>
  </form>
  <div class="hint">Press Enter to go &middot; this is your blank start page</div>
</div>
<script>
  var T = __SEARCH__;
  function go(e){
    e.preventDefault();
    var q = document.getElementById('q').value.trim();
    if(!q) return false;
    var url;
    if(q.indexOf(' ')<0 && q.indexOf('.')>0){
      url = (q.indexOf('http')===0) ? q : 'https://'+q;
    } else {
      url = T.replace('{}', encodeURIComponent(q));
    }
    location.href = url; return false;
  }
  window.addEventListener('load', function(){ document.getElementById('q').focus(); });
</script>
</body></html>"""


def write_new_tab_page(search_template):
    """Write the local blank new-tab page, baking in search engine + theme."""
    try:
        html = (NEW_TAB_HTML
                .replace("__SEARCH__", json.dumps(search_template))
                .replace("__BG__", C_NEWTAB_BG)
                .replace("__FG__", C_NEWTAB_FG)
                .replace("__ACCENT__", C_ACCENT)
                .replace("__BORDER__", C_BORDER)
                .replace("__FIELD__", C_ADDR_BG))
        with open(NEWTAB_FILE, "w", encoding="utf-8") as f:
            f.write(html)
    except Exception as e:
        log_line("write_new_tab_page failed: {}".format(e))


def new_tab_url():
    return QUrl.fromLocalFile(NEWTAB_FILE)


def is_blank_page(url_str):
    """True for our blank new-tab page or about:blank (so the address bar is empty)."""
    if not url_str or url_str in ("about:blank",):
        return True
    try:
        return url_str.startswith(new_tab_url().toString())
    except Exception:
        return False


def is_dead_restore_url(url_str):
    """True for a session-expired auth/IdP ERROR page that must never be saved
    into last_tabs nor restored on startup.

    The reported case: Inera's login IdP redirects an expired session to
    'https://idp.invanar-idp.inera.se/_error?status=412&...&message=No HTTP
    session'. That error address then gets stored as an open tab, so every
    restart reopens it — and it can never recover, because the HTTP session it
    needs is long gone. Left alone it multiplies across profiles. We detect the
    whole family (any '/_error' interstitial carrying an HTTP status, any 'No
    HTTP session' complaint, and Inera IdP error pages by host) and drop it."""
    if not url_str or not isinstance(url_str, str):
        return False
    try:
        from urllib.parse import unquote_plus
        qu   = QUrl(url_str)
        path = (qu.path() or "").lower()
        host = (qu.host() or "").lower()
        q    = unquote_plus(qu.query() or "").lower()
        # 1) An "_error" interstitial that carries an HTTP status code.
        if path.endswith("/_error") and "status=" in q:
            return True
        # 2) Any IdP page whose error text says the session is gone.
        if "no http session" in q:
            return True
        # 3) Inera identity-provider error pages, by host, to be safe.
        if host.endswith("inera.se") and path.endswith("/_error"):
            return True
    except Exception:
        return False
    return False


def _saved_tab_url(item):
    """The URL string out of a saved-tab entry, which may be a dict (current
    format) or a bare URL string (legacy). Used to vet entries before restore."""
    if isinstance(item, dict):
        return item.get("pin_url") if (item.get("pinned") and item.get("pin_url")) \
            else item.get("url")
    return item if isinstance(item, str) else None


# ---- Geocoding: turn a typed city/address into lat/lon (OpenStreetMap) ----
def geocode_place(query):
    """Return (lat, lon, display_name) for a place name, or None on failure."""
    import urllib.request
    import urllib.parse
    try:
        url = "https://nominatim.openstreetmap.org/search?" + urllib.parse.urlencode(
            {"q": query, "format": "json", "limit": 1})
        req = urllib.request.Request(
            url, headers={"User-Agent": "WhyBrowse/1.0 (location lookup)"})
        with urllib.request.urlopen(req, timeout=6) as r:
            data = json.loads(r.read().decode("utf-8"))
        if data:
            d = data[0]
            return float(d["lat"]), float(d["lon"]), d.get("display_name", query)
    except Exception as e:
        log_line("geocode failed for {!r}: {}".format(query, e))
    return None


# ---- Bookmark tree helpers ----------------------------------------------
# A bookmark store is {"bar": [nodes], "menu": [nodes]}.
# A node is a link {"title","url"} or a folder {"title","folder":[nodes]}.
def normalize_bookmarks(data):
    """Accept the new tree, or migrate an old flat list, into the tree form."""
    if isinstance(data, dict) and ("bar" in data or "menu" in data):
        return {"bar": data.get("bar") or [], "menu": data.get("menu") or []}
    if isinstance(data, list):                       # old flat [{url,title,bar}]
        bar = [{"title": b.get("title") or b.get("url", ""), "url": b["url"]}
               for b in data if b.get("bar") and b.get("url")]
        menu = [{"title": b.get("title") or b.get("url", ""), "url": b["url"]}
                for b in data if b.get("url")]
        return {"bar": bar, "menu": menu}
    return {"bar": [], "menu": []}


def bookmark_flatten(nodes, prefix=""):
    """Flatten a node list to [{title(with folder path), url}] (links only)."""
    out = []
    for n in nodes or []:
        if "folder" in n:
            out.extend(bookmark_flatten(n.get("folder", []),
                                        prefix + (n.get("title", "") + " / ")))
        elif n.get("url"):
            out.append({"title": prefix + (n.get("title") or n["url"]), "url": n["url"]})
    return out


# ---- Find the user's ACTIVE Firefox profile (not a stale/empty one) ----
def firefox_places_path():
    """Return places.sqlite for the active Firefox profile, or None."""
    import configparser
    appdata = os.environ.get("APPDATA", "")
    ff = os.path.join(appdata, "Mozilla", "Firefox")
    chosen = None
    try:
        cp = configparser.ConfigParser()
        cp.read(os.path.join(ff, "profiles.ini"))
        # 1) the profile flagged Default=1 in profiles.ini
        for s in cp.sections():
            if s.lower().startswith("profile") and cp[s].get("default", "0") == "1":
                chosen = cp[s].get("path")
        # 2) otherwise the install's locked default
        if not chosen and os.path.isfile(os.path.join(ff, "installs.ini")):
            ci = configparser.ConfigParser()
            ci.read(os.path.join(ff, "installs.ini"))
            for s in ci.sections():
                if ci[s].get("default"):
                    chosen = ci[s].get("default")
                    break
    except Exception as e:
        log_line("profiles.ini parse failed: {}".format(e))
    if chosen:
        p = os.path.join(ff, chosen.replace("/", os.sep), "places.sqlite")
        if os.path.isfile(p):
            return p
    # 3) last resort: the largest places.sqlite (most-used profile)
    cands = glob.glob(os.path.join(ff, "Profiles", "*", "places.sqlite"))
    if cands:
        cands.sort(key=lambda p: -os.path.getsize(p))
        return cands[0]
    return None


# ---- Firefox cookie import: bring a Google sign-in across (DEL 50) ----------
# WHY THIS EXISTS. Google's sign-in refuses browsers it judges to be embedded
# ("Couldn't sign you in - this browser or app may not be secure"), and no amount
# of matching Chrome's fingerprint is guaranteed to satisfy it: it is a moving
# target we do not control. But a profile that is ALREADY signed in stays signed
# in (we force persistent cookies), which is exactly why five profiles here work
# and only the newest one cannot get in. So: skip the sign-in entirely and carry
# the finished session over from Firefox, whose cookie store is a plain, readable
# SQLite file. Chrome and Edge are deliberately NOT offered - since Chrome 127
# their cookies are sealed with app-bound encryption that only the browser's own
# elevation service can open.
FF_COOKIE_HOSTS = ("google.com", "youtube.com")


def html_escape(s):
    return (str(s).replace("&", "&amp;").replace("<", "&lt;")
            .replace(">", "&gt;").replace('"', "&quot;"))


def firefox_profile_list():
    """[(label, folder)] for every Firefox profile that HAS a cookie store,
    newest cookie file first (the one he actually browses with)."""
    import configparser
    appdata = os.environ.get("APPDATA", "")
    ff = os.path.join(appdata, "Mozilla", "Firefox")
    names, default = {}, None
    try:
        cp = configparser.ConfigParser()
        cp.read(os.path.join(ff, "profiles.ini"))
        for s in cp.sections():
            if not s.lower().startswith("profile"):
                continue
            path = (cp[s].get("path") or "").replace("/", os.sep)
            if not path:
                continue
            full = path if os.path.isabs(path) else os.path.join(ff, path)
            names[os.path.normcase(full)] = cp[s].get("name") or os.path.basename(full)
            if cp[s].get("default", "0") == "1":
                default = os.path.normcase(full)
    except Exception as e:
        log_line("profiles.ini parse failed (cookies): {}".format(e))
    out = []
    for db in glob.glob(os.path.join(ff, "Profiles", "*", "cookies.sqlite")):
        folder = os.path.dirname(db)
        key = os.path.normcase(folder)
        label = names.get(key, os.path.basename(folder))
        if key == default:
            label += "  (Firefox's default)"
        out.append((label, folder, os.path.getmtime(db)))
    out.sort(key=lambda r: -r[2])
    return [(lbl, folder) for lbl, folder, _m in out]


def read_firefox_cookies(profile_dir, hosts=FF_COOKIE_HOSTS):
    """Cookies for `hosts` out of a Firefox profile, as plain dicts.

    Only the DEFAULT cookie jar is read: rows carrying originAttributes (a
    Container tab, or a partitioned third-party cookie) belong to a jar that has
    no counterpart here, and copying them over would mix two different logins."""
    src = os.path.join(profile_dir, "cookies.sqlite")
    if not os.path.isfile(src):
        return []
    tmp = os.path.join(tempfile.gettempdir(),
                       "whybrowse_ffcookies_%d.sqlite" % os.getpid())
    rows = []
    try:
        shutil.copy2(src, tmp)                     # Firefox locks the live file
        for extra in ("-wal", "-shm"):             # ...and may hold recent writes here
            if os.path.isfile(src + extra):
                try: shutil.copy2(src + extra, tmp + extra)
                except Exception: pass
        con = sqlite3.connect(tmp)
        # The schema is NOT the same in every profile. His oldest ones (2013)
        # have no `sameSite` column and no `originAttributes` at all, and asking
        # for a column that is not there fails the whole query - which quietly
        # reported those profiles as holding nothing rather than as unreadable.
        have = set(r[1] for r in con.execute("PRAGMA table_info(moz_cookies)"))
        need = ["host", "name", "value", "path", "expiry", "isSecure", "isHttpOnly"]
        missing = [c for c in need if c not in have]
        if missing:
            raise RuntimeError("unexpected cookie table (no %s)" % ", ".join(missing))
        cols = list(need) + [c for c in ("sameSite",) if c in have]
        where = " OR ".join(["host = ? OR host LIKE ?"] * len(hosts))
        sql = "SELECT %s FROM moz_cookies WHERE " % ", ".join(cols)
        if "originAttributes" in have:
            sql += "originAttributes = '' AND "
        args = []
        for h in hosts:
            args += [h, "%." + h]
        for rec in con.execute(sql + "(%s)" % where, args):
            row = dict(zip(cols, rec))
            rows.append({"host": row["host"], "name": row["name"],
                         "value": row["value"], "path": row["path"] or "/",
                         "expiry": row["expiry"], "secure": bool(row["isSecure"]),
                         "httponly": bool(row["isHttpOnly"]),
                         "samesite": row.get("sameSite", 0x100)})
        con.close()
    except Exception as e:
        log_line("Firefox cookie read failed: {}".format(e))
        raise
    finally:
        for p in (tmp, tmp + "-wal", tmp + "-shm"):
            if os.path.isfile(p):
                try: os.remove(p)
                except Exception: pass
    return rows


# The cookies that ARE the Google session. Used only to tell him honestly
# whether the Firefox profile he picked is actually signed in, instead of
# importing 26 harmless preference cookies and reporting success.
GOOGLE_SESSION_COOKIES = ("SID", "HSID", "SSID", "LSID", "APISID", "SAPISID",
                          "__Secure-1PSID", "__Secure-3PSID")


def firefox_cookie_to_qt(row):
    """One moz_cookies row -> QNetworkCookie, plus the origin URL to set it on.

    Two details that decide whether Chromium accepts the cookie at all:
      * a `__Host-` cookie MUST be host-only, so a Domain attribute is fatal -
        Firefox stores host-only cookies WITHOUT a leading dot, and we mirror
        that by not calling setDomain() for them at all;
      * expiry is in MILLISECONDS in current Firefox (measured 2026-09-01:
        SID expired at 1821170154070 = 2027-09-17), while older versions stored
        seconds. Decide by magnitude rather than by version.
    """
    host = row["host"]
    c = QNetworkCookie(row["name"].encode("utf-8"), row["value"].encode("utf-8"))
    c.setPath(row["path"])
    c.setSecure(row["secure"])
    c.setHttpOnly(row["httponly"])
    if host.startswith("."):
        c.setDomain(host)                          # domain cookie (.google.com)
    exp = row.get("expiry") or 0
    if exp:
        secs = exp / 1000.0 if exp > 10 ** 11 else float(exp)
        try:
            c.setExpirationDate(QDateTime.fromSecsSinceEpoch(int(secs)))
        except Exception:
            pass
    # Firefox 128+ packs "was it set explicitly" into the high bits; the low
    # byte is the value (0 None, 1 Lax, 2 Strict) and 0x100 means "unset", which
    # must stay unset so Chromium applies its own Lax-by-default.
    try:
        raw = int(row.get("samesite") or 0)
        if not (raw & 0x100):
            c.setSameSitePolicy({0: QNetworkCookie.SameSite.None_,
                                 1: QNetworkCookie.SameSite.Lax,
                                 2: QNetworkCookie.SameSite.Strict}
                                .get(raw & 0xFF, QNetworkCookie.SameSite.Default))
    except Exception:
        pass
    origin = "https://%s%s" % (host.lstrip("."), row["path"] or "/")
    return c, QUrl(origin)


# ---- Login / SSO pages that must NOT be blocked (need cross-domain cookies &
#      resources to render and work; blocking them breaks Google/Microsoft etc.) ----
LOGIN_DOMAINS = [
    "accounts.google.com", "accounts.youtube.com", "login.microsoftonline.com",
    "login.live.com", "login.microsoft.com", "appleid.apple.com",
    "login.yahoo.com", "auth.login.yahoo.co.jp", "signin.aws.amazon.com",
    "secure.login.gov", "id.atlassian.com", "github.com/login",
    "login.okta.com", "auth0.com", "facebook.com/login", "bankid.com",
    "accounts.epicgames.com",
]


def is_login_host(host):
    if not host:
        return False
    host = host.lower()
    return any(host == d or host.endswith("." + d) for d in
               (d.split("/")[0] for d in LOGIN_DOMAINS))


# ---- Identity / SSO ecosystems whose cookies must flow cross-site or their
#      sign-in breaks (e.g. Google's login renders skewed when these are blocked) ----
IDENTITY_DOMAINS = [
    "google.com", "googleapis.com", "gstatic.com", "googleusercontent.com",
    "youtube.com", "ggpht.com", "accounts.google.com",
    "microsoftonline.com", "microsoft.com", "live.com", "office.com", "azure.com",
    "apple.com", "icloud.com", "okta.com", "auth0.com", "onelogin.com",
    "duosecurity.com", "gmail.com",
    # Epic Games login flow loops on "Please refresh" when its cookies are
    # blocked — let them flow (its bot-check needs a consistent session).
    "epicgames.com", "epicgames.dev", "unrealengine.com", "hcaptcha.com",
    # Arkose Labs (formerly "FunCaptcha") - the actual human-verification
    # widget Epic Games AND OpenAI/ChatGPT sign-up both run, served from ITS
    # OWN domain in an iframe. Without this, its session cookie counts as
    # third-party and gets blocked, so the widget can't track which puzzle
    # it showed you or tally your answer - puzzle pieces fail to load and
    # every attempt comes back rejected, regardless of what you click. This
    # only lets the CAPTCHA's own legitimate cookie flow so it can verify a
    # real human normally; it doesn't change or skip the challenge itself.
    "arkoselabs.com", "funcaptcha.com",
]


def is_identity_host(host):
    if not host:
        return False
    host = host.lower()
    return any(host == d or host.endswith("." + d) for d in IDENTITY_DOMAINS)


# ---- Payment / checkout hosts: never block requests or apply cosmetic hiding
#      here. Aggressive ad-block or nag/freeze CSS can wipe out a payment QR code
#      (e.g. the Swish QR on amazon.se checkout — user had to switch to Firefox).
PAYMENT_DOMAINS = [
    "amazon.se", "amazon.com", "amazon.co.uk", "amazon.de",
    "swish.nu", "getswish.se", "klarna.com", "klarna.net",
    "paypal.com", "paypalobjects.com", "stripe.com", "adyen.com",
    "checkout.stripe.com", "trustly.com", "verifone.com", "nets.eu",
]

# ---- Merchant hosts whose CHECKOUT lives on the SAME hostname as the rest of the
#      shop. Unlike the payment PROVIDERS above (klarna.com, adyen.com …) whose
#      whole domain is payment, a shop like sellpy.se is only a "payment page" on
#      its /checkout* path. The cosmetic exemption (never freeze / never hide
#      nags) must be scoped to those paths so it does NOT wipe out the rest of the
#      site. Format: (host, (path_prefix, path_prefix, …)). Matched host+path.
#      NOTE: this is the cosmetic (freeze/nag) source of truth only. The cookie
#      filter (is_payment_host / PAYMENT_DOMAINS) is a separate concern and must
#      not be widened with these merchant hosts.
PAYMENT_PATH_HOSTS = [
    ("sellpy.se", ("/checkout",)),
]


# ---- Human-verification ("Verify you are human") providers ------------------
# Cloudflare Turnstile / the "Just a moment…" interstitial, hCaptcha, reCAPTCHA,
# Arkose, DataDome and PerimeterX all run their widget in an IFRAME served from
# their OWN domain, and they all need three things to work:
#   1. their own cookie (which is THIRD-PARTY relative to the site you visit),
#   2. every one of their scripts/beacons to actually reach the network, and
#   3. an untouched page (no frozen animations, no cosmetic hiding).
# Block any of those and the check can never pass - you click the box, it spins,
# and you land right back on "Verify you are human" forever. That is exactly what
# happened on predb.me. These hosts are therefore ALWAYS exempt from the cookie
# filter, from the ad-blocker and from the cosmetic scripts. This only lets the
# check run normally - it does not solve, skip or fake the challenge.
# HOSTS ONLY - no paths. A path-style entry ("google.com/recaptcha") would be
# matched host-first and quietly exempt the WHOLE of google.com, which is far
# wider than intended. reCAPTCHA on www.google.com/recaptcha is already covered
# for cookies by IDENTITY_DOMAINS and is not on the ad-block list.
CHALLENGE_DOMAINS = [
    "challenges.cloudflare.com", "cloudflare.com", "cloudflareinsights.com",
    "turnstile.com",
    "hcaptcha.com", "hcaptcha.net",
    "recaptcha.net",
    "arkoselabs.com", "funcaptcha.com",
    "datadome.co", "captcha-delivery.com",
    "perimeterx.net", "px-cdn.net", "px-cloud.net",
    "geetest.com", "friendlycaptcha.com",
]


def is_challenge_host(host):
    if not host:
        return False
    host = host.lower()
    return any(host == d or host.endswith("." + d) for d in CHALLENGE_DOMAINS)


def is_payment_host(host):
    if not host:
        return False
    host = host.lower()
    return any(host == d or host.endswith("." + d) for d in PAYMENT_DOMAINS)


def clean_host(text):
    """Reduce any user-typed domain or full URL to a bare lower-case host.
    'https://www.Tradera.com/login?x=1' -> 'tradera.com'.  This is what the
    password vault stores/matches on, so autofill works no matter how the
    user typed the site in."""
    s = (text or "").strip().lower()
    if "://" in s:
        s = s.split("://", 1)[1]
    s = s.split("/", 1)[0]          # drop any /path
    s = s.split("?", 1)[0]          # drop ?query
    s = s.split("#", 1)[0]          # drop #fragment
    s = s.split("@")[-1]            # drop any user:pass@
    s = s.split(":", 1)[0]          # drop :port
    if s.startswith("www."):
        s = s[4:]
    return s.strip()


# ---- Registered-domain ("same site") test — used by Lock level 4 ("3+") -----
# Second-level public suffixes where the registered domain is the LAST THREE
# labels (e.g. bbc.co.uk), not two. A small pragmatic list covering the ccTLDs
# an ordinary user actually meets; anything unlisted falls back to two labels.
# (A full Public Suffix List would be overkill for a same-domain tab rule.)
_MULTI_TLDS = {
    "co.uk", "org.uk", "gov.uk", "ac.uk", "me.uk", "ltd.uk", "plc.uk",
    "com.au", "net.au", "org.au", "co.nz", "co.za", "com.br", "co.jp",
    "co.in", "co.kr", "com.tr", "com.mx", "com.sg", "com.hk", "com.cn",
}


def base_domain(host):
    """Registered domain of a host: 'www.tradera.com' -> 'tradera.com',
    'shop.api.tradera.com' -> 'tradera.com', 'bbc.co.uk' -> 'bbc.co.uk'.
    A pragmatic eTLD+1 without the full Public Suffix List. A bare IP or an
    already-short host is returned unchanged."""
    h = (host or "").strip().lower().strip(".")
    if not h or h.replace(".", "").isdigit():        # empty or a bare IPv4
        return h
    parts = h.split(".")
    if len(parts) <= 2:
        return h
    last2 = ".".join(parts[-2:])
    if last2 in _MULTI_TLDS:
        return ".".join(parts[-3:])
    return last2


def domain_scopes(host):
    """Every address a block can be aimed at, most specific first, ending at the
    registered domain: 'adress.hk-r.se' -> ['adress.hk-r.se', 'hk-r.se'] and
    'a.b.hk-r.se' -> ['a.b.hk-r.se', 'b.hk-r.se', 'hk-r.se']. The list stops at
    the registered domain on purpose - 'se' or 'co.uk' as a block would take a
    whole country with it. A bare IP, or an address that is already the
    registered domain, gives just itself."""
    h = clean_host(host)
    if not h:
        return []
    floor = base_domain(h)
    if not floor or h == floor or not h.endswith("." + floor):
        return [h]
    out, cur = [h], h
    while cur != floor and "." in cur:
        cur = cur.split(".", 1)[1]
        out.append(cur)
        if cur == floor:
            break
    return out


def absorb_domain(lst, domain):
    """Add `domain` to a block list the way a person means it: it is a no-op if
    an entry already covers it, and it SWALLOWS the narrower entries it now
    covers (adding hk-r.se removes adress.hk-r.se, hittat.hk-r.se...), so the
    list does not keep three lines that one line says. Returns (changed,
    number_swallowed); `lst` is edited in place."""
    d = (domain or "").strip().lower().lstrip(".")
    if d.startswith("www."):
        d = d[4:]
    if not d:
        return False, 0
    for e in lst:
        e2 = (e or "").strip().lower().lstrip(".")
        if e2.startswith("www."):
            e2 = e2[4:]
        if e2 and (d == e2 or d.endswith("." + e2)):
            return False, 0
    keep = []
    for e in lst:
        e2 = (e or "").strip().lower().lstrip(".")
        if e2.startswith("www."):
            e2 = e2[4:]
        if e2 and e2.endswith("." + d):
            continue
        keep.append(e)
    swallowed = len(lst) - len(keep)
    lst[:] = keep
    lst.append(d)
    return True, swallowed


def same_registered_domain(a, b):
    """True when two hosts belong to the same registered domain (same site).
    'www.tradera.com' and 'shop.tradera.com' are the same site; 'google.com'
    is not."""
    ba, bb = base_domain(a), base_domain(b)
    return bool(ba) and ba == bb


# ============================================================================
#  DEL 07C - PASSWORD VAULT CRYPTO  (Windows DPAPI + optional 4-digit PIN)
#  Layering: encrypt = DPAPI( pin_encrypt(json) if PIN else json )
#  The PIN is never stored; a wrong PIN fails the HMAC tag (returns None).
#  Uses only the Python standard library (hashlib/hmac) - no extra packages.
# ============================================================================
try:
    from ctypes import wintypes as _wt

    class _DATA_BLOB(ctypes.Structure):
        _fields_ = [("cbData", _wt.DWORD), ("pbData", ctypes.POINTER(ctypes.c_char))]
except Exception:
    _wt = None


def _dpapi(data, protect):
    inb = _DATA_BLOB(len(data),
                     ctypes.cast(ctypes.create_string_buffer(data, len(data)),
                                 ctypes.POINTER(ctypes.c_char)))
    outb = _DATA_BLOB()
    fn = (ctypes.windll.crypt32.CryptProtectData if protect
          else ctypes.windll.crypt32.CryptUnprotectData)
    if not fn(ctypes.byref(inb), None, None, None, None, 0, ctypes.byref(outb)):
        raise OSError("DPAPI %s failed" % ("protect" if protect else "unprotect"))
    res = ctypes.string_at(outb.pbData, outb.cbData)
    ctypes.windll.kernel32.LocalFree(outb.pbData)
    return res


def _keystream(key, nonce, n):
    out, ctr = b"", 0
    while len(out) < n:
        out += hmac.new(key, nonce + ctr.to_bytes(4, "big"), hashlib.sha256).digest()
        ctr += 1
    return out[:n]


def _pin_key(pin, salt):
    return hashlib.pbkdf2_hmac("sha256", pin.encode("utf-8"), salt, 150000, 32)


def _pin_encrypt(plaintext, pin):
    salt, nonce = os.urandom(16), os.urandom(16)
    key = _pin_key(pin, salt)
    ct = bytes(a ^ b for a, b in zip(plaintext, _keystream(key, nonce, len(plaintext))))
    tag = hmac.new(key, nonce + ct, hashlib.sha256).digest()
    return b"P1" + salt + nonce + tag + ct


def _pin_decrypt(blob, pin):
    if not blob.startswith(b"P1"):
        return None
    salt, nonce, tag, ct = blob[2:18], blob[18:34], blob[34:66], blob[66:]
    key = _pin_key(pin, salt)
    if not hmac.compare_digest(tag, hmac.new(key, nonce + ct, hashlib.sha256).digest()):
        return None                              # wrong PIN
    return bytes(a ^ b for a, b in zip(ct, _keystream(key, nonce, len(ct))))


def vault_encrypt(obj, pin):
    data = json.dumps(obj, ensure_ascii=False).encode("utf-8")
    if pin:
        data = _pin_encrypt(data, pin)
    return _dpapi(data, True)


def vault_decrypt(blob, pin):
    """Return the dict, or None if a PIN is required/wrong."""
    data = _dpapi(blob, False)
    if data.startswith(b"P1"):                   # this vault was PIN-protected
        if not pin:
            return None
        data = _pin_decrypt(data, pin)
        if data is None:
            return None
    return json.loads(data.decode("utf-8"))


def vault_needs_pin(blob):
    """True if this stored vault was encrypted with a PIN."""
    try:
        return _dpapi(blob, False).startswith(b"P1")
    except Exception:
        return False


# ---- Chrome brand identity for the Sec-CH-UA request headers (DEL 50) -------
# MEASURED 2026-09-01 with QtWebEngine 6.11.1 / Chromium 140: this engine sends
#     User-Agent: ... Chrome/140.0.0.0 Safari/537.36        <- after our cleanup
#     sec-ch-ua:  "Not=A?Brand";v="24", "Chromium";v="140"
# A real Chrome sends a THIRD brand, "Google Chrome", in that same header. So the
# user-agent STRING claimed Chrome while the client hints said plain Chromium -
# a flat contradiction that a server sees on the very first request, before a
# single line of our injected JavaScript has run. That is exactly the shape of
# signal Google's sign-in uses to decide "this browser or app may not be secure",
# and no amount of UA-string polishing could ever reach it.
#
# We therefore rewrite the three Sec-CH-UA headers ourselves. QWebEngineUrlRequestInfo
# can SET a header but cannot READ one back, so the value has to be built from
# scratch - which is why the GREASE brand below is a measured constant rather
# than something we append to. That is safe because the SAME list is handed to
# the injected script (cfg["chBrands"]) and overwrites navigator.userAgentData,
# so the header and the JavaScript can never drift apart, whatever a future Qt
# build would have sent on its own.
QT_GREASE_BRAND = "Not=A?Brand"        # measured; Chromium's deliberate fake brand
QT_GREASE_VER   = "24"

# The Accept-Language header this browser sends, and therefore the list
# navigator.languages reports. QtWebEngine sends NOTHING here unless told
# (measured - see Browser._apply_accept_language), which both looks wrong to a
# server and left navigator.languages as the single-entry ["sv"]. Overridable
# with the "accept_language" setting for anyone who wants English pages.
ACCEPT_LANGUAGE = "sv-SE,sv;q=0.9,en-US;q=0.8,en;q=0.7"


def accept_language_list(header):
    """['sv-SE','sv','en-US','en'] from an Accept-Language header value."""
    out = []
    for part in (header or "").split(","):
        tag = part.split(";")[0].strip()
        if tag and tag != "*" and tag not in out:
            out.append(tag)
    return out


def chrome_brand_list(major, full_version):
    """[(brand, majorVersion, fullVersion)] as a real Chrome would report."""
    maj = str(int(major))
    return [(QT_GREASE_BRAND, QT_GREASE_VER, QT_GREASE_VER + ".0.0.0"),
            ("Chromium", maj, full_version),
            ("Google Chrome", maj, full_version)]


def chrome_high_entropy_hints():
    """The user-agent client hints we can state as FACT about this machine.

    Deliberately short, and only ever used to fill a hint the engine did NOT
    answer. platformVersion is not here on purpose: Chromium derives it from a
    build-number table we would have to duplicate, and a wrong platform version
    is a worse answer than no platform version - the point of this whole feature
    is to stop contradicting ourselves. (Measured: this engine answers
    platformVersion, architecture and bitness on its own anyway.)"""
    arch, bits = "x86", "64"
    try:
        m = (platform.machine() or "").upper()
        if m in ("ARM64", "AARCH64"):
            arch = "arm"
        elif m in ("X86", "I386", "I686"):
            bits = "32"
    except Exception:
        pass
    return {"architecture": arch, "bitness": bits, "model": "",
            "wow64": False, "formFactor": ["Desktop"]}


def chrome_brand_headers(major, full_version):
    """(sec-ch-ua, sec-ch-ua-full-version-list) header values, as bytes."""
    brands = chrome_brand_list(major, full_version)
    short = ", ".join('"%s";v="%s"' % (b, v) for b, v, _f in brands)
    full  = ", ".join('"%s";v="%s"' % (b, f) for b, _v, f in brands)
    return short.encode("utf-8"), full.encode("utf-8")


# *************** DEL 53 - PER-SITE USER AGENT *****************
# A site can be told to see a different browser than the rest of the web does
# (right-click -> Exceptions for <site> -> Browser identity here). Stored as
# site_overrides[host]["user_agent"] (a full UA string; absent = automatic, i.e.
# the global Settings value). Two halves, both driven by that one setting:
#   * the HTTP User-Agent header, set per request in AdblockInterceptor below,
#   * navigator.userAgent & friends, set by the injected script (GEO_SCRIPT,
#     cfg["siteUA"]) so the page and the server tell the same story.
# LIMIT: the Sec-CH-UA client-hint headers cannot be removed from a request by
# the interceptor, so a Firefox identity still carries Chromium's own
# low-entropy hints. Sites that only look at the UA string are fixed by this;
# a site that cross-checks the hints can still tell.
# ToDo: no way yet to give one site its own Accept-Language or to open a single
# tab with an identity without a host exception.
FIREFOX_UA_FALLBACK_MAJOR = 140        # Firefox ESR; used when no install is found


def installed_firefox_major():
    """Major version of the Firefox installed on this PC (0 = not found).

    Read from application.ini next to firefox.exe so the identity we claim is
    one that really exists - a made-up version is one more thing to be wrong."""
    for env in ("ProgramFiles", "ProgramFiles(x86)", "LOCALAPPDATA"):
        base = os.environ.get(env)
        if not base:
            continue
        for sub in ("Mozilla Firefox", os.path.join("Programs", "Mozilla Firefox")):
            ini = os.path.join(base, sub, "application.ini")
            try:
                with open(ini, "r", encoding="utf-8", errors="ignore") as f:
                    for line in f:
                        if line.startswith("Version="):
                            return int(line.split("=", 1)[1].strip().split(".")[0])
            except Exception:
                continue
    return 0


def firefox_user_agent():
    maj = installed_firefox_major() or FIREFOX_UA_FALLBACK_MAJOR
    return ("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:%d.0) "
            "Gecko/20100101 Firefox/%d.0" % (maj, maj))


# *************** DEL 58 - AMAZON GETS THE ENGINE'S OWN IDENTITY *****************
# Lars (2026-11-22): pasting an amazon.se product address needed 2-3 tries before
# the real page came; the other tries gave Amazon's "Ett ovantat fel har
# intraffat" page. MEASURED with a bare QtWebEngine (no WhyBrowse code, no
# cookies, same product page, 8 loads in a row):
#     engine's own user agent ("... QtWebEngine/6.x" kept)  -> 8 of 8 real page
#     the cleaned-up Chrome identity (token removed)         -> 2-3 of 8 real page
#     the same plus our Sec-CH-UA brand fix                  -> 3 of 8 real page
# Amazon's bot filter punishes a "Chrome" that is not quite Chrome, and does not
# mind an honest embedded engine. So these hosts get the engine's untouched UA
# through the per-site identity of DEL 53 (header + navigator.userAgent), and the
# Sec-CH-UA rewrite stands down there (DEL 53 already does that for any site UA).
# An explicit choice in the right-click menu (Browser identity here) always wins.
# ToDo: if another shop shows the same "works 1 time in 3" pattern, add its
# domain here; a checkout that stops working is the sign to take Amazon out again.
ENGINE_UA_DOMAINS = (
    "amazon.se", "amazon.com", "amazon.de", "amazon.co.uk", "amazon.fr",
    "amazon.it", "amazon.es", "amazon.nl", "amazon.pl", "amazon.com.be",
    "amazon.ca", "amazon.com.tr", "amazon.ae", "amazon.sa", "amazon.eg",
    "amazon.in", "amazon.co.jp", "amazon.com.au", "amazon.com.mx",
    "amazon.com.br", "amazon.sg",
)
# NOTE: whole domains, so aws.amazon.com (AWS console) is included. If that ever
# misbehaves, give it its own explicit "Chrome" identity in the right-click menu.


def site_ua_kind(ua):
    """Short name of a user-agent string, for menu labels."""
    ua = (ua or "").strip()
    if not ua:
        return "automatic"
    if "QtWebEngine/" in ua:
        return "engine default"
    if "Firefox/" in ua:
        return "Firefox"
    if "Edg/" in ua:
        return "Edge"
    if "Chrome/" in ua:
        return "Chrome"
    return "custom"


# ---- Ad / tracker blocker (runs on every network request) ----
class AdblockInterceptor(QWebEngineUrlRequestInterceptor):
    def __init__(self):
        super().__init__()
        self.enabled = True
        # domain -> User-Agent header bytes for sites with their own identity
        # (see DEL 53). Filled by Browser._apply_privacy(); empty = none.
        self.ua_by_host = {}
        self.domains = set()
        self.exempt_hosts = set()              # sites where adblock is turned off
        # Sites YOU blocked outright (the junk list - "BLOCK this site" on the
        # page right-click menu). Deliberately kept APART from `domains`: an ad
        # domain is a suggestion the ad blocker can be talked out of (switched
        # off, Plain mode, a per-site exception), a blocked site is not.
        self.junk_domains = set()
        # Sec-CH-UA rewrite (see chrome_brand_headers). Filled in by
        # Browser._apply_brand_headers(); empty = send whatever Qt sends.
        self.ch_ua = b""
        self.ch_ua_full = b""
        # DEL 56: sites whose renderer keeps crashing; WhyBrowse touches none of
        # their requests (no UA / Sec-CH-UA rewrite, no blocking) until restart.
        self.safe_hosts = set()

    def set_domains(self, domains):
        self.domains = set(d.strip().lower() for d in domains if d and d.strip())

    def _site_ua(self, info):
        """The per-site User-Agent for this request, b"" if the site has none.
        Keyed on the PAGE's host (first party), so a site's scripts, images and
        frames all carry the same identity as the page itself."""
        h = info.firstPartyUrl().host().lower() or info.requestUrl().host().lower()
        if h.startswith("www."):
            h = h[4:]
        parts = h.split(".")
        for i in range(len(parts)):                 # longest suffix first
            ua = self.ua_by_host.get(".".join(parts[i:]))
            if ua:
                return ua
        return b""

    def interceptRequest(self, info):
        # ---- Crash-safe sites (DEL 56): hands off completely ----
        if self.safe_hosts:
            try:
                _fh = (info.firstPartyUrl().host() or info.requestUrl().host()).lower()
                if _fh.startswith("www."):
                    _fh = _fh[4:]
                if any(_fh == d or _fh.endswith("." + d) for d in self.safe_hosts):
                    return
            except Exception:
                pass
        # ---- Per-site user agent (DEL 53) ----
        # Above everything else for the same reason as the brand fix below:
        # an identity choice, not a blocking rule.
        site_ua = b""
        if self.ua_by_host:
            try:
                site_ua = self._site_ua(info)
                if site_ua:
                    info.setHttpHeader(b"User-Agent", site_ua)
            except Exception:
                site_ua = b""
        # ---- Sec-CH-UA brand fix (DEL 50) ----
        # FIRST, and deliberately ABOVE every early return below: this has to
        # happen on every single request, including when the ad blocker is off
        # or the site is exempt. It is an identity header, not a blocking rule.
        # Stands down on a site with its own identity: claiming "Google Chrome"
        # next to a Firefox User-Agent is the contradiction this avoids.
        if self.ch_ua and not site_ua:
            try:
                info.setHttpHeader(b"sec-ch-ua", self.ch_ua)
                info.setHttpHeader(b"sec-ch-ua-full-version-list", self.ch_ua_full)
            except Exception:
                pass
        # TEMPORARY DIAGNOSTIC (safe to remove later): log Google Sheets/Docs
        # export requests specifically (and ONLY those - this must stay narrow
        # so it never spams the log on ordinary browsing). This runs BEFORE
        # the adblock enabled/domains check, so it fires even with adblock off,
        # and tells us whether the export request leaves the page at all -
        # if this line never appears when a "Download as xlsx/ods" does
        # nothing, the page's own JavaScript never even tried to fetch the
        # export in this browser (a Chromium/QtWebEngine-side issue, not a
        # WhyBrowse download-handling issue).
        try:
            _ru = info.requestUrl()
            _rh = _ru.host().lower()
            _rp = _ru.path().lower()
            if "google" in _rh and "export" in _rp:
                log_line("adblock: saw export-like request: %s" % _ru.toString())
        except Exception:
            pass
        # ---- Sites you BLOCKED outright (the junk list) -------------------
        # A blocked site's own page never gets this far: WebPage.
        # acceptNavigationRequest refuses the main-frame navigation first, says
        # so in a toast, and closes the tab if the tab existed only for it.
        # THIS is the other half of "never again" - it stops a blocked site
        # coming back in sideways, as an iframe, a script or a beacon inside a
        # page you DO want, which for a pop-up farm is the whole business. It
        # sits above the ad blocker's early return on purpose: blocked means
        # blocked with the ad blocker off, in Plain mode, and on a site that
        # has an adblock exception.
        if self.junk_domains:
            try:
                jh = info.requestUrl().host().lower()
            except Exception:
                jh = ""
            # Never a human-verification widget - killing one of those loops
            # the page back to "Verify you are human" with nothing to click.
            if jh and not is_challenge_host(jh):
                jp = jh.split(".")
                for i in range(len(jp) - 1):
                    if ".".join(jp[i:]) in self.junk_domains:
                        info.block(True)
                        return
        if not self.enabled or not self.domains:
            return
        try:
            fph = info.firstPartyUrl().host().lower()
            # Never block on login/SSO or payment pages, or sites with an
            # adblock exception (payment = don't risk killing a checkout QR).
            if is_login_host(fph) or is_payment_host(fph):
                return
            if any(fph == d or fph.endswith("." + d) for d in self.exempt_hosts):
                return
            host = info.requestUrl().host().lower()
            # NEVER block a human-verification widget (Cloudflare Turnstile,
            # hCaptcha, reCAPTCHA, Arkose, DataDome...) - neither its own
            # requests nor anything on a page that IS the challenge. Blocking
            # one of its beacons makes the check fail silently and loop back to
            # "Verify you are human" (reported on predb.me).
            if is_challenge_host(host) or is_challenge_host(fph):
                return
        except Exception:
            return
        if not host:
            return
        # Block exact matches and subdomains of a blocked domain.
        parts = host.split(".")
        for i in range(len(parts) - 1):
            if ".".join(parts[i:]) in self.domains:
                info.block(True)
                return


# ---- Injected JavaScript: geolocation spoof (must run before page scripts) ----
# The engine's untouched user-agent, captured the first time we look at it (see
# _effective_user_agent). Every engine shares the same Qt default, so one copy
# is enough - and deriving from it, rather than from the UA we last wrote, is
# what keeps a cleared custom UA from sticking around.
_PRISTINE_UA = ""

# How many Chrome majors this engine may fall behind latest stable before the
# user-agent starts claiming the newer version anyway. Below this gap we report
# the truth: a UA above the engine's real version fails the same feature-vs-
# version cross-check that bot walls use. Above it, sites start refusing an
# "ancient" browser outright, which is the worse failure.
#
# Why 20 and not something small: QtWebEngine tracks Chromium at its own pace,
# and the normal, healthy gap is already large - measured 2026-07-19, this
# machine's engine was Chromium 140 while latest stable Chrome was 151, a gap of
# ELEVEN with a fully up-to-date PyQt6-WebEngine. A small threshold would treat
# that everyday state as "ancient" and start lying again, which is precisely the
# mismatch that made Cloudflare loop. 20 majors is roughly a year and a half
# behind - genuinely stale, and by then the honest fix is to update the engine
# (Menu → Browser engine version), not to lie about it.
UA_BUMP_GAP = 20


# ---- "Did this page actually fail?" probe -----------------------------------
# Chromium fires loadFinished(ok=False) for plenty of harmless reasons (a
# navigation superseded by the next one, an aborted sub-resource, a late
# redirect), and the page then paints fine milliseconds later - which is how a
# "didn't load" pop-up ended up on top of pages that had loaded. This returns a
# rough CONTENT SCORE for the page; anything >= 40 means there is a real page
# there and we must stay quiet. Chromium's own network-error page scores 0.
PAGE_CONTENT_PROBE_JS = """(function(){
  try{
    var b = document.body;
    if(!b) return 0;
    // Chromium's built-in error page ("This site can't be reached").
    if(document.querySelector('div#main-frame-error,div.neterror,'+
       '#error-information-popup-container')) return 0;
    var text = (b.innerText || '').trim().length;
    var els  = b.querySelectorAll('img,video,canvas,svg,iframe,input,form,table').length;
    return text + els * 50;
  }catch(e){ return 0; }
})();"""


GEO_SCRIPT = """(function(){
  var cfg = __CFG__;
  // ---- Per-site browser identity (DEL 53) -----------------------------------
  // FIRST, so every block below sees the identity this site was given. The
  // matching HTTP header is set in AdblockInterceptor; this is the page-side
  // half. A non-Chrome identity also hides what only Chromium has
  // (userAgentData, window.chrome), otherwise the page would say "Firefox"
  // and then show Chrome's furniture.
  try{
    var _su = cfg.siteUA || {};
    var _sh = (location.hostname||'').toLowerCase().replace(/^www\\./,'');
    var _sua = '', _sbl = -1;
    for(var _sd in _su){
      if((_sh===_sd || _sh.endsWith('.'+_sd)) && _sd.length>_sbl){ _sua = _su[_sd]; _sbl = _sd.length; }
    }
    if(_sua){
      var _isCr = /Chrome\\//.test(_sua), _isFx = /Firefox\\//.test(_sua);
      var _def = function(k, v){
        try{ Object.defineProperty(navigator, k, {get: function(){ return v; }, configurable: true}); }catch(e){}
      };
      _def('userAgent', _sua);
      _def('appVersion', _isFx ? '5.0 (Windows)' : _sua.replace(/^Mozilla\\//,''));
      if(!_isCr){
        _def('vendor', '');
        _def('userAgentData', undefined);
        try{ delete window.chrome; }catch(e){}
      }
      if(_isFx){
        _def('oscpu', 'Windows NT 10.0; Win64; x64');
        _def('productSub', '20100101');
      }
    }
  }catch(e){}
  // ---- User-agent client-hints alignment (UA_CH_FIX) ------------------------
  // WhyBrowse rewrites the user-agent STRING (see _effective_user_agent) so
  // sites stop rejecting us for an old/unknown Chrome version. But Chromium
  // ALSO exposes navigator.userAgentData, and setHttpUserAgent does NOT touch
  // it - so the string claimed e.g. "Chrome/136" while userAgentData still
  // reported the engine's real, older version. Human-verification widgets
  // (Cloudflare Turnstile, hCaptcha) compare those two, and a disagreement is
  // the loudest "this is not a real browser" signal there is: you get an
  // endless "Verify you are human" loop no matter how many boxes you tick.
  // Make the two agree. Runs at document creation, in every frame, so the
  // challenge iframe sees it too.
  // Superseded by the fuller cfg.chromeIdentity block just below when that is
  // on - running both would wrap navigator.userAgentData twice for no gain.
  try{
    var _maj = cfg.chromeIdentity ? '' : (cfg.uaMajor ? String(cfg.uaMajor) : '');
    var _uad = navigator.userAgentData;
    // The deliberately-fake "GREASE" brand (Chrome sends something like
    // "Not.A/Brand" with an arbitrary version) must keep ITS version - real
    // Chrome does not move it with the release number, and rewriting it would
    // be its own small tell.
    var _grease = function(b){ return /not[^a-z]*a[^a-z]*brand/i.test(b.brand || ''); };
    if(_maj && _uad && _uad.brands && _uad.brands.length
       && _uad.brands.some(function(b){
            return !_grease(b) && b.version !== _maj; })){
      var _brands = _uad.brands.map(function(b){
        return {brand: b.brand, version: _grease(b) ? b.version : _maj};
      });
      var _full = _maj + '.0.0.0';
      var _patched = {
        brands: _brands,
        mobile: !!_uad.mobile,
        platform: _uad.platform,
        toJSON: function(){
          return {brands: _brands, mobile: !!_uad.mobile,
                  platform: _uad.platform};
        },
        getHighEntropyValues: function(hints){
          return _uad.getHighEntropyValues(hints).then(function(v){
            try{
              if(v.brands) v.brands = _brands;
              if(v.fullVersionList)
                v.fullVersionList = v.fullVersionList.map(function(b){
                  return {brand: b.brand,
                          version: _grease(b) ? b.version : _full};
                });
              if(v.uaFullVersion) v.uaFullVersion = _full;
            }catch(e){}
            return v;
          });
        }
      };
      Object.defineProperty(navigator, 'userAgentData',
        {get: function(){ return _patched; }, configurable: true});
    }
  }catch(e){}
  // ---- Chrome identity, part 2 (DEL 50) -------------------------------------
  // Three MEASURED differences between this engine and a real Chrome, all of
  // them free to fix and all of them read by sign-in bot checks. cfg.chBrands
  // is the SAME list the Sec-CH-UA request headers are built from (see
  // chrome_brand_headers) so the header and the JavaScript cannot disagree.
  if(cfg.chromeIdentity){
    // (a) navigator.userAgentData.brands said "Chromium", never "Google Chrome".
    try{
      var _cb = cfg.chBrands || [];
      if(_cb.length && navigator.userAgentData){
        var _u2 = navigator.userAgentData;
        var _b2 = _cb.map(function(b){ return {brand: b[0], version: b[1]}; });
        var _fv = _cb.map(function(b){ return {brand: b[0], version: b[2]}; });
        var _full2 = (_cb[_cb.length-1] || [])[2] || '';
        var _p2 = {
          brands: _b2, mobile: !!_u2.mobile, platform: _u2.platform,
          toJSON: function(){ return {brands:_b2, mobile:!!_u2.mobile,
                                      platform:_u2.platform}; },
          // The engine answers this properly (measured: it returns a real
          // platformVersion, architecture, bitness...), so the ONLY things we
          // override are the two brand lists and uaFullVersion - the values
          // that would otherwise still say plain "Chromium" while the header
          // says "Google Chrome". Everything else is passed through untouched;
          // cfg.chHints only fills a hint the engine left out, and never
          // replaces one it answered. platformVersion is deliberately not in
          // chHints: Chromium derives it from a build-number table we would
          // have to duplicate, and a wrong value is worse than none.
          getHighEntropyValues: function(hints){
            var want = hints || [];
            var fill = function(v){
              v = v || {};
              try{
                v.brands = _b2;
                v.mobile = !!_u2.mobile;
                if(!v.platform) v.platform = _u2.platform;
                var extra = cfg.chHints || {};
                if(want.indexOf('fullVersionList') >= 0) v.fullVersionList = _fv;
                if(want.indexOf('uaFullVersion') >= 0)   v.uaFullVersion = _full2;
                ['architecture','bitness','model','wow64','formFactor']
                  .forEach(function(k){
                    if(want.indexOf(k) >= 0 && v[k] === undefined
                       && extra[k] !== undefined) v[k] = extra[k];
                  });
              }catch(e){}
              return v;
            };
            try{
              return _u2.getHighEntropyValues(want).then(fill,
                       function(){ return fill({}); });
            }catch(e){ return Promise.resolve(fill({})); }
          }
        };
        Object.defineProperty(navigator, 'userAgentData',
          {get: function(){ return _p2; }, configurable: true});
      }
    }catch(e){}
    // (b) window.chrome existed but was an EMPTY object - no app/csi/loadTimes/
    //     runtime. A browser calling itself Chrome with nothing on window.chrome
    //     is one of the oldest embedded-browser tells there is.
    try{
      var c = window.chrome;
      if(c && typeof c === 'object' && !c.runtime){
        var t0 = (window.performance && performance.timing) || {};
        var _start = t0.navigationStart || Date.now();
        if(!c.app) c.app = {
          isInstalled: false,
          InstallState: {DISABLED:'disabled', INSTALLED:'installed',
                         NOT_INSTALLED:'not_installed'},
          RunningState: {CANNOT_RUN:'cannot_run', READY_TO_RUN:'ready_to_run',
                         RUNNING:'running'},
          getDetails: function(){ return null; },
          getIsInstalled: function(){ return false; },
          runningState: function(){ return 'cannot_run'; }
        };
        if(!c.csi) c.csi = function(){
          return {startE: _start, onloadT: t0.domContentLoadedEventEnd || _start,
                  pageT: (Date.now() - _start), tran: 15};
        };
        if(!c.loadTimes) c.loadTimes = function(){
          var s = _start / 1000;
          return {requestTime: s, startLoadTime: s,
                  commitLoadTime: (t0.responseStart || _start)/1000,
                  finishDocumentLoadTime: (t0.domContentLoadedEventEnd || _start)/1000,
                  finishLoadTime: (t0.loadEventEnd || _start)/1000,
                  firstPaintTime: s, firstPaintAfterLoadTime: 0,
                  navigationType: 'Other', wasFetchedViaSpdy: true,
                  wasNpnNegotiated: true, npnNegotiatedProtocol: 'h2',
                  wasAlternateProtocolAvailable: false, connectionInfo: 'h2'};
        };
        // Real Chrome exposes runtime on ordinary pages too: the enums are
        // there, id is undefined, and calling connect/sendMessage without an
        // extension throws. Mirror that rather than inventing a working stub -
        // a site that probes it must get Chrome's answer, including the throw.
        c.runtime = {
          id: undefined,
          OnInstalledReason: {CHROME_UPDATE:'chrome_update', INSTALL:'install',
                              SHARED_MODULE_UPDATE:'shared_module_update',
                              UPDATE:'update'},
          OnRestartRequiredReason: {APP_UPDATE:'app_update',
                                    OS_UPDATE:'os_update', PERIODIC:'periodic'},
          PlatformArch: {ARM:'arm', ARM64:'arm64', MIPS:'mips',
                         MIPS64:'mips64', X86_32:'x86-32', X86_64:'x86-64'},
          PlatformNaclArch: {ARM:'arm', MIPS:'mips', MIPS64:'mips64',
                             X86_32:'x86-32', X86_64:'x86-64'},
          PlatformOs: {ANDROID:'android', CROS:'cros', LINUX:'linux',
                       MAC:'mac', OPENBSD:'openbsd', WIN:'win'},
          RequestUpdateCheckStatus: {NO_UPDATE:'no_update',
                                     THROTTLED:'throttled',
                                     UPDATE_AVAILABLE:'update_available'},
          connect: function(){
            throw new TypeError("Error in invocation of runtime.connect(" +
              "optional string extensionId, optional object connectInfo): " +
              "chrome.runtime.connect() called from a webpage must specify an " +
              "Extension ID (string) for its first argument.");
          },
          sendMessage: function(){
            throw new TypeError("Error in invocation of runtime.sendMessage(" +
              "optional string extensionId, any message, optional object " +
              "options, optional function responseCallback): " +
              "chrome.runtime.sendMessage() called from a webpage must " +
              "specify an Extension ID (string) for its first argument.");
          }
        };
      }
    }catch(e){}
    // (c) navigator.languages was the single-entry ["sv"]. Keep it in step with
    //     the Accept-Language header we now actually send.
    try{
      var _langs = cfg.navLangs || [];
      if(_langs.length > 1 && (navigator.languages || []).length < _langs.length){
        Object.defineProperty(navigator, 'languages',
          {get: function(){ return _langs.slice(); }, configurable: true});
      }
    }catch(e){}
  }
  // Hard de-animation (opt-in): neutralise the JavaScript animation loop so
  // canvas/Lottie/sprite mascots (e.g. Duolingo's basketball guy) and JS-driven
  // bounces stop. Must run at document-creation, before page scripts capture
  // these. It CAN break sites that rely on rAF (some scroll/UI effects, games).
  // The rAF-loop kill is resolved PER-HOST: the global switch, OR a per-site
  // "freeze_js" exception. (Global-on breaks YouTube/Google lazy loading, so the
  // sane way is to turn it on only for the few sites that need it, e.g. Duolingo.)
  var freezeHard = !!cfg.freezeHard;
  try{
    var so0 = cfg.siteOverrides || {}, h0 = (location.hostname||'').replace(/^www\\./,'');
    var best0 = null, bl0 = -1;
    for(var d0 in so0){ if((h0===d0 || h0.endsWith('.'+d0)) && d0.length>bl0 && ('freeze_js' in so0[d0])){ best0 = so0[d0].freeze_js; bl0 = d0.length; } }
    if(best0 !== null) freezeHard = !!best0;
  }catch(e){}
  if(freezeHard){
    // Stop animation that PAUSING can't reach: canvas / Lottie / rAF-driven
    // transforms (Duolingo's basketball + bouncing rectangles) by killing the
    // requestAnimationFrame loop. PLUS pause any Web Animations / CSS ones.
    // IMPORTANT: we deliberately do NOT touch Element.prototype.animate (that
    // hides content that "reveals" via animate() → logged-out look, dead
    // buttons, grey-lock) and do NOT touch setInterval. Killing rAF alone was
    // safe in testing; if a specific site misbehaves, turn this option off.
    try{
      var _si = window.setInterval;
      var noop = function(){ return 0; };
      window.requestAnimationFrame = noop;
      window.webkitRequestAnimationFrame = noop;
      window.cancelAnimationFrame = function(){};
      window.webkitCancelAnimationFrame = function(){};
      var pauseAll = function(){ try{
        if(document.getAnimations) document.getAnimations().forEach(
          function(a){ try{ a.pause(); }catch(e){} });
      }catch(e){} };
      _si(pauseAll, 400);
      document.addEventListener('DOMContentLoaded', pauseAll);
    }catch(e){}
  }
  // Disable passkeys/WebAuthn so sites (e.g. Google sign-in) fall back to a
  // normal password field instead of the broken "choose a passkey" prompt.
  if(cfg.noPasskeys){
    // Keep PublicKeyCredential present (so page layout doesn't break) but tell
    // sites there is no authenticator, and reject passkey get() calls.
    try{
      if(window.PublicKeyCredential){
        window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable =
          function(){ return Promise.resolve(false); };
        if('isConditionalMediationAvailable' in window.PublicKeyCredential){
          window.PublicKeyCredential.isConditionalMediationAvailable =
            function(){ return Promise.resolve(false); };
        }
      }
      if(navigator.credentials && navigator.credentials.get){
        var _get = navigator.credentials.get.bind(navigator.credentials);
        navigator.credentials.get = function(o){
          if(o && o.publicKey){
            return Promise.reject(new DOMException('Passkeys disabled', 'NotAllowedError'));
          }
          return _get(o);
        };
      }
    }catch(e){}
  }
  if(!cfg.spoof || cfg.lat===null || cfg.lat===undefined) return;
  var coords = {latitude:cfg.lat, longitude:cfg.lon, accuracy:45,
                altitude:null, altitudeAccuracy:null, heading:null, speed:null};
  var pos = {coords:coords, timestamp:Date.now()};
  try{
    if(navigator.geolocation){
      navigator.geolocation.getCurrentPosition = function(s,e,o){ try{s(pos);}catch(_){}};
      navigator.geolocation.watchPosition = function(s,e,o){ try{s(pos);}catch(_){ } return 0; };
    }
  }catch(_){}
})();"""

# ---- Injected JavaScript: cosmetic (freeze animations, element-hide, search block)
COSMETIC_SCRIPT = """(function(){
  var cfg = __CFG__;
  function injectCSS(css){
    try{ var s=document.createElement('style'); s.textContent=css;
         (document.head||document.documentElement).appendChild(s); }catch(e){}
  }
  // Per-site exception resolver: returns the override for this host if any.
  function ovr(key, deflt){
    try{
      var so=cfg.siteOverrides||{}, host=(location.hostname||'').replace(/^www\\./,'');
      var best=null, bl=-1;
      for(var d in so){ if((host===d||host.endsWith('.'+d)) && d.length>bl){ best=so[d]; bl=d.length; } }
      if(best && key in best) return best[key];
    }catch(e){}
    return deflt;
  }
  // True if the user EXPLICITLY set this key for this host (a per-site exception).
  // Such an explicit choice overrides the payment/app "never freeze" safe-lists.
  function hasOvr(key){
    try{
      var so=cfg.siteOverrides||{}, host=(location.hostname||'').replace(/^www\\./,'');
      var best=null, bl=-1;
      for(var d in so){ if((host===d||host.endsWith('.'+d)) && d.length>bl){ best=so[d]; bl=d.length; } }
      return !!(best && key in best);
    }catch(e){ return false; }
  }
  // Payment/checkout pages: skip cosmetic hiding/freezing entirely so we never
  // wipe out a payment QR code (e.g. Swish QR on amazon.se checkout).
  // Payment hosts come from Python (single source of truth) via cfg — NO
  // hand-copied duplicate list here (that divergence is exactly what once let
  // sellpy.se fall through). cfg.payHosts = whole-domain payment hosts;
  // cfg.payPathHosts = [host, [pathPrefix,…]] merchant hosts that count as a
  // payment page only under those path prefixes (e.g. sellpy.se/checkout*).
  var PAY_HOSTS = cfg.payHosts || [];
  var PAY_PATH_HOSTS = cfg.payPathHosts || [];
  function isPaymentHost(){
    try{ var h=(location.hostname||'').replace(/^www\\./,'');
      if(PAY_HOSTS.some(function(d){return h===d||h.endsWith('.'+d);}))
        return true;
      var p=location.pathname||'/';
      return PAY_PATH_HOSTS.some(function(e){
        var d=e[0], pre=e[1]||[];
        if(!(h===d||h.endsWith('.'+d))) return false;
        return pre.some(function(x){return p.indexOf(x)===0;});
      });
    }catch(e){ return false; }
  }
  var paymentSafe = isPaymentHost();
  // Video / streaming hosts: NEVER pause their media. The freeze feature pauses
  // <video> on DOM mutations, and YouTube mutates constantly, so it re-paused the
  // video every ~0.5s ("video stops right after starting"). On these hosts we
  // leave all media alone; elsewhere we only pause AUTOPLAY media, once.
  var VIDEO_HOSTS = ["youtube.com","youtu.be","vimeo.com","twitch.tv",
    "netflix.com","dailymotion.com","disneyplus.com","hbomax.com","max.com",
    "viaplay.com","svtplay.se","tv4play.se","primevideo.com","spotify.com",
    "soundcloud.com","plex.tv","kanal5play.se","discoveryplus.com","imdb.com"];
  function isVideoHost(){
    try{ var h=(location.hostname||'').replace(/^www\\./,'');
      return VIDEO_HOSTS.some(function(d){return h===d||h.endsWith('.'+d);});
    }catch(e){ return false; }
  }
  var videoSafe = isVideoHost();
  // Web-app hosts where the freeze CSS (animation/transition:none) can break the
  // app's own rendering (Google Sheets/Docs/Drive are canvas/transition-driven and
  // were going blank). Never freeze on these.
  var APP_HOSTS = ["docs.google.com","sheets.google.com","drive.google.com",
    "script.google.com","calendar.google.com","meet.google.com",
    "slides.google.com","keep.google.com","mail.google.com"];
  function isAppHost(){
    try{ var h=(location.hostname||'').replace(/^www\\./,'');
      return APP_HOSTS.some(function(d){return h===d||h.endsWith('.'+d);});
    }catch(e){ return false; }
  }
  var appSafe = isAppHost();
  // Human-verification pages ("Verify you are human" / "Just a moment…"):
  // leave them COMPLETELY alone. Frozen animations stop the challenge's own
  // spinner and its widget never finishes; the nag-hiding CSS and the
  // auto-accept-cookies clicker can hide or mis-click the very box you are
  // supposed to tick. Either way you loop back to the check forever - which is
  // what happened on predb.me. Detected two ways: the page IS served by a
  // challenge provider (cfg.chalHosts), or the page carries a challenge
  // widget's own markup (Cloudflare interstitial / Turnstile / hCaptcha /
  // reCAPTCHA). Nothing here solves or skips the challenge - it just stops us
  // interfering with it.
  var CHAL_HOSTS = cfg.chalHosts || [];
  function isChallengePage(){
    try{
      var h=(location.hostname||'').replace(/^www\\./,'');
      if(CHAL_HOSTS.some(function(d){return h===d||h.endsWith('.'+d);}))
        return true;
      // Anubis (Techaro / within.website) is a proof-of-work wall served
      // FIRST-PARTY under a /.within.website/ path on the site's own domain
      // (opensubtitles.org uses it), so no third-party host gives it away -
      // the path and its #anubis_challenge markup do. Leaving this page
      // untouched lets its script set the verification cookie and pass.
      if((location.pathname||'').indexOf('/.within.website/')>=0) return true;
      if(document.querySelector('#anubis_challenge,#anubis_version,'+
        '[src*="/.within.website/"],[href*="/.within.website/"]')) return true;
      return !!document.querySelector(
        '#challenge-form,#challenge-stage,#challenge-running,#cf-challenge-running,'+
        '#cf-wrapper,.cf-turnstile,.h-captcha,.g-recaptcha,'+
        'iframe[src*="challenges.cloudflare.com"],'+
        'iframe[src*="hcaptcha.com"],iframe[src*="recaptcha"],'+
        'script[src*="challenges.cloudflare.com"],script[src*="hcaptcha.com"]');
    }catch(e){ return false; }
  }
  var challengeSafe = isChallengePage();
  // 1-caret) ALWAYS steady the blinking TEXT CARET when freeze is on, even on the
  //   Google app hosts (Docs/Sheets/Slides) that skip the broad animation freeze
  //   below. The broad "*{animation:none}" rule blanks their canvas, so they are
  //   exempt — but the caret is drawn by the editor itself (.kix-cursor-caret) and
  //   blinks via its own animation; this narrow rule makes it a fixed, non-blinking
  //   caret without touching the document canvas. (User hates blinking carets.)
  if(ovr('freeze_animations', cfg.freeze)){
    injectCSS('.kix-cursor-caret,.kix-cursor,.docs-text-ui-cursor-blink,'+
      '.cursor-blink,.blinking-cursor,.CodeMirror-cursor,'+
      '[class*="cursor-blink"]{animation:none !important;'+
      '-webkit-animation:none !important;opacity:1 !important;'+
      'visibility:visible !important;}');
  }
  // 1) Freeze blinking carets, animations and pause media. Payment/app pages skip
  //    freeze by default, BUT an explicit "Freeze animations here" exception wins
  //    (e.g. Amazon's checkout QR only renders readable when its spinner is frozen).
  if(ovr('freeze_animations', cfg.freeze) && !challengeSafe
     && (hasOvr('freeze_animations') || (!paymentSafe && !appSafe))){
    // MEASURED, do not go back to `animation:none` / `transition:none`:
    // those two DELETE the animation instead of shortening it, so the browser
    // never fires `animationend` / `transitionend`. Any site that finishes a
    // job in those events therefore never finishes it. Two of Issu's bug
    // reports were exactly this, both on Tradera:
    //   * the green "done / shipping booked" toast auto-hides with
    //     `animation: fade .3s 4s forwards` - frozen, it stays on screen until
    //     you reload;
    //   * a dialog fades its backdrop out and removes it + restores
    //     body{overflow} in `transitionend` - frozen, the backdrop stays and
    //     the page keeps the scroll lock, so there is no scrollbar and
    //     everything below the fold is unreachable until you reload.
    // Reproduced in this engine with the old rule and cleared with this one.
    // So: keep the DURATION longhand at ~1ms (still instant to the eye, no
    // movement to see) and never touch the shorthand, `animation-name`,
    // `animation-fill-mode` or `animation-delay` - the delay is the site's own
    // "show this toast for 4 seconds" and must be honoured. iteration-count 1
    // is what actually stops an endless blink/pulse/spin.
    injectCSS('*,*::before,*::after{animation-duration:0.001s !important;'+
      '-webkit-animation-duration:0.001s !important;'+
      'animation-iteration-count:1 !important;'+
      '-webkit-animation-iteration-count:1 !important;'+
      'transition-duration:0.001s !important;'+
      '-webkit-transition-duration:0.001s !important;'+
      'will-change:auto !important;scroll-behavior:auto !important;}'+
      '.kix-cursor-caret,.kix-cursor,.cursor{animation:none !important;opacity:1 !important;}'+
      'marquee{}'+
      'blink{text-decoration:none !important;}');
    function freezeMedia(){
      // Only stop AUTOPLAY media, and only ONCE per element, so a video the user
      // starts (or replays) is never paused again. Skipped entirely on video
      // hosts (YouTube etc.) so playback there is untouched.
      if(!videoSafe){
        try{document.querySelectorAll('video,audio').forEach(function(v){
          try{
            if(v.dataset.wbseen) return;        // already handled this element
            v.dataset.wbseen='1';
            if(v.autoplay) v.pause();            // only kill auto-started media
            v.autoplay=false;
          }catch(e){}});}catch(e){}
      }
      // Pause SVG (SMIL) animations - many mascots/icons animate this way.
      try{document.querySelectorAll('svg').forEach(function(s){
        try{ if(s.pauseAnimations) s.pauseAnimations(); }catch(e){}});}catch(e){}
      // Stop <marquee> scrolling.
      try{document.querySelectorAll('marquee').forEach(function(m){
        try{ if(m.stop) m.stop(); }catch(e){}});}catch(e){}
      // Freeze animated GIFs: swap the <img> for a <canvas> of its current
      // frame (drawing works cross-origin; only reading pixels would be blocked).
      try{document.querySelectorAll('img').forEach(function(img){
        try{
          if(img.dataset.wbgif) return;
          var s=(img.currentSrc||img.src||'');
          if(!/\\.gif(\\?|#|$)/i.test(s)) return;
          if(!img.complete || !img.naturalWidth) return;
          var c=document.createElement('canvas');
          c.width=img.naturalWidth; c.height=img.naturalHeight;
          c.getContext('2d').drawImage(img,0,0);
          var r=img.getBoundingClientRect();
          c.className=img.className;
          c.style.cssText=img.getAttribute('style')||'';
          c.style.width=((img.width||r.width)||img.naturalWidth)+'px';
          c.style.height=((img.height||r.height)||img.naturalHeight)+'px';
          c.dataset.wbgif='1';
          img.replaceWith(c);
        }catch(e){}
      });}catch(e){}
    }
    freezeMedia();
    document.addEventListener('DOMContentLoaded', freezeMedia);
    // Re-apply to elements added later (SPAs, lazy mascots).
    try{ new MutationObserver(freezeMedia).observe(document.documentElement,
         {childList:true, subtree:true}); }catch(e){}
  }
  // 1b) Forced colours (high-contrast for colour-blind / low vision)
  var fc=cfg.forced;
  if(fc && fc.enabled){
    injectCSS('*,*::before,*::after{background-color:'+fc.bg+' !important;color:'+fc.fg+' !important;'+
      'border-color:'+fc.fg+' !important;}'+
      'a,a *{color:'+(fc.link||fc.fg)+' !important;}'+
      'input,textarea,select,button{background-color:'+fc.bg+' !important;color:'+fc.fg+' !important;}'+
      'img,video,svg,canvas,picture{opacity:1 !important;}');
  }
  // 1c) Hide cookie banners and donation bars. ONLY well-known consent-platform
  //     ids/classes - NO broad wildcards and NO forced overflow, so we never
  //     break a site's own layout/scrolling (Tradera, Duolingo, etc.).
  if(!paymentSafe && !challengeSafe && ovr('hide_nag_banners', cfg.hideNags)){
    injectCSS([
      '#onetrust-consent-sdk','#onetrust-banner-sdk','.onetrust-pc-dark-filter',
      '#CybotCookiebotDialog','#CybotCookiebotDialogBodyUnderlay',
      '.qc-cmp2-container','.qc-cmp-cleanslate','.fc-consent-root','.fc-dialog-overlay',
      '.cc-window','.cmpbox','#gdpr-cookie-message','.osano-cm-window',
      '#usercentrics-root','.didomi-popup-container','#didomi-host',
      '.cn-fundraiser','#frbanner','.frbanner','#centralNotice'
    ].join(',')+'{display:none !important;}');
  }
  // 1d) Auto-accept cookie pop-ups (click the accept button) AND release the
  //     scroll-lock the consent script puts on <body> (that is why Tradera's
  //     scrollbar vanished: banner hidden but body stayed overflow:hidden).
  if(cfg.autoCookies && !challengeSafe){
    var SEL=['#onetrust-accept-btn-handler','#accept-recommended-btn-handler',
      '#CybotCookiebotDialogBodyLevelButtonLevelOptinAllowAll',
      '#CybotCookiebotDialogBodyButtonAccept','#didomi-notice-agree-button',
      'button[data-testid="uc-accept-all-button"]',
      '.qc-cmp2-summary-buttons button[mode="primary"]','.cc-allow','.cc-dismiss',
      'button[aria-label="Godkänn alla"]','button[aria-label="Acceptera alla"]'];
    var TXT=['acceptera alla','godkänn alla','tillåt alla','acceptera','godkänn',
      'jag godkänner','ok, godkänt','accept all','allow all','i accept','accept'];
    function clickAccept(){
      for(var i=0;i<SEL.length;i++){var b=document.querySelector(SEL[i]); if(b){b.click(); return true;}}
      var bs=document.querySelectorAll('button,[role=button],input[type=button],input[type=submit]');
      for(var j=0;j<bs.length;j++){
        var t=(bs[j].textContent||bs[j].value||'').trim().toLowerCase();
        if(t && t.length<22 && TXT.indexOf(t)>=0){ bs[j].click(); return true; }
      }
      return false;
    }
    function unlock(){
      try{[document.documentElement, document.body].forEach(function(e){
        if(e && getComputedStyle(e).overflow==='hidden'){ e.style.setProperty('overflow','auto','important'); }
      });}catch(e){}
    }
    var tries=0;
    var iv=setInterval(function(){ tries++; var done=clickAccept(); unlock();
      if(done || tries>12) clearInterval(iv); }, 600);
  }
  // 1e) Capture a submitted login so the vault can offer to save it. The creds
  //      go ONLY into this site's own sessionStorage (which it already controls,
  //      since you just typed your password into its form) - never to disk - and
  //      WhyBrowse reads + clears it on the next page load.
  if(cfg.autosaveLogin){
    try{
      document.addEventListener('submit', function(ev){
        try{
          var form = ev.target;
          if(!form || !form.querySelector) return;
          var pw = form.querySelector('input[type=password]');
          if(!pw || !pw.value) return;
          var us = form.querySelector('input[autocomplete=username],input[type=email],'+
            'input[name*=user i],input[name*=email i],input[id*=user i],input[id*=email i],'+
            'input[type=text]');
          var rec = {u: us?us.value:'', p: pw.value,
                     host: (location.hostname||'').replace(/^www\\./,''),
                     https: location.protocol==='https:', t: Date.now()};
          sessionStorage.setItem('__wb_pending_login', JSON.stringify(rec));
        }catch(e){}
      }, true);
    }catch(e){}
  }
  // 2) Element-hide rules for this host
  var host = (location.hostname||'').replace(/^www\\./,'');
  // 2b) Kill Google's animated SEARCH box only on the bare search domain
  //     (NOT accounts/docs/drive/mail - disabling transitions there breaks the
  //      Material outlined inputs, e.g. the distorted password field).
  if(/^google\\.[a-z.]+$/.test(host)){
    injectCSS('#searchform *,#sfcnt *,.RNNXgb,.RNNXgb *,.gLFyf{'+
      'animation:none !important;-webkit-animation:none !important;transition:none !important;}');
  }
  // 2b2) Hide the sponsored "ad" results on the big search engines. These sit
  //      ABOVE the real results (DuckDuckGo shows up to ~3 at the very top).
  //      This is COSMETIC only - nothing is blocked at the network level, so a
  //      search still works exactly as before, just without the paid results.
  //      DuckDuckGo's markup was verified live: an ad is a list item marked
  //      data-layout="ad" (real results are data-layout="organic"), which the
  //      obfuscated class names never expose. The other engines use their own
  //      long-standing ad containers. Toggle: "Hide search-engine ads".
  if(cfg.hideSearchAds){
    var AD = [];
    if(/(^|\\.)duckduckgo\\.com$/.test(host))
      AD.push('li[data-layout="ad"]','[data-testid="ad"]','.results--ads','.result--ad');
    else if(/^google\\./.test(host))
      AD.push('#tads','#tadsb','#bottomads','.commercial-unit-desktop-top',
              '.commercial-unit-desktop-rhs','[data-text-ad]','#taw .uEierd');
    else if(/(^|\\.)bing\\.com$/.test(host))
      AD.push('.b_ad','.b_adTop','.b_adBottom','li.b_ad','.sb_adTA','.b_adSlug','.b_adLabel');
    else if(/(^|\\.)search\\.yahoo\\.com$/.test(host))
      AD.push('ol.searchCenterTopAds','.searchCenterTopAds','.searchRightTopAds','.ads');
    else if(/(^|\\.)ecosia\\.org$/.test(host))
      AD.push('[data-test-id="main-ad"]','.card-ad','.result--ad');
    else if(/(^|\\.)search\\.brave\\.com$/.test(host))
      AD.push('.ad','[data-type="ad"]');
    else if(/(^|\\.)startpage\\.com$/.test(host))
      AD.push('.inline-ad','[class*="sponsored"]');
    if(AD.length) injectCSS(AD.join(',')+'{display:none !important;}');
  }
  // 2c) Google sign-in: replace the fragile notched <fieldset> outline with a
  //     clean solid border (fixes the skewed password box at some display
  //     scalings) and strip the "webauthn" autofill token from inputs.
  if(cfg.fixGoogleLogin && location.hostname.indexOf('accounts.google.')>=0){
    // Make the floating label's white background fully mask the outline border
    // it sits on (the skew is that mask misaligning at some display scalings).
    injectCSS('.AxOyFc.snByac{background:#fff !important; padding:0 5px !important;'+
      'box-shadow:0 0 0 2px #fff !important;}');
    var stripWA = function(){
      try{
        document.querySelectorAll('input[autocomplete~="webauthn"]').forEach(function(i){
          var a = (i.getAttribute('autocomplete')||'').replace(/\\bwebauthn\\b/, '')
                    .replace(/\\s+/g, ' ').trim();
          i.setAttribute('autocomplete', a || 'on');
        });
      }catch(e){}
    };
    stripWA();
    try{ new MutationObserver(stripWA).observe(document.documentElement,
         {childList:true, subtree:true}); }catch(e){}
  }
  // DEL 56: hide rules switched off for THIS site by "Try without..." (session only).
  var cOffT = {};
  try{ var co = cfg.crashOff || {};
    for(var ck in co){ if(host===ck || host.endsWith('.'+ck)) (co[ck]||[]).forEach(function(t){ cOffT[t]=1; }); }
  }catch(e){}
  var sel = [];
  (cfg.elementHide||[]).forEach(function(r){
    if(cOffT['hide:*'] || cOffT['hide:'+r.selector]) return;
    if(r.domain==='*' || host.indexOf(r.domain)>=0) sel.push(r.selector);
  });
  if(sel.length) injectCSS(sel.join(',')+'{display:none !important;}');
  // 2d) Freeze chosen sections to the top while scrolling (Sheets-like freeze)
  var stick = [];
  (cfg.stick||[]).forEach(function(r){
    if(cOffT['stick']) return;
    if(r.domain==='*' || host.indexOf(r.domain)>=0) stick.push(r.selector);
  });
  if(stick.length) injectCSS(stick.join(',')+
    '{position:sticky !important;top:0 !important;z-index:99990 !important;'+
    'background:inherit;}');
  // 2e) Stop just the chosen elements from moving (per-element de-animation):
  //     kill their CSS animation/transition AND pause their Web Animations.
  var froze=[];
  (cfg.freezeEls||[]).forEach(function(r){
    if(cOffT['stick']) return;
    if(r.domain==='*' || host.indexOf(r.domain)>=0) froze.push(r.selector);
  });
  if(froze.length){
    var fsel = froze.concat(froze.map(function(s){return s+' *';})).join(',');
    injectCSS(fsel+'{animation:none !important;-webkit-animation:none !important;'+
      'animation-play-state:paused !important;transition:none !important;}');
    var pauseFroze=function(){ try{ froze.forEach(function(s){
      try{ document.querySelectorAll(s).forEach(function(el){
        try{ el.getAnimations({subtree:true}).forEach(function(a){try{a.pause();}catch(e){}}); }catch(e){}
      }); }catch(e){} }); }catch(e){} };
    pauseFroze();
    document.addEventListener('DOMContentLoaded', pauseFroze);
    try{ new MutationObserver(pauseFroze).observe(document.documentElement,
         {childList:true, subtree:true}); }catch(e){}
  }
  // 3) Hide blocked domains from search-engine result pages
  var blocked = cfg.searchBlock||[];
  var engines = ['google.','duckduckgo.','bing.','ecosia.','startpage.','brave.','search.'];
  var isSearch = engines.some(function(e){return host.indexOf(e)>=0;});
  if(isSearch && blocked.length){
    function matches(h){ return blocked.some(function(d){ return h===d || h.endsWith('.'+d); }); }
    function clean(){
      var links = document.querySelectorAll('a[href]');
      for(var i=0;i<links.length;i++){
        var a=links[i], h;
        try{ h=new URL(a.href).hostname.replace(/^www\\./,''); }catch(e){ continue; }
        if(matches(h)){
          var el=a;
          for(var k=0;k<7 && el;k++){
            el=el.parentElement;
            if(el && el.matches && el.matches('li,div.g,article,[data-hveid],.result,.b_algo,.w-gl__result,[data-testid="result"]')){
              el.style.display='none'; break;
            }
          }
        }
      }
    }
    clean();
    try{ new MutationObserver(clean).observe(document.documentElement,{childList:true,subtree:true}); }catch(e){}
  }
})();"""


# ---- Element zapper: click an element to hide it (and remember a selector) ----
ZAP_SCRIPT = """(function(){
  if(window.__wbZap) return;
  window.__wbZap = true;
  var hl = document.createElement('div');
  hl.style.cssText='position:fixed;z-index:2147483647;background:rgba(57,198,218,0.30);'+
    'border:2px solid #39c6da;pointer-events:none;box-sizing:border-box;';
  document.documentElement.appendChild(hl);
  var tip = document.createElement('div');
  tip.style.cssText='position:fixed;z-index:2147483647;left:8px;bottom:8px;background:#11151f;'+
    'color:#39c6da;font:12px sans-serif;padding:6px 10px;border-radius:6px;pointer-events:none;';
  tip.textContent='Click an element to hide it · Esc to cancel';
  document.documentElement.appendChild(tip);
  function uniquePath(el){
    // A structural selector that targets THIS one element (matches exactly it),
    // so we never hide a whole page just because a class is shared site-wide.
    var parts=[];
    while(el && el.nodeType===1 && el.tagName.toLowerCase()!=='html'){
      if(el.id){ parts.unshift('#'+CSS.escape(el.id)); break; }
      var part=el.tagName.toLowerCase(), parent=el.parentNode;
      if(parent){
        var same=Array.prototype.filter.call(parent.children,
                   function(c){return c.tagName===el.tagName;});
        if(same.length>1) part += ':nth-of-type('+(same.indexOf(el)+1)+')';
      }
      parts.unshift(part);
      el=el.parentNode;
    }
    return parts.join(' > ');
  }
  function sel(el){
    if(el.id) return '#'+CSS.escape(el.id);
    var s=el.tagName.toLowerCase();
    if(el.classList && el.classList.length){
      s += Array.prototype.slice.call(el.classList).slice(0,3)
            .map(function(c){return '.'+CSS.escape(c);}).join('');
    }
    // Only keep the short class selector if it is SPECIFIC (few matches);
    // otherwise (e.g. Google's reused obfuscated classes) use a unique path.
    try{ if(document.querySelectorAll(s).length<=3) return s; }catch(e){}
    return uniquePath(el);
  }
  function over(e){ var el=e.target; if(el===hl||el===tip) return;
    window.__wbTarget=el; var r=el.getBoundingClientRect();
    hl.style.left=r.left+'px'; hl.style.top=r.top+'px';
    hl.style.width=r.width+'px'; hl.style.height=r.height+'px'; }
  function done(){ window.__wbZap=false;
    if(hl.parentNode)hl.parentNode.removeChild(hl);
    if(tip.parentNode)tip.parentNode.removeChild(tip);
    document.removeEventListener('mousemove',over,true);
    document.removeEventListener('click',clk,true);
    document.removeEventListener('keydown',key,true); }
  function clk(e){ e.preventDefault(); e.stopPropagation();
    var el=window.__wbTarget; if(!el){done();return;}
    var s=sel(el); try{el.style.setProperty('display','none','important');}catch(_){}
    window.__wbOrigTitle=document.title; done(); document.title='WBZAP::'+s; }
  function key(e){ if(e.key==='Escape'){ done(); } }
  document.addEventListener('mousemove',over,true);
  document.addEventListener('click',clk,true);
  document.addEventListener('keydown',key,true);
})();"""


# ****************************************************************************
#  DEL 21L - POP-UP KILLER  (the advert box that appears INSIDE the page)
#
#  Not the same thing as the popup guard in DEL 21I. That one stops a site
#  opening new TABS. This one is for the box drawn inside the page itself - the
#  advert Vinted throws up after a shipping label, or the video box on subdl -
#  which no new-tab rule can ever touch.
#
#  Two choices, because one of them is not always safe:
#    * REMOVE IT      - the box never appears again on that site.
#    * CLICK ITS X    - the box still appears, but its own close button is
#                       pressed for you. Slower by a blink, but it lets the page
#                       run its own tidy-up, so anything that depends on the box
#                       being closed properly still works.
#
#  Why removing alone was not enough before: an overlay is normally a full-screen
#  fixed BACKDROP with the visible box inside it, and it usually locks page
#  scrolling too. Hiding just the box leaves the dark sheet over a page you
#  cannot scroll - exactly the "went black but did not go away" behaviour. So
#  when removing, the OUTERMOST full-screen overlay ancestor goes, and the scroll
#  lock is undone with it.
#
#  These boxes also appear LONG after the page has loaded (after an action, like
#  getting a label), so the rules are re-applied by a MutationObserver rather
#  than once at load.
#
#  SAFETY: a selector that matches several elements is refused unless it is made
#  unique, because a sloppy one ("div.modal") would take the QR code with it -
#  the same class of mistake that once hid an Amazon checkout QR.
# ****************************************************************************
POPUP_KILL_PICK_SCRIPT = """(function(){
  if(window.__wbKill) return;
  window.__wbKill = true;
  var hl = document.createElement('div');
  hl.style.cssText='position:fixed;z-index:2147483647;background:rgba(248,113,113,0.25);'+
    'border:2px solid #f87171;pointer-events:none;box-sizing:border-box;';
  document.documentElement.appendChild(hl);
  var tip = document.createElement('div');
  tip.style.cssText='position:fixed;z-index:2147483647;left:8px;bottom:8px;background:#11151f;'+
    'color:#f87171;font:12px sans-serif;padding:7px 11px;border-radius:6px;pointer-events:none;';
  tip.textContent='Click the pop-up you want rid of · Esc to cancel';
  document.documentElement.appendChild(tip);

  function esc(s){ return CSS.escape(s); }
  function uniquePath(el){
    var parts=[];
    while(el && el.nodeType===1 && el.tagName.toLowerCase()!=='html'){
      if(el.id){ parts.unshift('#'+esc(el.id)); break; }
      var part=el.tagName.toLowerCase(), parent=el.parentNode;
      if(parent){
        var same=Array.prototype.filter.call(parent.children,
                   function(c){return c.tagName===el.tagName;});
        if(same.length>1) part += ':nth-of-type('+(same.indexOf(el)+1)+')';
      }
      parts.unshift(part);
      el=el.parentNode;
    }
    return parts.join(' > ');
  }
  function shortSel(el){
    if(el.id) return '#'+esc(el.id);
    var s=el.tagName.toLowerCase();
    if(el.classList && el.classList.length){
      s += Array.prototype.slice.call(el.classList).slice(0,3)
            .map(function(c){return '.'+esc(c);}).join('');
    }
    return s;
  }
  function count(sel){ try{ return document.querySelectorAll(sel).length; }catch(e){ return 0; } }
  // Pick the selector that identifies exactly this one element.
  function bestSel(el){
    var s = shortSel(el);
    if(count(s) === 1) return s;
    return uniquePath(el);
  }
  // The real overlay: the OUTERMOST fixed/absolute ancestor that covers most of
  // the window. That is the backdrop, and it is what has to go.
  function overlayRoot(el){
    var best = el, node = el, depth = 0;
    var vw = window.innerWidth || 1, vh = window.innerHeight || 1;
    while(node && node.nodeType === 1 && depth++ < 12
          && node.tagName.toLowerCase() !== 'body'){
      var cs = window.getComputedStyle(node);
      var r = node.getBoundingClientRect();
      if((cs.position === 'fixed' || cs.position === 'absolute')
         && r.width >= vw * 0.75 && r.height >= vh * 0.6){
        best = node;
      }
      node = node.parentElement;
    }
    return best;
  }
  // Its own close button, if it has one.
  function findClose(root){
    var sels = 'button,[role="button"],a,svg,span,div';
    var best = null, bestScore = 0;
    var nodes = root.querySelectorAll(sels);
    var rr = root.getBoundingClientRect();
    for(var i=0; i<nodes.length && i<400; i++){
      var n = nodes[i];
      var r = n.getBoundingClientRect();
      if(r.width <= 0 || r.height <= 0) continue;
      if(r.width > 90 || r.height > 90) continue;          // a close button is small
      var txt = (n.textContent || '').trim();
      var aria = ((n.getAttribute && (n.getAttribute('aria-label') ||
                   n.getAttribute('title') || n.getAttribute('data-testid'))) || '');
      var cls = (typeof n.className === 'string' ? n.className : '') + ' ' + aria;
      var sc = 0;
      if(/close|dismiss|stäng|stang|avbryt|skip|later|no thanks/i.test(cls)) sc += 6;
      if(/^(×|✕|✖|x|X|╳)$/.test(txt)) sc += 6;
      if(/close|dismiss|stäng/i.test(txt)) sc += 3;
      if(n.tagName.toLowerCase() === 'button') sc += 2;
      // Corner position inside the box is the usual home of an X.
      if(r.top - rr.top < 70 && rr.right - r.right < 90) sc += 3;
      if(sc > bestScore){ bestScore = sc; best = n; }
    }
    if(!best || bestScore < 5) return null;
    return {sel: bestSel(best),
            label: ((best.getAttribute && best.getAttribute('aria-label')) ||
                    (best.textContent || '').trim() || 'X').slice(0, 30)};
  }

  function over(e){
    var el = e.target; if(el === hl || el === tip) return;
    window.__wbKillTarget = el;
    var r = overlayRoot(el).getBoundingClientRect();
    hl.style.left=r.left+'px'; hl.style.top=r.top+'px';
    hl.style.width=r.width+'px'; hl.style.height=r.height+'px';
  }
  function done(){ window.__wbKill=false;
    if(hl.parentNode)hl.parentNode.removeChild(hl);
    if(tip.parentNode)tip.parentNode.removeChild(tip);
    document.removeEventListener('mousemove',over,true);
    document.removeEventListener('click',clk,true);
    document.removeEventListener('keydown',key,true); }
  // Let the app cancel the picker from the OUTSIDE (its Esc handler), because
  // the page's own keydown below only fires when the web content has keyboard
  // focus - and after a right-click menu it often does not.
  window.__wbKillCancel = done;
  function clk(e){
    e.preventDefault(); e.stopPropagation();
    var el = window.__wbKillTarget; if(!el){ done(); return; }
    var root = overlayRoot(el);
    var rootSel = bestSel(root);
    var closer = findClose(root);
    var out = {sel: rootSel,
               matches: count(rootSel),
               inner: bestSel(el),
               close_sel: closer ? closer.sel : "",
               close_label: closer ? closer.label : "",
               text: (root.textContent || '').trim().slice(0, 90)};
    window.__wbOrigTitle = document.title;
    done();
    document.title = 'WBKILL::' + JSON.stringify(out);
  }
  function key(e){ if(e.key==='Escape'){ done(); } }
  document.addEventListener('mousemove',over,true);
  document.addEventListener('click',clk,true);
  document.addEventListener('keydown',key,true);
})();"""


# ****************************************************************************
#  DEL 21L-b - "REMEMBER A CHOICE" PICKER  (auto-click a button for me)
#
#  The other side of the pop-up problem: some boxes are MANDATORY and only go
#  away once you MAKE a choice - 1177's "Välj region" is the classic one.
#  Fighting it (remove / click-X) just makes it blink back. The right answer is
#  to make the choice ONCE, point at it, and have WhyBrowse click that same
#  button whenever the box reappears. The box is then satisfied and closes
#  itself - no blink, because there is nothing left to match.
#
#  This picker highlights in GREEN (a "do this" colour, vs the red "get rid of
#  this" of the killer) and reports the EXACT element clicked - not its overlay
#  backdrop. The rule is stored beside the pop-up rules (mode:"autoclick") and
#  is applied by the same engine, with the same anti-blink give-up guard.
#
#  SAFETY: an ambiguous selector (matches >1) is refused - auto-clicking several
#  things at once is never what anyone wants.
# ****************************************************************************
AUTOCLICK_PICK_SCRIPT = """(function(){
  if(window.__wbClick) return;
  window.__wbClick = true;
  var hl = document.createElement('div');
  hl.style.cssText='position:fixed;z-index:2147483647;background:rgba(52,211,153,0.22);'+
    'border:2px solid #34d399;pointer-events:none;box-sizing:border-box;';
  document.documentElement.appendChild(hl);
  var tip = document.createElement('div');
  tip.style.cssText='position:fixed;z-index:2147483647;left:8px;bottom:8px;background:#11151f;'+
    'color:#34d399;font:12px sans-serif;padding:7px 11px;border-radius:6px;pointer-events:none;';
  tip.textContent='Click the button to remember (e.g. your region) · Esc to cancel';
  document.documentElement.appendChild(tip);

  function esc(s){ return CSS.escape(s); }
  function uniquePath(el){
    var parts=[];
    while(el && el.nodeType===1 && el.tagName.toLowerCase()!=='html'){
      if(el.id){ parts.unshift('#'+esc(el.id)); break; }
      var part=el.tagName.toLowerCase(), parent=el.parentNode;
      if(parent){
        var same=Array.prototype.filter.call(parent.children,
                   function(c){return c.tagName===el.tagName;});
        if(same.length>1) part += ':nth-of-type('+(same.indexOf(el)+1)+')';
      }
      parts.unshift(part);
      el=el.parentNode;
    }
    return parts.join(' > ');
  }
  function shortSel(el){
    if(el.id) return '#'+esc(el.id);
    var s=el.tagName.toLowerCase();
    if(el.classList && el.classList.length){
      s += Array.prototype.slice.call(el.classList).slice(0,3)
            .map(function(c){return '.'+esc(c);}).join('');
    }
    return s;
  }
  function count(sel){ try{ return document.querySelectorAll(sel).length; }catch(e){ return 0; } }
  function bestSel(el){
    var s = shortSel(el);
    if(count(s) === 1) return s;
    return uniquePath(el);
  }

  function over(e){ var el=e.target; if(el===hl||el===tip) return;
    window.__wbClickTarget=el; var r=el.getBoundingClientRect();
    hl.style.left=r.left+'px'; hl.style.top=r.top+'px';
    hl.style.width=r.width+'px'; hl.style.height=r.height+'px'; }
  function done(){ window.__wbClick=false;
    if(hl.parentNode)hl.parentNode.removeChild(hl);
    if(tip.parentNode)tip.parentNode.removeChild(tip);
    document.removeEventListener('mousemove',over,true);
    document.removeEventListener('click',clk,true);
    document.removeEventListener('keydown',key,true); }
  window.__wbClickCancel = done;      // the app's Esc handler can end it too
  function clk(e){
    e.preventDefault(); e.stopPropagation();
    var el=window.__wbClickTarget; if(!el){ done(); return; }
    var s=bestSel(el);
    var lbl=((el.getAttribute && (el.getAttribute('aria-label') ||
              el.getAttribute('title'))) || (el.textContent||'').trim() ||
             el.tagName.toLowerCase());
    var out={sel:s, matches:count(s), label:lbl.replace(/\\s+/g,' ').slice(0,40)};
    window.__wbOrigTitle=document.title; done();
    document.title='WBCLICK::'+JSON.stringify(out); }
  function key(e){ if(e.key==='Escape'){ done(); } }
  document.addEventListener('mousemove',over,true);
  document.addEventListener('click',clk,true);
  document.addEventListener('keydown',key,true);
})();"""


# Applies this site's pop-up rules - at load AND whenever the page changes,
# because these boxes appear long after loading, on an action.
# __RULES__ is replaced by Python with a JSON list.
# ============================================================================
#  DEL 48 - SCROLL-LOCK GUARD  ("no scrollbar, and the mouse wheel does nothing")
# ----------------------------------------------------------------------------
#  Reported on Tradera: the page suddenly could not be scrolled - no scrollbar,
#  no wheel - and only a Refresh brought it back.
#
#  A site locks the page behind a modal by putting overflow:hidden (or the
#  position:fixed "iOS trick") on <html>/<body>, and lifts it again when the
#  modal closes. If that modal is hidden or removed by anything OTHER than the
#  site's own close handler - our nag/cookie hider, the pop-up killer, an
#  element you zapped, or the site's own script simply losing its place - the
#  lock is never lifted and the page stays frozen until you reload.
#
#  WhyBrowse already had THREE separate unlock snippets (in the cookie
#  auto-accepter, the pop-up killer and the YouTube ad-block). All three shared
#  two faults, both MEASURED rather than guessed:
#
#    * each only ran inside its own feature - the cookie one only when
#      auto-accept was switched on, and even then only for ~7 seconds after
#      load - so a lock applied LATER (opening a dialog, a lightbox, a filter
#      drawer) met nothing at all;
#
#    * all three tested `getComputedStyle(el).overflow === 'hidden'`, and
#      `overflow` is a SHORTHAND. Measured in this exact engine:
#          body{overflow:hidden}    ->  .overflow === 'hidden'       caught
#          body{overflow-y:hidden}  ->  .overflow === 'auto hidden'  MISSED
#          body{position:fixed}     ->  .overflow === 'visible'      MISSED
#          body{overflow:clip}      ->  .overflow === 'clip'         MISSED
#      so the most common spellings of a scroll lock walked straight past them.
#
#  This is ONE general guard instead. It reads overflow-Y (never the shorthand)
#  and is deliberately CAUTIOUS: it unlocks only when the content really is
#  taller than the window AND there is no visible full-screen overlay in the
#  middle of the screen - a real, visible modal is SUPPOSED to stop the page
#  behind it from scrolling. It never touches overflow-X either, which sites
#  set to hidden on purpose to stop sideways scrolling (the old code forced the
#  shorthand to `auto`, handing the page a horizontal scrollbar it never asked
#  for).
# ============================================================================
SCROLL_GUARD_SCRIPT = r"""(function(){
  if(window.__wbScrollGuard) return;
  window.__wbScrollGuard = true;

  // Own copy of the per-site override lookup (this script is standalone, so it
  // cannot borrow the one inside COSMETIC_SCRIPT's closure). NOTE: this literal
  // is a RAW python string, unlike COSMETIC_SCRIPT - so the regex is written
  // with ONE backslash here and two there. Both end up as \. in the JS.
  var cfg = __CFG__;
  function ovr(key, deflt){
    try{
      var so = cfg.siteOverrides || {},
          host = (location.hostname || '').replace(/^www\./, '');
      var best = null, bl = -1;
      for(var d in so){
        if((host === d || host.endsWith('.' + d)) && d.length > bl){
          best = so[d]; bl = d.length;
        }
      }
      if(best && key in best) return best[key];
    }catch(e){}
    return deflt;
  }
  // Off globally, or switched off for this site in "Exceptions for this site".
  if(!ovr('scroll_guard', cfg.scrollGuard !== false)) return;

  var CHECK_MS   = 700;    // how often to look
  var NEED_TICKS = 2;      // locked this many checks running before acting
  var MAX_FREES  = 8;      // then stop fighting a site that re-locks on purpose

  var locked = 0, frees = 0;
  window.__wbScrollGuardQuiet = false;

  function tallerThanWindow(){
    var vh = window.innerHeight, de = document.documentElement, b = document.body;
    if(de && de.scrollHeight > vh + 8) return true;
    if(b){
      if(b.scrollHeight > vh + 8) return true;
      // MEASURED, and the reason this needs three tries: the position:fixed
      // lock takes <body> OUT OF FLOW, so documentElement collapses to one
      // screen (scrollHeight 600) - and body's OWN scrollHeight reports 600
      // too, even though the body really is 4000px tall. Only its bounding
      // box tells the truth. Without this the guard concludes "nothing to
      // scroll here" on precisely the page that is stuck.
      try{
        if(b.getBoundingClientRect().height > vh + 8) return true;
      }catch(e){}
    }
    return false;
  }

  // Read overflow-Y, NOT the `overflow` shorthand: the shorthand reads back as
  // "auto hidden" whenever x and y differ, which is exactly why the older
  // checks missed the commonest lock of all.
  function lockKind(el){
    if(!el) return null;
    try{
      var cs = window.getComputedStyle(el);
      if(cs.position === 'fixed') return 'fixed';
      var oy = cs.overflowY;
      if(oy === 'hidden' || oy === 'clip') return 'overflow';
    }catch(e){}
    return null;
  }

  // A lock is not always parked on html/body. Single-page apps (Tradera, and
  // anything Next.js-shaped) hang it on their OWN full-height wrapper -
  // body > div#__next{overflow:hidden;height:100vh} - and then html and body
  // both look perfectly innocent. Worse, that wrapper clips the document down
  // to one screen, so documentElement.scrollHeight equals the window height
  // and tallerThanWindow() answers "nothing to scroll here" on precisely the
  // page that is stuck. "Get scrolling back" in the right-click menu already
  // covered this shape; the AUTOMATIC guard did not, which is why a reload was
  // the only cure. Scanned 2 deep and 6 wide from <body>, and only elements
  // that (a) fill the viewport and (b) really are clipping something - their
  // own scrollHeight overflows the window. A proper app shell that scrolls in
  // an inner pane has scrollHeight == the window height, so it is left alone.
  function lockedWrappers(){
    var out = [], vw = window.innerWidth, vh = window.innerHeight;
    try{
      var lvl = document.body
        ? Array.prototype.slice.call(document.body.children, 0, 6) : [];
      for(var d = 0; d < 2 && lvl.length; d++){
        var next = [];
        for(var i = 0; i < lvl.length; i++){
          var el = lvl[i];
          if(!el || el.nodeType !== 1) continue;
          var cs = window.getComputedStyle(el);
          if(cs.display === 'none' || cs.visibility === 'hidden') continue;
          var r = el.getBoundingClientRect();
          if(r.width >= vw * 0.9 && r.height >= vh * 0.8 &&
             (cs.overflowY === 'hidden' || cs.overflowY === 'clip') &&
             el.scrollHeight > vh + 8){
            out.push(el);
          }
          next = next.concat(Array.prototype.slice.call(el.children, 0, 6));
        }
        lvl = next;
      }
    }catch(e){}
    return out;
  }

  function lockedNow(){
    if(tallerThanWindow() &&
       (lockKind(document.documentElement) || lockKind(document.body))) return true;
    return lockedWrappers().length > 0;
  }

  // Is a real modal actually up? One hit-test at the centre of the screen, so
  // this costs the same on a huge page as on a small one. If something visible
  // and roughly full-screen sits on top, the lock is legitimate: leave it.
  function overlayUp(){
    try{
      var vw = window.innerWidth, vh = window.innerHeight;
      var els = document.elementsFromPoint(vw / 2, vh / 2) || [];
      for(var i = 0; i < els.length && i < 6; i++){
        var e = els[i];
        if(!e || e === document.body || e === document.documentElement) continue;
        var cs = window.getComputedStyle(e);
        if(cs.position !== 'fixed' && cs.position !== 'absolute' &&
           cs.position !== 'sticky') continue;
        if(cs.visibility === 'hidden' || cs.display === 'none') continue;
        if(parseFloat(cs.opacity || '1') < 0.05) continue;
        var r = e.getBoundingClientRect();
        if(r.width >= vw * 0.5 && r.height >= vh * 0.4) return true;
      }
    }catch(e){}
    return false;
  }

  function release(){
    var moved = 0;
    [document.documentElement, document.body].forEach(function(el){
      if(!el) return;
      try{
        var cs = window.getComputedStyle(el);
        var oy = cs.overflowY;
        if(oy === 'hidden' || oy === 'clip'){
          el.style.setProperty('overflow-y', 'auto', 'important');
          moved++;
        }
        if(cs.position === 'fixed'){
          // The "iOS trick": body is pinned with a negative top that REMEMBERS
          // where you were. Put the page back there instead of jumping to 0.
          var top = parseInt(cs.top, 10);
          el.style.setProperty('position', 'static', 'important');
          el.style.setProperty('top', 'auto', 'important');
          el.style.setProperty('width', 'auto', 'important');
          if(!isNaN(top) && top < 0){
            window.__wbScrollOK = 1;          // this put-back is OURS (DEL 51)
            window.scrollTo(0, -top);
          }
          moved++;
        }
      }catch(e){}
    });
    // ...and the same lock parked on a full-height wrapper inside <body>.
    lockedWrappers().forEach(function(el){
      try{ el.style.setProperty('overflow-y', 'auto', 'important'); moved++; }catch(e){}
    });
    return moved;
  }

  function tick(){
    if(window.__wbScrollGuardQuiet) return;
    if(!lockedNow()){ locked = 0; return; }
    if(overlayUp()){ locked = 0; return; }      // a real modal - hands off
    locked++;
    if(locked < NEED_TICKS) return;             // let a modal finish opening
    locked = 0;
    if(release()){
      frees++;
      if(frees >= MAX_FREES){
        // The site keeps putting the lock back and clearly means it. Stop,
        // rather than flicker forever; "Get scrolling back" in the right-click
        // menu is still there if it really is stuck.
        window.__wbScrollGuardQuiet = true;
      }
    }
  }

  setInterval(tick, CHECK_MS);
  // A lock is nearly always applied by changing style or class on html/body,
  // so react to that at once instead of waiting for the next tick.
  try{
    var mo = new MutationObserver(function(){ tick(); });
    mo.observe(document.documentElement,
               {attributes: true, attributeFilter: ['style', 'class']});
    if(document.body){
      mo.observe(document.body,
                 {attributes: true, attributeFilter: ['style', 'class']});
    }
  }catch(e){}
  // A fresh page gets a fresh budget.
  window.addEventListener('pageshow', function(){
    frees = 0; window.__wbScrollGuardQuiet = false;
  });
})();"""


# The same release, run once on demand from the right-click menu. No detection,
# no conditions, no waiting: you say the page is stuck, so it gets unstuck -
# even if a modal IS up, because at that point you have already decided.
SCROLL_UNLOCK_NOW_JS = r"""(function(){
  var n = 0;
  [document.documentElement, document.body].forEach(function(el){
    if(!el) return;
    try{
      var cs = window.getComputedStyle(el);
      if(cs.overflowY === 'hidden' || cs.overflowY === 'clip'){
        el.style.setProperty('overflow-y','auto','important'); n++;
      }
      if(cs.position === 'fixed'){
        var top = parseInt(cs.top, 10);
        el.style.setProperty('position','static','important');
        el.style.setProperty('top','auto','important');
        el.style.setProperty('width','auto','important');
        if(!isNaN(top) && top < 0){
          window.__wbScrollOK = 1;            // this put-back is OURS (DEL 51)
          window.scrollTo(0, -top);
        }
        n++;
      }
    }catch(e){}
  });
  // Also lift a lock parked on a full-height wrapper just inside <body> - a
  // common variant where html and body themselves look perfectly innocent.
  try{
    var k = document.body ? document.body.children : [];
    for(var i = 0; i < k.length && i < 6; i++){
      var cs2 = window.getComputedStyle(k[i]);
      if((cs2.overflowY === 'hidden' || cs2.overflowY === 'clip') &&
         k[i].scrollHeight > window.innerHeight + 8){
        k[i].style.setProperty('overflow-y','auto','important'); n++;
      }
    }
  }catch(e){}
  window.__wbScrollGuardQuiet = false;
  return n;
})();"""


# ============================================================================
#  DEL 51 - "KEEP MY PLACE": THE PAGE MAY NOT YANK YOU BACK
# ----------------------------------------------------------------------------
#  Reported: "when I open a page and start scrolling, every now and then the
#  window drags itself to a specific place - as if it had not finished loading
#  and MUST start somewhere particular."
#
#  That is exactly what it is. A page is not finished when it first appears:
#  late stylesheets, fonts, adverts and lazy images keep arriving for seconds
#  afterwards, and with them come scroll calls - a framework restoring "where
#  you were", an anchor/#fragment applied late, a banner scrolling itself into
#  view, an ad slot pushing the layout about. They all land AFTER you started
#  reading, so they take the page away from you.
#
#  The rule here is the simple one: ONCE YOU HAVE SCROLLED THIS PAGE YOURSELF,
#  THE PAGE DOES NOT GET TO MOVE YOU. Not a rule about who is "right" - a rule
#  about who asked last. Four things keep that from breaking real sites:
#
#   * it only guards the MAIN page scroll. Inner panels (a chat that scrolls to
#     the newest message, a spreadsheet grid, a dropdown) are never touched;
#   * a jump you ASKED for still happens - anything within RESPOND_MS of your
#     wheel/key/touch, anything within CLICK_MS of a click (a menu link, a
#     "back to top" button, an in-page anchor), and a smooth-scroll animation
#     once it has been let through keeps its pass;
#   * a single-page app that changes route (pushState/popstate/hashchange) is a
#     NEW page: the hold is dropped so it can land at the top as it should;
#   * it gives up after MAX_FIX corrections. A site that insists that hard is
#     doing it on purpose, and flickering forever helps nobody.
#
#  Injected at DocumentCreation so it wraps window.scrollTo & co. BEFORE the
#  page's own scripts can grab them. Anything WhyBrowse itself scrolls on
#  purpose (the scroll-lock release, split-view sync scrolling) sets
#  window.__wbScrollOK = 1 first, which buys one free pass through the guard.
#  It also publishes window.__wbUserScrolled, which is how "go to last
#  position" and "jump to a word" know to stop fighting you (they retry for a
#  couple of seconds after load - the exact window in which you start reading).
# ============================================================================
KEEP_SCROLL_SCRIPT = r"""(function(){
  if(window.__wbKeepScroll) return;
  window.__wbKeepScroll = true;
  if(window.top !== window) return;        // the main frame owns the page scroll

  var cfg = __CFG__;
  function ovr(key, deflt){
    try{
      var so = cfg.siteOverrides || {},
          host = (location.hostname || '').replace(/^www\./, '');
      var best = null, bl = -1;
      for(var d in so){
        if((host === d || host.endsWith('.' + d)) && d.length > bl){
          best = so[d]; bl = d.length;
        }
      }
      if(best && key in best) return best[key];
    }catch(e){}
    return deflt;
  }

  var W = window, D = document;

  var HOLD_MS    = 20000;  // your scroll holds the page this long
  var RESPOND_MS = 400;    // a page scroll this soon after your input is yours
  var GLIDE_MS   = 900;    // smooth-scrolling still counts as your gesture
  var CLICK_MS   = 1200;   // a jump this soon after a click is the click's doing
  var CHAIN_MS   = 400;    // an allowed animation keeps its pass this long
  var MIN_JUMP   = 60;     // px - never fight a nudge
  var BIG_JUMP   = 220;    // px - the watchdog only undoes moves this big
  var MAX_FIX    = 6;      // then let the site have its way

  var lastUser = 0, lastClick = 0, lastY = 0, lastX = 0;
  var pointerDown = false, fixes = 0, armed = false;
  var quietUntil = 0, allowUntil = 0;

  function now(){ return Date.now(); }
  function curY(){ return W.pageYOffset || 0; }
  function curX(){ return W.pageXOffset || 0; }
  function remember(){ lastY = curY(); lastX = curX(); }

  // isScroll = an input that MOVES the page (wheel, PageDown, a drag of the
  // scrollbar). A plain click is input too, but it does not mean "I have put
  // this page where I want it", so it must not arm the hold on its own.
  function user(isScroll){
    lastUser = now();
    if(isScroll){ armed = true; W.__wbUserScrolled = true; }
    remember();
  }

  function newPage(){
    armed = false; fixes = 0; allowUntil = 0;
    W.__wbUserScrolled = false;
  }
  newPage();

  try{
    W.addEventListener('wheel',      function(){ user(true); },  true);
    W.addEventListener('touchmove',  function(){ user(true); },  true);
    W.addEventListener('touchstart', function(){ user(false); }, true);
    W.addEventListener('keydown', function(e){
      var k = (e && e.key) || '';
      user(k === 'PageUp' || k === 'PageDown' || k === 'Home' || k === 'End' ||
           k === ' ' || k === 'Spacebar' || k.indexOf('Arrow') === 0);
    }, true);
    W.addEventListener('pointerdown', function(){
      pointerDown = true; lastClick = now(); user(false);
    }, true);
    W.addEventListener('pointerup', function(){
      pointerDown = false; lastClick = now(); lastUser = now();
    }, true);
    // A route change in a single-page app is a new page: drop the hold, or the
    // app cannot land the new view at the top where it belongs.
    W.addEventListener('popstate',   newPage, true);
    W.addEventListener('hashchange', newPage, true);
    W.addEventListener('pagehide',   newPage, true);
    ['pushState', 'replaceState'].forEach(function(nm){
      try{
        var o = history[nm];
        if(typeof o !== 'function') return;
        history[nm] = function(){ newPage(); return o.apply(history, arguments); };
      }catch(e){}
    });
  }catch(e){}

  // Everything above runs even when the guard is switched off, because
  // __wbUserScrolled is what stops "go to last position" and "jump to a word"
  // from pulling the page around under you. Only the BLOCKING is optional.
  if(!ovr('keep_scroll', cfg.keepScroll !== false)) return;

  // WhyBrowse's own put-backs buy one free pass - and the watchdog has to be
  // told as well, or it would undo the very move the wrapper just allowed.
  function escaped(){
    if(W.__wbScrollOK){
      W.__wbScrollOK = 0;
      quietUntil = now() + 300;
      return true;
    }
    return false;
  }

  // targetY = where the call wants to put us, or null when we cannot tell -
  // and when we cannot tell we let it through. Guessing wrong in that
  // direction only costs a jump; guessing wrong the other way breaks a page.
  function hold(targetY){
    if(!armed) return false;
    var t = now();
    if(pointerDown) return false;
    if(t - lastUser > HOLD_MS) return false;            // you left it alone
    if(t - lastUser < RESPOND_MS){ allowUntil = t + CHAIN_MS; return false; }
    if(t < allowUntil){ allowUntil = t + CHAIN_MS; return false; }
    if(t - lastClick < CLICK_MS) return false;          // your click, its answer
    if(fixes >= MAX_FIX) return false;
    if(targetY === null || targetY === undefined) return false;
    var want = Number(targetY);
    if(want !== want) return false;                     // NaN
    if(Math.abs(want - curY()) < MIN_JUMP) return false;
    fixes++;
    return true;
  }

  function optTop(a, b){
    try{
      if(a && typeof a === 'object') return (a.top == null) ? null : Number(a.top);
      return (b == null) ? null : Number(b);
    }catch(e){ return null; }
  }
  function optDelta(a, b){
    try{
      if(a && typeof a === 'object') return Number(a.top || 0);
      return Number(b || 0);
    }catch(e){ return 0; }
  }
  function isMain(el){
    return el === D.documentElement || el === D.body || el === D.scrollingElement;
  }

  var origTo = W.scrollTo, origBy = W.scrollBy, origSc = W.scroll;

  W.scrollTo = function(a, b){
    if(!escaped() && hold(optTop(a, b))) return;
    return origTo.apply(W, arguments);
  };
  W.scroll = function(a, b){
    if(!escaped() && hold(optTop(a, b))) return;
    return origSc.apply(W, arguments);
  };
  W.scrollBy = function(a, b){
    if(!escaped() && hold(curY() + optDelta(a, b))) return;
    return origBy.apply(W, arguments);
  };

  try{
    var eiv = Element.prototype.scrollIntoView;
    Element.prototype.scrollIntoView = function(){
      var ty = null;
      try{
        ty = isMain(this) ? 0 : (curY() + this.getBoundingClientRect().top);
      }catch(e){ ty = null; }
      if(!escaped() && hold(ty)) return;
      return eiv.apply(this, arguments);
    };
  }catch(e){}

  // document.documentElement.scrollTop = 0 is the other half of the same
  // trick. Only the MAIN scroller is guarded: every other element pays two
  // identity comparisons and nothing else.
  try{
    var dsc = Object.getOwnPropertyDescriptor(Element.prototype, 'scrollTop');
    if(dsc && dsc.get && dsc.set){
      Object.defineProperty(Element.prototype, 'scrollTop', {
        configurable: true, enumerable: dsc.enumerable, get: dsc.get,
        set: function(v){
          if(isMain(this) && !escaped() && hold(Number(v))) return;
          return dsc.set.call(this, v);
        }
      });
    }
  }catch(e){}

  try{
    ['scrollTo', 'scroll', 'scrollBy'].forEach(function(nm){
      var o = Element.prototype[nm];
      if(typeof o !== 'function') return;
      Element.prototype[nm] = function(a, b){
        if(isMain(this)){
          var ty = (nm === 'scrollBy') ? (curY() + optDelta(a, b)) : optTop(a, b);
          if(!escaped() && hold(ty)) return;
        }
        return o.apply(this, arguments);
      };
    });
  }catch(e){}

  // The wrappers cannot catch a jump the ENGINE makes on its own (a late
  // anchor, a restored position, a layout that re-lands). This notices one
  // after the fact and puts the page back where you had it.
  try{
    W.addEventListener('scroll', function(e){
      var tgt = e && e.target;
      if(tgt && tgt !== D && tgt !== D.documentElement && tgt !== D.body) return;
      var t = now();
      if(pointerDown){ user(true); return; }      // dragging the scrollbar IS you
      // A move WE made or allowed: take the new position as where you are,
      // otherwise the next scroll event measures against the old one and
      // "corrects" a jump that never happened.
      if(t < quietUntil){ remember(); return; }
      if(!armed){ remember(); return; }
      if(t - lastUser < GLIDE_MS){ remember(); return; }
      if(t - lastUser > HOLD_MS){ remember(); return; }
      if(t - lastClick < CLICK_MS){ remember(); return; }
      if(t < allowUntil){ remember(); return; }
      if(Math.abs(curY() - lastY) < BIG_JUMP){ remember(); return; }
      if(fixes >= MAX_FIX){ remember(); return; }
      fixes++;
      quietUntil = t + 300;
      try{ origTo.call(W, lastX, lastY); }catch(_e){}
    }, true);
  }catch(e){}
})();"""


POPUP_KILL_APPLY_SCRIPT = r"""(function(){
  var RULES = __RULES__;
  if(!RULES.length) return;
  if(window.__wbKillApply){ window.__wbKillRules = RULES; return; }
  window.__wbKillApply = true;
  window.__wbKillRules = RULES;

  function unlockScroll(){
    // Overlays lock the page behind them. Undo that, or removing the box
    // leaves a page that cannot be scrolled.
    [document.body, document.documentElement].forEach(function(b){
      if(!b) return;
      try{
        var cs = window.getComputedStyle(b);
        if(cs.overflow === 'hidden') b.style.setProperty('overflow','auto','important');
        if(cs.position === 'fixed'){
          b.style.setProperty('position','static','important');
          b.style.setProperty('top','auto','important');
        }
      }catch(e){}
    });
  }

  // Per-box click bookkeeping. "close" mode presses the page's own X, but some
  // boxes are MANDATORY (e.g. 1177's "Välj region") and pop straight back after
  // every close - which turns into an endless on/off blink. So we give up on a
  // box that keeps returning, and never flash it forever. A box that genuinely
  // reappears much later (after a real action) resets and gets one clean close.
  var CLOSE = {};                 // key -> {n: quick-attempts, last: ts, dead: bool}
  var CLOSE_CAP  = 2;             // at most this many close-clicks in a burst...
  var CLOSE_GAP  = 1200;          // ...never faster than this apart...
  var CLOSE_COOL = 8000;          // ...and this much idle time = a fresh appearance
  function vis(el){               // don't click a hidden match
    try{ var r = el.getBoundingClientRect();
      if(r.width <= 0 || r.height <= 0) return false;
      var cs = window.getComputedStyle(el);
      return cs.visibility !== 'hidden' && cs.display !== 'none';
    }catch(e){ return true; }
  }
  function apply(){
    var rules = window.__wbKillRules || [];
    for(var i=0; i<rules.length; i++){
      var r = rules[i];
      if(!r || !r.sel) continue;
      var nodes;
      try{ nodes = document.querySelectorAll(r.sel); }catch(e){ continue; }
      for(var j=0; j<nodes.length; j++){
        var el = nodes[j];
        if(r.mode === 'close' || r.mode === 'autoclick'){
          // 'close'     = press the box's OWN X, so its tidy-up runs.
          // 'autoclick' = press the very element the user pointed at (e.g. their
          //               region), so a MANDATORY box makes its choice and goes.
          var btn = null;
          if(r.mode === 'autoclick'){
            btn = (el && vis(el)) ? el : null;
          }else{
            try{ btn = r.close_sel ? (el.querySelector(r.close_sel) ||
                                      document.querySelector(r.close_sel)) : null; }catch(e){}
          }
          if(btn){
            var key = r.sel + '|' + j;
            var now = Date.now();
            var st  = CLOSE[key] || (CLOSE[key] = {n:0, last:0, dead:false});
            if(now - st.last > CLOSE_COOL){ st.n = 0; st.dead = false; }  // fresh
            if(!st.dead && now - st.last > CLOSE_GAP){
              st.last = now; st.n++;
              if(st.n > CLOSE_CAP){        // keeps coming right back -> stop the blink
                st.dead = true;
              } else {
                try{ btn.click(); }catch(e){}
                setTimeout(unlockScroll, 120);
              }
            }
          }
        } else {
          if(el.getAttribute('data-wbkilled')) continue;
          try{
            el.setAttribute('data-wbkilled','1');
            el.style.setProperty('display','none','important');
          }catch(e){}
          unlockScroll();
        }
      }
    }
  }
  apply();
  document.addEventListener('DOMContentLoaded', apply);
  try{
    new MutationObserver(function(){
      clearTimeout(window.__wbKillT);
      window.__wbKillT = setTimeout(apply, 60);     // coalesce bursts
    }).observe(document.documentElement, {childList:true, subtree:true});
  }catch(e){}
  setInterval(apply, 2000);        // belt and braces for late/animated boxes
})();"""


# ---- Un-hide manager: reveal this site's hidden elements, click one to un-hide it
UNHIDE_SCRIPT = """(function(){
  if(window.__wbUnhide) return; window.__wbUnhide=true;
  var sels = __SELS__, found=0;
  sels.forEach(function(s){ try{ document.querySelectorAll(s).forEach(function(el){
    el.style.setProperty('display','revert','important');
    el.style.setProperty('visibility','visible','important');
    el.style.setProperty('outline','2px dashed #ff5555','important');
    el.style.setProperty('cursor','pointer','important');
    el.setAttribute('data-wbsel', s); found++; }); }catch(e){} });
  var tip=document.createElement('div');
  tip.style.cssText='position:fixed;z-index:2147483647;left:8px;bottom:8px;background:#11151f;'+
    'color:#ff8888;font:12px sans-serif;padding:6px 10px;border-radius:6px;';
  tip.textContent = found ? 'Hidden elements shown (red). Click one to un-hide it · Esc to finish'
                          : 'No hidden elements are present on this page right now · Esc';
  document.documentElement.appendChild(tip);
  function clk(e){ var el=e.target.closest('[data-wbsel]'); if(!el) return;
    e.preventDefault(); e.stopPropagation();
    window.__wbOrigTitle=document.title; document.title='WBUNHIDE::'+el.getAttribute('data-wbsel'); }
  function key(e){ if(e.key==='Escape'){ done(); location.reload(); } }
  function done(){ window.__wbUnhide=false; if(tip.parentNode)tip.parentNode.removeChild(tip);
    document.removeEventListener('click',clk,true); document.removeEventListener('keydown',key,true); }
  document.addEventListener('click',clk,true);
  document.addEventListener('keydown',key,true);
})();"""


# ---- Sticky picker: click a section to freeze it at the top while scrolling ----
STICKY_SCRIPT = """(function(){
  if(window.__wbPick) return;
  window.__wbPick = true;
  var hl=document.createElement('div');
  hl.style.cssText='position:fixed;z-index:2147483647;background:rgba(124,92,255,0.30);'+
    'border:2px solid #7c5cff;pointer-events:none;box-sizing:border-box;';
  document.documentElement.appendChild(hl);
  var tip=document.createElement('div');
  tip.style.cssText='position:fixed;z-index:2147483647;left:8px;bottom:8px;background:#11151f;'+
    'color:#7c5cff;font:12px sans-serif;padding:6px 10px;border-radius:6px;pointer-events:none;';
  tip.textContent='Click a section to freeze it at the top · Esc to cancel';
  document.documentElement.appendChild(tip);
  function sel(el){ if(el.id) return '#'+CSS.escape(el.id);
    var s=el.tagName.toLowerCase();
    if(el.classList && el.classList.length){
      s+=Array.prototype.slice.call(el.classList).slice(0,3).map(function(c){return '.'+CSS.escape(c);}).join('');}
    return s; }
  function over(e){ var el=e.target; if(el===hl||el===tip) return; window.__wbTarget=el;
    var r=el.getBoundingClientRect(); hl.style.left=r.left+'px';hl.style.top=r.top+'px';
    hl.style.width=r.width+'px';hl.style.height=r.height+'px'; }
  function done(){ window.__wbPick=false;
    if(hl.parentNode)hl.parentNode.removeChild(hl); if(tip.parentNode)tip.parentNode.removeChild(tip);
    document.removeEventListener('mousemove',over,true);
    document.removeEventListener('click',clk,true);
    document.removeEventListener('keydown',key,true); }
  function clk(e){ e.preventDefault(); e.stopPropagation(); var el=window.__wbTarget; if(!el){done();return;}
    var s=sel(el);
    try{el.style.setProperty('position','sticky','important');el.style.setProperty('top','0','important');
        el.style.setProperty('z-index','99990','important');}catch(_){}
    window.__wbOrigTitle=document.title; done(); document.title='WBSTICK::'+s; }
  function key(e){ if(e.key==='Escape'){ done(); } }
  document.addEventListener('mousemove',over,true);
  document.addEventListener('click',clk,true);
  document.addEventListener('keydown',key,true);
})();"""


# ---- Movement freezer: click a moving element to stop just THAT one ----
FREEZE_PICK_SCRIPT = """(function(){
  if(window.__wbPick) return;
  window.__wbPick = true;
  var hl=document.createElement('div');
  hl.style.cssText='position:fixed;z-index:2147483647;background:rgba(57,198,218,0.30);'+
    'border:2px solid #39c6da;pointer-events:none;box-sizing:border-box;';
  document.documentElement.appendChild(hl);
  var tip=document.createElement('div');
  tip.style.cssText='position:fixed;z-index:2147483647;left:8px;bottom:8px;background:#11151f;'+
    'color:#39c6da;font:12px sans-serif;padding:6px 10px;border-radius:6px;pointer-events:none;';
  tip.textContent='Click a moving element to stop it · Esc to cancel';
  document.documentElement.appendChild(tip);
  function sel(el){ if(el.id) return '#'+CSS.escape(el.id);
    var s=el.tagName.toLowerCase();
    if(el.classList && el.classList.length){
      s+=Array.prototype.slice.call(el.classList).slice(0,3).map(function(c){return '.'+CSS.escape(c);}).join('');}
    return s; }
  function over(e){ var el=e.target; if(el===hl||el===tip) return; window.__wbTarget=el;
    var r=el.getBoundingClientRect(); hl.style.left=r.left+'px';hl.style.top=r.top+'px';
    hl.style.width=r.width+'px';hl.style.height=r.height+'px'; }
  function done(){ window.__wbPick=false;
    if(hl.parentNode)hl.parentNode.removeChild(hl); if(tip.parentNode)tip.parentNode.removeChild(tip);
    document.removeEventListener('mousemove',over,true);
    document.removeEventListener('click',clk,true);
    document.removeEventListener('keydown',key,true); }
  function clk(e){ e.preventDefault(); e.stopPropagation(); var el=window.__wbTarget; if(!el){done();return;}
    var s=sel(el);
    // Stop this element (and its children) right away so the user sees it work.
    try{ el.getAnimations({subtree:true}).forEach(function(a){try{a.pause();}catch(_){}});
         el.style.setProperty('animation','none','important');
         el.style.setProperty('transition','none','important'); }catch(_){}
    window.__wbOrigTitle=document.title; done(); document.title='WBFREEZE::'+s; }
  function key(e){ if(e.key==='Escape'){ done(); } }
  document.addEventListener('mousemove',over,true);
  document.addEventListener('click',clk,true);
  document.addEventListener('keydown',key,true);
})();"""


# ****************************************************************************
#  DEL 21G - AUCTION CLOCK  (never trust the site's own countdown again)
#
#  WHY THIS EXISTS
#  A bid was placed on Tradera with the page saying "8 seconds left" and the
#  auction was already over. A site countdown can be wrong for several reasons
#  and NONE of them are visible to you:
#    * it is drawn from the browser's clock, which drifts from the seller's
#      server (WhyBrowse measured ~1 s here, but nothing keeps it small);
#    * the page (or the tab) may have been restored/served from cache, so the
#      "now" it started counting from is older than it looks;
#    * a tick-based countdown (subtract 1 each second) loses time whenever the
#      renderer is busy or throttled, and never catches up;
#    * and the bid still has to TRAVEL to the server - a bid you send with 8 s
#      showing may arrive after the hammer even if the clock was right.
#
#  WHAT IT DOES
#  Reads the auction's ABSOLUTE end time out of the page's own embedded data
#  (an ISO timestamp, immune to staleness), measures the offset between this
#  computer and the AUCTION SITE'S OWN SERVER clock (HEAD request -> Date
#  header, corrected for round-trip), and shows its own countdown from those
#  two facts. It also parses the site's visible countdown and tells you, in
#  seconds, how wrong it is. Below the safety margin it turns red and says so.
#  Nothing blinks and nothing is animated (house rule).
#
#  __CFG__ is replaced by Python: {"margin": <seconds>, "debug": <bool>}
# ****************************************************************************
AUCTION_CLOCK_SCRIPT = r"""(function(){
  if(window.__wbAuction) return; window.__wbAuction = true;
  var CFG = __CFG__;
  var MARGIN = (CFG.margin || 20) * 1000;
  // Only reveal the panel in the closing window (default: last 3 minutes) and
  // only while the auction is still running. "8 days left" or "ended 2 h ago"
  // is noise. showWithn is in ms; 0 means "always show" (used by the manual
  // Troubleshoot -> run-here action, where you asked for it explicitly).
  var SHOW_WITHIN = (CFG.showWithin || 0) * 1000;
  var userClosed  = false;

  // ---- 1) server clock -----------------------------------------------------
  // offset = serverTime - localTime, in ms. The Date header is whole seconds,
  // so the true instant sits somewhere in that second: assume its middle.
  var offset = 0, rtt = 9e9, synced = false;
  function serverNow(){ return Date.now() + offset; }
  function sync(){
    var t0 = Date.now();
    fetch(location.origin + '/favicon.ico?wbclock=' + t0,
          {method:'HEAD', cache:'no-store', credentials:'omit'})
      .then(function(r){
        var t1 = Date.now(), d = r.headers.get('date');
        if(!d) return;
        var srv = Date.parse(d);
        if(!srv) return;
        var thisRtt = t1 - t0;
        // Keep the sample with the SHORTEST round-trip: it is the most precise.
        if(!synced || thisRtt <= rtt){
          offset = (srv + 500) - (t0 + t1) / 2;
          rtt = thisRtt;
          synced = true;
        }
      }).catch(function(){});
  }
  sync(); setTimeout(sync, 1500); setTimeout(sync, 6000);
  setInterval(sync, 60000);

  // ---- 2) the auction's absolute end time ---------------------------------
  // Taken from the page's embedded data, NOT from anything relative, so it
  // stays right however stale the rendered page is.
  //
  // CAREFUL: an item page carries the end time of MANY auctions - the one you
  // are looking at plus every "related item" in the sidebar. A real Tradera
  // page checked while writing this had 17 of them, and simply taking the
  // soonest one landed on a recommendation ending THREE HOURS earlier. So the
  // end time is tied to the item id out of the URL, and the panel prints the
  // date it picked so a wrong guess is visible instead of silent.
  var END_RE = '"(?:end(?:Date|Time|sAt|ingAt|_date|_time)?|closingDate|closeDate|auctionEnd(?:Date|Time)?)"\\s*:\\s*(?:"([^"]{8,40})"|(\\d{12,13}))';
  function sane(v){
    if(!v || isNaN(v)) return null;
    var dt = v - Date.now();
    if(dt < -6*3600*1000 || dt > 400*86400*1000) return null;   // not this sale
    return v;
  }
  // Long digit runs in the URL path: for /item/1000617/740416359/slug that is
  // the category and the item id; the item id is the longer, later one.
  function urlIds(){
    var ids = (location.pathname.match(/\d{6,}/g) || []);
    ids.sort(function(a, b){ return b.length - a.length; });
    return ids.slice(0, 4);
  }
  // Every inline script, biggest first. NOTE: do not cap this by COUNT - the
  // real Tradera page keeps its data in script tag number 81 of 83, so an
  // "only look at the first 80" limit threw away the only one that mattered.
  // The budget is on characters scanned instead.
  function scriptTexts(){
    var out = [], nodes = document.querySelectorAll('script');
    for(var i=0; i<nodes.length; i++){
      var t = nodes[i].textContent || '';
      if(t.length > 40 && t.length < 4000000) out.push(t);
    }
    out.sort(function(a, b){ return b.length - a.length; });   // data blocks first
    var budget = 8000000, keep = [];
    for(var j=0; j<out.length; j++){
      budget -= out[j].length;
      if(budget < 0) break;
      keep.push(out[j]);
    }
    return keep;
  }
  // A) the end time that sits in the SAME data block as this item's id.
  function byItemId(texts, ids){
    for(var k=0; k<ids.length; k++){
      var idRe = new RegExp('"(?:itemId|itemID|itemid|listingId|id)"\\s*:\\s*"?' + ids[k] + '"?', 'g');
      for(var i=0; i<texts.length; i++){
        var t = texts[i], m;
        idRe.lastIndex = 0;
        while((m = idRe.exec(t))){
          var window_ = t.substr(m.index, 4000);       // the object around it
          var em = new RegExp(END_RE, 'i').exec(window_);
          if(em){
            var v = sane(em[1] ? Date.parse(em[1]) : parseInt(em[2], 10));
            if(v) return {ms: v, sure: true};
          }
        }
      }
    }
    return null;
  }
  // B) no id match: the end time lying CLOSEST to the id anywhere in the text.
  function byNearest(texts, ids){
    var best = null;
    for(var i=0; i<texts.length; i++){
      var t = texts[i], m, re = new RegExp(END_RE, 'gi');
      while((m = re.exec(t))){
        var v = sane(m[1] ? Date.parse(m[1]) : parseInt(m[2], 10));
        if(!v) continue;
        var dist = 1e9;
        for(var k=0; k<ids.length; k++){
          var p = -1;
          while((p = t.indexOf(ids[k], p + 1)) >= 0){
            dist = Math.min(dist, Math.abs(p - m.index));
          }
        }
        if(best === null || dist < best.dist) best = {ms: v, dist: dist, sure: false};
      }
    }
    return best;
  }
  // C) plain markup (sites that put the end time in an attribute).
  function fromMarkup(){
    var els = document.querySelectorAll(
      'time[datetime],[data-end-date],[data-endtime],[data-end],[data-end-time]');
    for(var i=0; i<els.length; i++){
      var e = els[i];
      var s = e.getAttribute('datetime') || e.getAttribute('data-end-date')
            || e.getAttribute('data-endtime') || e.getAttribute('data-end')
            || e.getAttribute('data-end-time');
      var v = s && sane(Date.parse(s));
      if(v) return {ms: v, sure: false};
    }
    return null;
  }

  var texts = scriptTexts(), ids = urlIds();
  var hit = (ids.length ? (byItemId(texts, ids) || byNearest(texts, ids)) : null)
            || fromMarkup();
  if(!hit || !hit.ms){ window.__wbAuction = false; return; }   // not an auction page
  var endMs = hit.ms, endSure = !!hit.sure;

  // ---- 3) what the SITE claims, so the two can be compared ----------------
  // Small text nodes only, Swedish + English units, plus a strict h:mm:ss.
  //
  // Two traps avoided here. A bare "22:10" on the page is the auction's END
  // TIME, not "22 hours left", so the mm:ss form is NOT accepted - only the
  // three-part h:mm:ss. And of the remaining candidates the one taken is the
  // one CLOSEST to our own figure, inside a sanity window: that is what
  // "which of these numbers is the countdown" actually means, and it stops
  // random page text from raising a fake "this page is wrong" warning.
  function siteRemaining(ref){
    var best = null, bestGap = Infinity;
    var re1 = /(?:(\d+)\s*(?:d|dag|dagar|day|days)\D{0,4})?(?:(\d+)\s*(?:t|tim|timmar|h|hr|hour|hours)\D{0,4})?(?:(\d+)\s*(?:m|min|minut|minuter|minute|minutes)\D{0,4})?(?:(\d+)\s*(?:s|sek|sekund|sekunder|sec|second|seconds))?/i;
    var re2 = /\b(\d{1,2}):([0-5]\d):([0-5]\d)\b/;
    if(!document.body) return null;
    var w = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, null);
    var n, seen = 0;
    // Accept a candidate only if it is in the same ballpark as our own value:
    // within 10 minutes, or within a factor of 4 for the long ones.
    var window_ = Math.max(600000, Math.abs(ref) * 3);
    while((n = w.nextNode()) && seen < 4000){
      seen++;
      var t = (n.nodeValue || '').trim();
      if(!t || t.length > 40) continue;
      var ms = null, m;
      if(/\d\s*(sek|sec|min|tim|hour|dag|day)/i.test(t)){
        m = re1.exec(t);
        if(m && (m[1]||m[2]||m[3]||m[4])){
          ms = ((+m[1]||0)*86400 + (+m[2]||0)*3600 + (+m[3]||0)*60 + (+m[4]||0)) * 1000;
        }
      } else if(t.length <= 12 && (m = re2.exec(t))){
        ms = ((+m[1])*3600 + (+m[2])*60 + (+m[3])) * 1000;
      }
      if(ms === null || ms <= 0 || ms > 400*86400*1000) continue;
      var gap = Math.abs(ms - ref);
      if(gap > window_) continue;                 // not the countdown
      if(gap < bestGap){ bestGap = gap; best = ms; }
    }
    return best;
  }

  // ---- 4) the panel -------------------------------------------------------
  var box = document.createElement('div');
  box.id = '__wb_auction_clock';
  box.style.cssText =
    'position:fixed;right:14px;bottom:14px;z-index:2147483647;'+
    'background:#11151f;color:#e8edf6;border:2px solid #39c6da;border-radius:10px;'+
    'padding:9px 13px;min-width:186px;box-shadow:0 4px 18px rgba(0,0,0,.55);'+
    'font:12px/1.45 "Segoe UI",sans-serif;text-align:left;'+
    'display:none;animation:none!important;transition:none!important;';
  box.innerHTML =
    '<div style="font-size:9px;letter-spacing:.9px;color:#9aa6bf;">'+
      'AUCTION CLOCK &middot; WHYBROWSE'+
      '<span id="__wb_x" style="float:right;cursor:pointer;color:#9aa6bf;">&#10005;</span></div>'+
    '<div id="__wb_big" style="font:bold 25px/1.2 Consolas,monospace;color:#4ade80;'+
      'margin:3px 0 1px;">--:--</div>'+
    '<div id="__wb_sub" style="color:#9aa6bf;font-size:11px;"></div>'+
    '<div id="__wb_cmp" style="font-size:11px;margin-top:3px;"></div>'+
    '<div id="__wb_end" style="color:#6b7793;font-size:10px;margin-top:4px;"></div>'+
    '<div id="__wb_acc" style="color:#6b7793;font-size:9px;margin-top:2px;"></div>';
  function attach(){
    if(document.body && !document.getElementById('__wb_auction_clock')){
      document.body.appendChild(box);
      document.getElementById('__wb_x').onclick = function(){ userClosed = true; box.style.display='none'; };
    }
  }
  attach();
  document.addEventListener('DOMContentLoaded', attach);

  function two(x){ return (x<10?'0':'') + x; }
  function fmt(ms){
    if(ms < 0) ms = 0;
    var s = Math.floor(ms/1000);
    var d = Math.floor(s/86400); s -= d*86400;
    var h = Math.floor(s/3600);  s -= h*3600;
    var m = Math.floor(s/60);    s -= m*60;
    if(d) return d + 'd ' + h + 'h';
    if(h) return h + ':' + two(m) + ':' + two(s);
    return m + ':' + two(s);
  }

  // The end time it decided on, spelled out - so if it ever grabs a RELATED
  // item's clock by mistake you can see that at a glance instead of trusting it.
  (function(){
    var e = document.getElementById('__wb_end');
    if(!e) return;
    var d = new Date(endMs);
    e.textContent = (endSure ? 'Ends ' : 'Ends (best guess) ')
      + d.toLocaleString(undefined, {day:'numeric', month:'short',
                                     hour:'2-digit', minute:'2-digit',
                                     second:'2-digit'});
    if(!endSure) e.style.color = '#fbbf24';
  })();

  var lastCmp = 0, siteMs = null;
  function tick(){
    var left = endMs - serverNow();
    var big = document.getElementById('__wb_big');
    var sub = document.getElementById('__wb_sub');
    var cmp = document.getElementById('__wb_cmp');
    var acc = document.getElementById('__wb_acc');
    if(!big) return;

    // Show only inside the closing window and while still running. Re-checked
    // every tick, so the panel pops up on its own the moment it drops under the
    // threshold, and vanishes once the auction is over. Hidden -> stop here and
    // skip the expensive site-countdown compare below.
    var show = userClosed ? false
             : (SHOW_WITHIN <= 0 ? true : (left > 0 && left <= SHOW_WITHIN));
    box.style.display = show ? '' : 'none';
    if(!show) return;

    // The bid must REACH the server before the end: subtract the safety margin
    // and one measured round-trip.
    var travel = synced ? Math.max(rtt, 150) : 400;
    var safeLeft = left - MARGIN - travel;

    if(left <= 0){
      big.textContent = 'ENDED';
      big.style.color = '#f87171';
      sub.textContent = 'Closed ' + fmt(-left) + ' ago (server time).';
    } else {
      big.textContent = fmt(left);
      big.style.color = safeLeft <= 0 ? '#f87171'
                      : (left < MARGIN * 3 ? '#fbbf24' : '#4ade80');
      var deadline = new Date(endMs - MARGIN - travel);
      sub.textContent = safeLeft <= 0
        ? 'TOO LATE TO BID SAFELY'
        : 'Bid before ' + two(deadline.getHours()) + ':' + two(deadline.getMinutes())
          + ':' + two(deadline.getSeconds());
    }
    box.style.borderColor = left <= 0 ? '#f87171'
                          : (safeLeft <= 0 ? '#f87171' : '#39c6da');

    // Compare against the site's own countdown every 2 s (it is the expensive bit).
    var now = Date.now();
    if(now - lastCmp > 2000){
      lastCmp = now;
      try{ siteMs = siteRemaining(left); }catch(e){ siteMs = null; }
    }
    if(siteMs !== null && left > -60000){
      var diff = Math.round((siteMs - left) / 1000);
      if(Math.abs(diff) >= 3){
        cmp.style.color = '#f87171';
        cmp.textContent = '⚠ This page is ' + Math.abs(diff) + ' s '
                        + (diff > 0 ? 'SLOW - it shows more time than there is'
                                    : 'fast');
      } else {
        cmp.style.color = '#6b7793';
        cmp.textContent = 'Page agrees (' + (diff>=0?'+':'') + diff + ' s)';
      }
    } else {
      cmp.textContent = '';
    }
    acc.textContent = synced
      ? ('server clock ±' + Math.round(500 + rtt/2) + ' ms  ·  ping '
         + Math.round(rtt) + ' ms')
      : 'checking the server clock...';
  }
  tick();
  setInterval(tick, 250);
})();"""


# ****************************************************************************
#  DEL 21J - BULK UPLOAD QUEUE  (one picture at a time, without the tedium)
#
#  The case: posting adverts on boardgamegeek.com, where images go up ONE at a
#  time. The genuine time sink is not the clicking - it is that the file dialog
#  comes back at square one every single time, so the same folder has to be
#  found and the next picture picked out of it, over and over.
#
#  So the queue is attacked first, because that part can be made certain:
#  pick every picture ONCE, and from then on each time the page opens its file
#  dialog WhyBrowse answers it straight from the queue. No dialog appears, no
#  folder to find, no picking the right file. Chromium receives the file by the
#  normal route, so the site cannot tell the difference and nothing about its
#  upload can break.
#
#  On top of that it TRIES to press the site's own "add image" control itself,
#  so the whole run goes through unattended. That part is best-effort by nature
#  - a browser deliberately restricts opening a file dialog without a real
#  click, and every site builds its uploader differently - so it is written to
#  fail softly: if the automatic press does not take, the queue simply waits and
#  you click "add image" yourself. You still never see the file dialog again.
#
#  If the site's input happens to accept several files at once, the whole
#  remaining queue is handed over in one go and the job is done immediately.
# ****************************************************************************
# MEASURED, not assumed: a click fired from JavaScript (element.click()) does
# NOT open the file picker - Chromium requires real user input, and a scripted
# click carries none. Verified against this exact engine: the click event fires,
# the page sees it, and chooseFiles is never called. A QMouseEvent posted to the
# view's focusProxy() DOES count, and drives the picker properly.
#
# So this script does not click anything. It finds the control, scrolls it into
# view and reports WHERE it is; Python then clicks that spot for real.
BULK_UPLOAD_TARGET_JS = r"""(function(){
  function rectOf(el){
    try{ el.scrollIntoView({block:'center', inline:'center'}); }catch(e){}
    var r = el.getBoundingClientRect();
    if(r.width <= 0 || r.height <= 0) return null;
    // Must be inside the viewport for a real click to land on it.
    if(r.bottom < 0 || r.right < 0 ||
       r.top > (window.innerHeight||0) || r.left > (window.innerWidth||0)) return null;
    return {x: r.left + r.width/2, y: r.top + r.height/2};
  }
  var ins = document.querySelectorAll('input[type=file]');
  var hiddens = [];
  for(var i=0; i<ins.length; i++){
    var e = ins[i];
    if(e.disabled) continue;
    var r = rectOf(e);
    if(r){ r.kind = 'input'; return JSON.stringify(r); }   // a visible input
    hiddens.push(e);
  }
  // Uploaders usually hide the real input behind a styled button. A <label>
  // pointing at it forwards a real click, and so does a visible ancestor.
  for(var j=0; j<hiddens.length; j++){
    var h = hiddens[j];
    if(h.id){
      var lab = document.querySelector('label[for="' + CSS.escape(h.id) + '"]');
      if(lab){ var lr = rectOf(lab); if(lr){ lr.kind = 'label'; return JSON.stringify(lr); } }
    }
    var p = h.parentElement, depth = 0;
    while(p && depth++ < 4){
      var pr = rectOf(p);
      if(pr){ pr.kind = 'wrapper'; return JSON.stringify(pr); }
      p = p.parentElement;
    }
  }
  return 'noinput';
})()"""


# ---- Site macros: record clicks/inputs as DOM SELECTORS (position-independent,
#      so window size / browser placement don't matter - it finds the same
#      element every time) and replay them, waiting for each element to appear.
MACRO_RECORD_SCRIPT = """(function(){
  if(window.__wbRec) return; window.__wbRec=true;
  var KEY='__wb_macro';
  function sel(el){
    if(!el || el.nodeType!==1) return '';
    if(el.id) return '#'+CSS.escape(el.id);
    var tag=el.tagName.toLowerCase();
    if(el.name && (tag==='input'||tag==='select'||tag==='textarea'))
      return tag+'[name="'+CSS.escape(el.name)+'"]';
    var parts=[];
    while(el && el.nodeType===1 && el.tagName.toLowerCase()!=='html'){
      if(el.id){ parts.unshift('#'+CSS.escape(el.id)); break; }
      var p=el.tagName.toLowerCase(), par=el.parentNode;
      if(par){ var same=Array.prototype.filter.call(par.children,
                 function(c){return c.tagName===el.tagName;});
        if(same.length>1) p+=':nth-of-type('+(same.indexOf(el)+1)+')'; }
      parts.unshift(p); el=el.parentNode;
    }
    return parts.join('>');
  }
  function badge(n){ try{ var b=document.getElementById('__wbRecBadge');
    if(b) b.textContent='● REC  '+n+' steps  (right-click → Stop)'; }catch(e){} }
  function push(step){ try{
    var a=JSON.parse(sessionStorage.getItem(KEY)||'[]'); a.push(step);
    sessionStorage.setItem(KEY, JSON.stringify(a)); badge(a.length);
  }catch(e){} }
  document.addEventListener('click', function(e){
    try{ var t=e.target; if(t && t.id==='__wbRecBadge') return;
      var s=sel(t); if(s) push({type:'click', sel:s}); }catch(_){}
  }, true);
  document.addEventListener('change', function(e){
    try{ var t=e.target, tag=t&&t.tagName;
      if((tag==='SELECT'||tag==='INPUT'||tag==='TEXTAREA') && t.type!=='password'){
        var s=sel(t); if(s) push({type:'set', sel:s, value:(t.value||'')}); }
    }catch(_){}
  }, true);
  document.addEventListener('keydown', function(e){
    try{ if(e.key==='Enter'){ var s=sel(e.target); if(s) push({type:'key', sel:s}); } }catch(_){}
  }, true);
  try{ if(!document.getElementById('__wbRecBadge')){
    var b=document.createElement('div'); b.id='__wbRecBadge';
    b.style.cssText='position:fixed;z-index:2147483647;right:10px;bottom:10px;'+
      'background:#c0392b;color:#fff;font:bold 12px sans-serif;padding:6px 10px;'+
      'border-radius:6px;pointer-events:none;';
    (document.body||document.documentElement).appendChild(b);
    var a=JSON.parse(sessionStorage.getItem(KEY)||'[]'); badge(a.length);
  } }catch(e){}
})();"""

MACRO_PLAY_SCRIPT = """(function(){
  var steps=__STEPS__; var i=0;
  function act(s, el){
    try{
      if(s.type==='set'){ el.value=s.value;
        el.dispatchEvent(new Event('input',{bubbles:true}));
        el.dispatchEvent(new Event('change',{bubbles:true})); }
      else if(s.type==='key'){ el.focus();
        var f=el.form;
        if(f && f.requestSubmit){ f.requestSubmit(); }
        else { ['keydown','keypress','keyup'].forEach(function(t){
          el.dispatchEvent(new KeyboardEvent(t,{key:'Enter',code:'Enter',
            keyCode:13,which:13,bubbles:true})); }); }
      }
      else { el.click(); }
    }catch(e){}
  }
  function next(){
    if(i>=steps.length) return;
    var s=steps[i++], tries=0;
    var iv=setInterval(function(){
      tries++;
      var el=null; try{ el=document.querySelector(s.sel); }catch(e){}
      if(el){ clearInterval(iv); act(s, el); setTimeout(next, 500); }
      else if(tries>25){ clearInterval(iv); next(); }   // give up on this step
    }, 200);
  }
  next();
})();"""


# ---- Scroll-position capture / restore (the "go to last position" feature) ----
# Captures window scroll AND the inner scroller used by spreadsheet-style apps
# (Google Sheets = .grid-scrollable-wrapper) so a big sheet can auto-sleep and
# still come back where you left it.
SCROLL_CAPTURE_JS = r"""(function(){
  try{
    var p={x:window.scrollX||0,y:window.scrollY||0,gsel:null,gx:0,gy:0};
    var sels=['.grid-scrollable-wrapper','.waffle-edit-cell-container',
              '.native-scrollbar-container'];
    for(var i=0;i<sels.length;i++){
      var g=document.querySelector(sels[i]);
      if(g && (g.scrollTop||g.scrollLeft)){ p.gsel=sels[i]; p.gx=g.scrollLeft; p.gy=g.scrollTop; break; }
    }
    return JSON.stringify(p);
  }catch(e){ return ''; }
})()"""

SCROLL_RESTORE_JS = r"""(function(p){
  try{
    // You have already scrolled this page yourself - you win, every time.
    // This runs 0.4/1.2/2.5 s after load, which is precisely the window in
    // which you start reading, so without this it yanks you off your line.
    if(window.__wbUserScrolled) return;
    // __wbScrollOK is single-use, so set it only when a call really follows:
    // a flag left lying about would wave the NEXT scroll through instead.
    if(p.x||p.y){ window.__wbScrollOK = 1; window.scrollTo(p.x,p.y); }
    if(p.gsel){ var g=document.querySelector(p.gsel);
      if(g){ if(p.gx!=null)g.scrollLeft=p.gx; if(p.gy!=null)g.scrollTop=p.gy; } }
  }catch(e){}
})(%s)"""

# ---- "Jump to a word" (Remember-scroll-position, content edition) ------------
# Read-only: find the FIRST visible text node that contains the saved word/phrase
# (case-insensitive) and scroll it to the top of the viewport. `off` shifts the
# landing by whole rows: -1 = the row above, 0 = exact, +1 = the row below.
# scrollIntoView also scrolls nested scroll-containers, so this works inside a
# page's own scrollable panels too. Returns true when a match was found so the
# caller can stop retrying. Never types or changes anything on the page.
FIND_WORD_JS = r"""(function(word, off){
  try{
    if(!word || !document.body) return false;
    // Already scrolling by hand? Then you have found your own place; say
    // "done" so the retries (up to ~4 s after load) stop chasing you.
    if(window.__wbUserScrolled) return true;
    var needle = String(word).toLowerCase();
    var walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, {
      acceptNode: function(n){
        if(!n.nodeValue || n.nodeValue.toLowerCase().indexOf(needle) < 0)
          return NodeFilter.FILTER_REJECT;
        var el = n.parentElement;
        if(!el) return NodeFilter.FILTER_REJECT;
        var st = window.getComputedStyle(el);
        if(st && (st.visibility==='hidden' || st.display==='none'))
          return NodeFilter.FILTER_REJECT;
        var r = el.getBoundingClientRect();
        if(!r || (r.width===0 && r.height===0)) return NodeFilter.FILTER_REJECT;
        return NodeFilter.FILTER_ACCEPT;
      }
    });
    var node = walker.nextNode();
    if(!node) return false;
    var el = node.parentElement;
    try{ el.scrollIntoView({block:'start', inline:'nearest'}); }
    catch(e){ el.scrollIntoView(true); }
    if(off){
      var r = el.getBoundingClientRect();
      var lh = parseFloat(window.getComputedStyle(el).lineHeight);
      var line = (r.height || lh || 20);
      if(line > 80) line = (lh && lh < 80) ? lh : 24;   // huge block -> one text line
      window.scrollBy(0, off * line);
    }
    // Brief highlight so you can see where you landed (skip on big containers).
    try{
      var rr = el.getBoundingClientRect();
      if(rr.height && rr.height < 140){
        var old = el.style.backgroundColor;
        el.style.backgroundColor = '#ffe680';
        setTimeout(function(){ try{ el.style.backgroundColor = old; }catch(_){} }, 1500);
      }
    }catch(e){}
    return true;
  }catch(e){ return false; }
})(%s, %s)"""

# ---- Form-field memory: read/refill STABLE fields per host ----
# Deliberately CONSERVATIVE: only plain <input> fields (no textareas), and NEVER
# search boxes or message/comment fields. Otherwise an old search ("la boca")
# kept reappearing in Vinted's search, and a half-written reply leaked into other
# people's message threads. Messages are handled by the separate draft store.
_FORM_SKIP_KEY = (r"search|sök|sok|query|^q$|message|composer|comment|reply|"
                  r"chat|body|kommentar|meddel|post|tweet|caption|status")
FORM_CAPTURE_JS = r"""(function(){
  try{
    var SKIP=/__SKIP__/i;
    var out={};
    var els=document.querySelectorAll('input');
    for(var i=0;i<els.length;i++){
      var el=els[i], t=(el.type||'').toLowerCase();
      if(t==='password'||t==='hidden'||t==='file'||t==='submit'||t==='button'
         ||t==='image'||t==='reset'||t==='search'||t==='checkbox'||t==='radio') continue;
      if(el.isContentEditable) continue;
      var key=el.name||el.id||el.getAttribute('placeholder');
      if(!key || SKIP.test(key)) continue;
      var v=el.value;
      if(v!=null && v!=='' && String(v).length<200) out[key]=String(v);
    }
    return JSON.stringify(out);
  }catch(e){ return ''; }
})()""".replace("__SKIP__", _FORM_SKIP_KEY)

# ---- Message-draft live-save: capture textareas / contenteditable / message inputs ----
# Saved per URL with a timestamp, kept 7 days, viewable via ☰ → "Recover message
# drafts". NOT auto-filled back (so a draft never leaks into another conversation) —
# it's a safety net for sites that wipe your half-written reply (Vinted/Tradera).
DRAFT_CAPTURE_JS = r"""(function(){
  try{
    var out=[], seen={};
    function add(k,txt){ if(k && txt && txt.trim().length>=2 && txt.length<8000
        && !seen[k]){ seen[k]=1; out.push({k:k, t:txt}); } }
    document.querySelectorAll('textarea').forEach(function(el){
      add(el.name||el.id||el.getAttribute('placeholder')||'message', el.value);
    });
    document.querySelectorAll('[contenteditable=true],[contenteditable=""]').forEach(
      function(el,i){ add(el.getAttribute('aria-label')||el.getAttribute('data-placeholder')
        ||el.id||('editable'+i), el.innerText||el.textContent||''); });
    document.querySelectorAll('input[type=text]').forEach(function(el){
      var k=el.name||el.id||el.getAttribute('placeholder')||'';
      if(/message|composer|comment|reply|chat|meddel|kommentar/i.test(k)) add(k, el.value);
    });
    return JSON.stringify(out);
  }catch(e){ return ''; }
})()"""

SCROLL_BY_JS = r"""(function(x,y,dx,dy){
  try{
    // Try the nearest scrollable ancestor UNDER the cursor; if that doesn't move
    // (maxed out / not really scrollable), fall back to the page's MAIN scroller,
    // then the window. Verifying scrollTop changed avoids "ate the event but the
    // page didn't move" dead spots (some Tradera pages).
    function canScroll(el){
      if(!el || el===document) return false;
      var s; try{ s=getComputedStyle(el); }catch(e){ return false; }
      var oy=s.overflowY;
      return (oy==='auto'||oy==='scroll'||oy==='overlay')
             && el.scrollHeight > el.clientHeight + 2;
    }
    function moved(el, before){ return el && el.scrollTop !== before; }
    var t=document.elementFromPoint(x,y), el=t;
    while(el && el!==document.body && el!==document.documentElement){
      if(canScroll(el)){ var b=el.scrollTop; el.scrollBy(dx,dy);
        if(moved(el,b)) return; }
      el=el.parentElement;
    }
    var se=document.scrollingElement||document.documentElement||document.body;
    if(se){ var b2=se.scrollTop; se.scrollBy(dx,dy); if(moved(se,b2)) return;
      // last resort: directly nudge top in case scrollBy is overridden
      se.scrollTop=b2+dy; if(se.scrollTop!==b2) return; }
    window.scrollBy(dx,dy);
  }catch(e){ try{ window.scrollBy(dx,dy); }catch(_){} }
})(%d,%d,%d,%d)"""

# ---- Eager lazy-images: some sites (e.g. Bandcamp) leave a placeholder in
# <img src> and keep the REAL url in data-original / data-src, swapping it in
# only on a SCROLL event. WhyBrowse's custom scroll-speed handler scrolls via
# JS and that scroll can miss the site's own lazy-loader, so covers below the
# first screen never load (they load fine in Firefox, which scrolls natively).
# This promotes those data-* urls straight into src so every image loads at
# once. It deliberately does NOT touch native loading="lazy" images (Chromium
# handles those correctly), so image-heavy pages aren't forced to load all.
LAZY_IMAGES_JS = r"""(function(){
  try{
    var q='img[data-original],img[data-src],img[data-lazy-src],img.lazy,img[data-wb-real]';
    // A "placeholder" src is what a site (Bandcamp) puts back on an off-screen
    // cover to save memory: empty, a /img/0.gif-style tiny gif, a data: URI, or
    // any root-relative path (real covers are absolute https URLs on bcbits.com).
    function isPlaceholder(s){
      if(!s) return true;
      if(/\b0\.gif(\?|$)/i.test(s) || /(blank|spacer|placeholder|1x1)/i.test(s)) return true;
      if(/^data:/i.test(s)) return true;
      if(s.charAt(0)==='/' && s.charAt(1)!=='/') return true;   // root-relative
      return false;
    }
    function realOf(im){
      return im.getAttribute('data-wb-real')
          || im.getAttribute('data-original')
          || im.getAttribute('data-src')
          || im.getAttribute('data-lazy-src') || '';
    }
    // Fix ONE image: remember its real URL (in our own data-wb-real, which the
    // site never touches) and put it back in src whenever src is missing/placeholder.
    function fixImg(im){
      var real=realOf(im);
      if(!real || !/^(https?:|\/)/.test(real) || isPlaceholder(real)) return 0;
      if(!im.getAttribute('data-wb-real')) im.setAttribute('data-wb-real',real);
      var cur=im.getAttribute('src')||'';
      if(cur!==real && isPlaceholder(cur)){ im.setAttribute('src',real); return 1; }
      return 0;
    }
    function promote(){
      var imgs=document.querySelectorAll(q), p=0;
      for(var i=0;i<imgs.length;i++){ p+=fixImg(imgs[i]); }
      return p;
    }
    var first=promote();
    // ---- THE FIX: react instantly and PERMANENTLY, don't race on a timer -----
    // Bandcamp resets an off-screen cover's src back to the placeholder (to save
    // memory) every time you scroll away or leave and return to the tab. Earlier
    // versions re-promoted on a 20s timer and kept LOSING once it expired. This
    // watchdog instead restores the real URL the INSTANT the src is flipped to a
    // placeholder — it only reacts to actual src mutations, so it is cheap and
    // never loops (restoring sets a NON-placeholder src, which the guard skips).
    // Installed ONLY on pages that actually have lazy covers, so ordinary/SPA
    // pages (Gmail, Vinted…) that mutate constantly pay nothing.
    var hasLazy = !!document.querySelector(
        'img[data-wb-real],img[data-original],img[data-src],img[data-lazy-src],img.lazy');
    if(hasLazy && !window.__wb_lazy_mo){
      try{
        var pend=null;
        var mo=new MutationObserver(function(muts){
          var addned=false;
          for(var k=0;k<muts.length;k++){
            var m=muts[k], t=m.target;
            if(m.type==='attributes' && t && t.tagName==='IMG'){
              var real=t.getAttribute('data-wb-real');
              if(real){ var s=t.getAttribute('src')||''; if(s!==real && isPlaceholder(s)) t.setAttribute('src',real); }
            } else if(m.type==='childList' && m.addedNodes && m.addedNodes.length){
              addned=true;
            }
          }
          if(addned && !pend){           // new grid items — debounce to ~200ms
            pend=setTimeout(function(){ pend=null; promote(); },200);
          }
        });
        mo.observe(document.documentElement,
                   {subtree:true, childList:true, attributes:true, attributeFilter:['src']});
        window.__wb_lazy_mo=mo;
      }catch(e){}
    }
    // On becoming visible again also re-promote and re-decode (belt & braces for
    // the discarded-bitmap case; img.decode() re-decodes from cache, no flash).
    function decodeAll(){
      var xs=document.querySelectorAll('img[data-wb-real]');
      for(var i=0;i<xs.length;i++){ var im=xs[i];
        if(im.decode){ try{ im.decode().then(function(){}).catch(function(){}); }catch(e){} } }
    }
    if(!window.__wb_lazy_vis){
      window.__wb_lazy_vis=true;
      document.addEventListener('visibilitychange',function(){
        if(!document.hidden){ promote(); decodeAll(); setTimeout(function(){ promote(); decodeAll(); },300); } });
      window.addEventListener('pageshow',function(){ promote(); decodeAll(); });
    }
    return {p:first, f:0};
  }catch(e){ return -1; }
})()"""

FORM_FILL_JS = r"""(function(data){
  try{
    var SKIP=/__SKIP__/i;
    var setV=Object.getOwnPropertyDescriptor(
      window.HTMLInputElement.prototype,'value').set;
    var els=document.querySelectorAll('input');
    for(var i=0;i<els.length;i++){
      var el=els[i], t=(el.type||'').toLowerCase();
      if(t==='password'||t==='hidden'||t==='file'||t==='search'
         ||t==='checkbox'||t==='radio') continue;
      if(el.isContentEditable) continue;
      var key=el.name||el.id||el.getAttribute('placeholder');
      if(!key || SKIP.test(key) || !(key in data)) continue;
      if(!el.value){                                     // only fill EMPTY fields
        try{ setV.call(el,data[key]); }catch(e){ el.value=data[key]; }
        el.dispatchEvent(new Event('input',{bubbles:true}));
        el.dispatchEvent(new Event('change',{bubbles:true}));
      }
    }
  }catch(e){}
})(%s)""".replace("__SKIP__", _FORM_SKIP_KEY)

# ---- CP button ("Copy/Paste" field memory) ------------------------------
# A MANUAL, single-field alternative to the automatic form-field memory above.
# It targets whatever field currently has focus (drilling into open shadow
# DOMs, since some sites - e.g. checkout widgets - build their inputs inside
# a shadow root, which document.querySelectorAll() in FORM_CAPTURE_JS/
# FORM_FILL_JS can never see). The key is looked up the same way, but with a
# longer fallback chain (name/id/placeholder, THEN aria-label/data-testid/
# data-qa) since many custom fields skip name/id/placeholder entirely.
# NOTE: this can only reach fields in the TOP-level document. A field inside
# a cross-origin <iframe> (common for payment widgets) is invisible to any
# in-page JavaScript, CP included - that's a browser security boundary, not
# a bug in this feature.
# ---- CP field-focus tracker: runs in EVERY frame (main doc + all iframes,
# including cross-origin ones - QWebEngineScript content scripts are allowed
# to run there even though page JS itself couldn't reach across). This is
# what lets the CP button work on fields living inside a payment/embed
# iframe (e.g. a Swish-number field on a checkout page), where plain
# document.activeElement in the main frame only ever sees the <iframe> tag
# itself, never the real input inside it. Each frame reports its own
# focused field up to the top frame via postMessage; a "fill" request is
# broadcast back down the same way and only the matching frame acts on it. ----
FIELD_FOCUS_TRACKER_JS = r"""(function(){
  try{
    if (window.__wbFieldTrackerInstalled) return;
    window.__wbFieldTrackerInstalled = true;
    var FRAME_ID = Math.random().toString(36).slice(2) + Date.now().toString(36);
    var lastEl = null;

    function fieldKey(el){
      return el.name || el.id || el.getAttribute('placeholder')
             || el.getAttribute('aria-label') || el.getAttribute('data-testid')
             || el.getAttribute('data-qa') || '';
    }
    function isFillable(el){
      if(!el) return false;
      if(el.isContentEditable) return true;
      var tag=(el.tagName||'').toLowerCase();
      if(tag!=='input' && tag!=='textarea') return false;
      var t=(el.type||'').toLowerCase();
      return !(t==='password'||t==='hidden'||t==='file'||t==='submit'||t==='button'
               ||t==='image'||t==='reset'||t==='checkbox'||t==='radio');
    }
    document.addEventListener('focusin', function(e){
      var el = e.target;
      if(!isFillable(el)) return;
      lastEl = el;
      var k = fieldKey(el);
      if(!k) return;
      try{
        window.top.postMessage({__wbField:true, kind:'focus', frame:FRAME_ID, key:k,
          value: el.isContentEditable ? (el.innerText||'') : (el.value||'')}, '*');
      }catch(err){}
    }, true);

    window.addEventListener('message', function(ev){
      var d = ev.data;
      if(!d || !d.__wbField) return;
      if(d.kind === 'fill'){
        // Relay downward too, so a nested (iframe-inside-iframe) field still
        // gets reached - every frame forwards to its own children.
        for(var i=0;i<window.frames.length;i++){
          try{ window.frames[i].postMessage(d, '*'); }catch(err){}
        }
        if(d.frame !== FRAME_ID || !lastEl) return;
        try{
          if(lastEl.isContentEditable){
            lastEl.innerText = d.value;
          } else {
            var proto=(lastEl.tagName||'').toLowerCase()==='textarea'
                      ? window.HTMLTextAreaElement.prototype
                      : window.HTMLInputElement.prototype;
            Object.getOwnPropertyDescriptor(proto,'value').set.call(lastEl, d.value);
          }
          lastEl.dispatchEvent(new Event('input', {bubbles:true}));
          lastEl.dispatchEvent(new Event('change', {bubbles:true}));
          window.top.postMessage({__wbField:true, kind:'fillack', frame:FRAME_ID, ok:true}, '*');
        }catch(err){
          window.top.postMessage({__wbField:true, kind:'fillack', frame:FRAME_ID, ok:false}, '*');
        }
      }
    });

    // Only the TOP frame keeps the aggregated "what's focused right now,
    // anywhere on the page" state that CP_PROBE_JS / CP_FILL_JS_TMPL read.
    if (window === window.top) {
      window.__wbActiveField = null;
      window.__wbFillAck = null;
      window.addEventListener('message', function(ev){
        var d = ev.data;
        if(!d || !d.__wbField) return;
        if(d.kind === 'focus'){
          window.__wbActiveField = {frame:d.frame, key:d.key, value:d.value, t:Date.now()};
        } else if(d.kind === 'fillack'){
          window.__wbFillAck = d.ok;
        }
      });
    }
  }catch(e){}
})();"""

CP_PROBE_JS = r"""(function(){
  try{
    function deepActive(root){
      var el = root.activeElement;
      while(el && el.shadowRoot && el.shadowRoot.activeElement){
        el = el.shadowRoot.activeElement;
      }
      return el;
    }
    var el = deepActive(document);
    if(el){
      var tag = (el.tagName||'').toLowerCase();
      if(tag==='input' || tag==='textarea' || el.isContentEditable){
        var key = el.name || el.id || el.getAttribute('placeholder')
                  || el.getAttribute('aria-label') || el.getAttribute('data-testid')
                  || el.getAttribute('data-qa') || '';
        if(key){
          var val = el.isContentEditable ? (el.innerText||'') : (el.value||'');
          return JSON.stringify({k:key, v:val, frame:null});
        }
      }
    }
    // Fallback: deepActive(document) only ever sees an <iframe> tag when
    // focus is INSIDE that iframe. Use the cross-frame tracker instead -
    // it works even across origins (e.g. a Swish/payment field embed).
    var af = window.__wbActiveField;
    if(af && af.key && (Date.now() - af.t) < 15000){
      return JSON.stringify({k:af.key, v:af.value, frame:af.frame});
    }
    return null;
  }catch(e){ return null; }
})()"""

CP_FILL_JS_TMPL = r"""(function(key,val,frame){
  try{
    function deepActive(root){
      var el = root.activeElement;
      while(el && el.shadowRoot && el.shadowRoot.activeElement){
        el = el.shadowRoot.activeElement;
      }
      return el;
    }
    if(!frame){
      var el = deepActive(document);
      if(!el) return false;
      var k = el.name || el.id || el.getAttribute('placeholder')
              || el.getAttribute('aria-label') || el.getAttribute('data-testid')
              || el.getAttribute('data-qa') || '';
      if(k !== key) return false;
      if(el.isContentEditable){
        el.innerText = val;
      } else {
        var proto = (el.tagName||'').toLowerCase()==='textarea'
                    ? window.HTMLTextAreaElement.prototype
                    : window.HTMLInputElement.prototype;
        var setV = Object.getOwnPropertyDescriptor(proto,'value').set;
        try{ setV.call(el, val); }catch(e){ el.value = val; }
      }
      el.dispatchEvent(new Event('input',{bubbles:true}));
      el.dispatchEvent(new Event('change',{bubbles:true}));
      return true;
    }
    // Field lives inside an iframe: broadcast a fill request down through the
    // frame tree via the tracker script; only the matching frame acts on it.
    // (See _cp_click - it double-checks window.__wbFillAck a moment later.)
    window.__wbFillAck = null;
    window.postMessage({__wbField:true, kind:'fill', frame:frame, value:val}, '*');
    return true;
  }catch(e){ return false; }
})(%s,%s,%s)"""


# ============================================================================
#  DEL 07Y - YOUTUBE AD-BLOCK SCRIPT  (built-in; toggle = "youtube_adblock")
# ----------------------------------------------------------------------------
#  Skips/auto-skips video ads, mutes them during the skip, and hides banner /
#  overlay / feed ad slots. Guarded so it ONLY runs on youtube.com hosts (the
#  setInterval/observer never touch other sites). Injected at DocumentCreation
#  so the CSS + observer are in place before the player builds itself.
#  (This is the in-app version of the userscript that used to require manually
#   dropping youtube-adblock.js into Helpfiles/WhyBrowse/userscripts/.)
# ============================================================================
YOUTUBE_ADBLOCK_SCRIPT = r"""(function(){
  try {
    var h = (location.hostname || '').replace(/^www\./, '');
    if (!(h === 'youtube.com' || h.endsWith('.youtube.com'))) return;

    // ── CSS: hide every known ad overlay / slot ────────────────────────────
    var style = document.createElement('style');
    style.textContent = [
      '.ytp-ad-skip-button-container { opacity: 0; pointer-events: none; }',
      '.ytp-ad-overlay-container { display: none !important; }',
      '.ytp-ad-button-icon { display: none !important; }',
      '.ytp-ad-badge { display: none !important; }',
      '#masthead-ad { display: none !important; }',
      'ytd-banner-promo-renderer { display: none !important; }',
      'ytd-statement-banner-renderer { display: none !important; }',
      'ytd-ad-slot-renderer { display: none !important; }',
      'ytd-in-feed-ad-layout-renderer { display: none !important; }',
      'ytd-promoted-sparkles-web-renderer { display: none !important; }',
      '.ytd-display-ad-renderer { display: none !important; }',
      '.companion-ad-container { display: none !important; }',
      '#player-ads { display: none !important; }',
      '#ad-container { display: none !important; }'
    ].join('\n');
    (document.head || document.documentElement).appendChild(style);

    // ── Skip video ads by seeking past them ────────────────────────────────
    function skipAd() {
      var video = document.querySelector('video');
      if (!video) return;
      // STRICT ad detection: only the player's canonical ".ad-showing" class
      // (set on the html5 player ONLY during an ad) or a real skip button.
      // We deliberately DROPPED the broad [class*="ad-showing"] match — it
      // caused false positives that seeked REAL videos to the end (= "video
      // freezes after half a second"). Better to miss a rare ad than break play.
      var player = document.querySelector('.html5-video-player');
      var skipBtn = (
        document.querySelector('.ytp-skip-ad-button') ||
        document.querySelector('.ytp-ad-skip-button') ||
        document.querySelector('button.ytp-ad-skip-button-modern')
      );
      var adPlaying = (player && player.classList.contains('ad-showing')) || !!skipBtn;
      if (adPlaying) {
        if (!video.muted) video.muted = true;
        // SAFETY: only seek to the end for SHORT clips (ads are short). A real
        // video misdetected as an ad has a long duration → we never touch it.
        if (video.duration && isFinite(video.duration)
            && video.duration > 0 && video.duration < 90) {
          video.currentTime = video.duration;
        }
        if (skipBtn) skipBtn.click();
        video.addEventListener('adEnd', function(){ video.muted = false; }, { once: true });
      } else {
        if (video.muted && !video.dataset.wbUserMuted) video.muted = false;
      }
    }

    // Respect a user's own mute so we never un-mute them on real videos.
    document.addEventListener('volumechange', function(e){
      var v = e.target;
      if (v && v.tagName === 'VIDEO') {
        if (v.muted) v.dataset.wbUserMuted = '1'; else delete v.dataset.wbUserMuted;
      }
    }, true);

    // ── Anti-"you're using an ad blocker" wall ─────────────────────────────
    // YouTube detects the blocker and shows a popup + blacks the player. We
    // remove ONLY that enforcement popup (identified by its text) and, since
    // it was YouTube that paused the video, resume it. (Arms race — if YouTube
    // changes this, turn the YouTube ad-block OFF in Settings to just watch
    // with ads, or download the clip via Menu → Download video/audio.)
    function killEnforcement(){
      try{
        var found=false;
        var nodes=document.querySelectorAll(
          'ytd-enforcement-message-view-model, tp-yt-paper-dialog,'+
          'ytd-popup-container tp-yt-paper-dialog, .ytd-enforcement-message-view-model');
        for(var i=0;i<nodes.length;i++){
          var txt=(nodes[i].textContent||'').toLowerCase();
          if(txt.indexOf('ad block')>=0||txt.indexOf('adblock')>=0||
             txt.indexOf('ad-block')>=0||txt.indexOf('annonsblock')>=0||
             txt.indexOf('inte tillåt')>=0||txt.indexOf('not allowed')>=0||
             txt.indexOf('violates')>=0||txt.indexOf('bryter mot')>=0){
            nodes[i].remove(); found=true;
          }
        }
        if(found){
          var b=document.querySelectorAll('tp-yt-iron-overlay-backdrop');
          for(var j=0;j<b.length;j++) b[j].remove();
          try{ document.body.style.overflow=''; }catch(_){}
          var v=document.querySelector('video');
          if(v && v.paused){ var p=v.play(); if(p&&p.catch) p.catch(function(){}); }
        }
      }catch(e){}
    }

    function tick(){ skipAd(); killEnforcement(); }
    setInterval(tick, 300);
    try {
      new MutationObserver(function(muts){
        for (var i = 0; i < muts.length; i++) {
          if (muts[i].addedNodes.length) { tick(); break; }
        }
      }).observe(document.documentElement, { childList: true, subtree: true });
    } catch (e) {}
  } catch (e) {}
})();"""


# ============================================================================
#  DEL 08 - WEB PAGE  (handles new windows / target=_blank as new tabs)
# ============================================================================
# ****************************************************************************
#  DEL 21I - POPUP GUARD + JUNK DOMAINS
#
#  The case this was built for: subdl.com shows a video box that will not close;
#  pressing its "Close" opens a new tab on togglevpn.org full of nonsense.
#  Chromium's own popup blocker does not stop it, because a popup opened from a
#  CLICK counts as user-requested - and you did click something.
#
#  Two independent defences, because they answer different questions:
#    1. JUNK DOMAINS - "I never want to see this site again." A main-frame
#       navigation to a listed host is refused, and if the tab was opened for
#       that navigation it closes itself. Add the site while standing on it
#       (right-click -> Junk site), or straight from a blocked popup.
#    2. POPUP POLICY per opener site - "this page may not open new tabs at all."
#       Set on the MAIN site (subdl.com), so the junk tab is never created in
#       the first place, whatever address it was going to use.
#
#  A blocked popup must not be anonymous, or you cannot tell a nuisance from the
#  thing you actually wanted - and a silently crippled page looks like a broken
#  page. So the toolbar grows a 🚫 counter for the current tab, listing WHERE
#  each blocked popup wanted to go, with "open it anyway" and "always allow this
#  site" one click away. Learning that address without loading the junk site is
#  what PopupProbePage below is for.
# ****************************************************************************
class PopupProbePage(QWebEnginePage):
    """A throwaway page handed to Chromium in place of a real tab for a BLOCKED
    popup. It never loads anything: Chromium drives it to the popup's address,
    acceptNavigationRequest writes that address down and REFUSES it, and the
    page then deletes itself. That is how a blocked popup can be reported as
    "wanted to open togglevpn.org" instead of just "something was blocked",
    without the junk site getting a single request."""

    def __init__(self, profile, window, opener_view):
        super().__init__(profile, window)
        self._window = window
        self._opener_view = opener_view
        # Belt and braces: if Chromium never drives it anywhere, don't leak it.
        QTimer.singleShot(8000, self.deleteLater)

    def acceptNavigationRequest(self, url, nav_type, is_main_frame):
        try:
            if is_main_frame:
                self._window._record_blocked_popup(self._opener_view, url.toString())
                QTimer.singleShot(0, self.deleteLater)
        except Exception:
            pass
        return False                       # never load it


# ****************************************************************************
#  DEL 21K - "?" HOVER HELP MODE
#
#  Press ? and the browser explains itself: hover anything - a toolbar button, a
#  menu entry, a bookmark - and a panel says what it is, where it lives and what
#  it does, with "More" for the full explanation.
#
#  The text is NOT written twice. Every button here already carries a careful
#  tooltip, and FEATURE_INDEX already holds the long description used by the
#  feature search (Ctrl+Shift+F) - so this mode shows the tooltip and looks up
#  the matching FEATURE_INDEX entry underneath it. Nothing to keep in sync: a
#  new feature that gets a tooltip and an index entry is explained here for
#  free, and one that is missing an entry still shows its tooltip.
# ****************************************************************************
def help_lookup(query, limit=1):
    """Best FEATURE_INDEX entries for some UI text. Scored on where the words
    land: the feature NAME counts most, its keywords next, the body least."""
    # Words that carry no meaning here. "this" and "page" look harmless but are
    # the two most common words in these tooltips AND in a dozen feature names
    # ("Home page", "Find on page", "...on this site"), so left in they decide
    # the match on their own and drown out the word that actually matters.
    STOP = {"this", "that", "these", "those", "here", "there", "what", "when",
            "with", "from", "your", "you", "the", "and", "for", "are", "its",
            "it's", "use", "used", "using", "click", "clicking", "open", "opens",
            "opening", "show", "shows", "set", "sets", "setting", "was", "were",
            "can", "will", "not", "all", "any", "one", "into", "onto", "off",
            "than", "then", "them", "they", "his", "her", "our", "out", "own",
            "per", "via", "each", "every", "also", "just", "only", "same",
            "right", "left", "press", "type", "typed", "typing", "see", "seen"}
    raw = [w for w in re.split(r"[^\wÀ-ſ]+", (query or "").lower())
           if len(w) > 2 and w not in STOP][:12]
    if not raw:
        return []
    # Match plurals against singulars and back. Without this a tooltip saying
    # "Blocked popups" misses the entry named "...popup guard" entirely, and
    # lands on some unrelated feature that merely mentions "page".
    words = []
    for w in raw:
        forms = {w}
        if w.endswith("s") and len(w) > 3:
            forms.add(w[:-1])
        else:
            forms.add(w + "s")
        words.append(forms)

    def hit(forms, text):
        return any(f in text for f in forms)

    scored = []
    for name, where, desc, keys in FEATURE_INDEX:
        n, k, d = name.lower(), keys.lower(), (where + " " + desc).lower()
        score = 0
        for w in words:
            if hit(w, n):
                score += 10
            elif hit(w, k):
                score += 4
            elif hit(w, d):
                score += 1
        if score:
            scored.append((score, name, where, desc))
    scored.sort(key=lambda t: -t[0])
    return [(n, wh, d) for _s, n, wh, d in scored[:limit]]


class HelpHoverPanel(QFrame):
    """The floating explanation shown while ? mode is on. It never takes focus
    (WA_ShowWithoutActivating), so hovering the browser keeps working normally
    while it is up."""

    def __init__(self, parent=None):
        super().__init__(None, Qt.WindowType.FramelessWindowHint
                         | Qt.WindowType.Tool | Qt.WindowType.WindowStaysOnTopHint)
        self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating, True)
        self.setStyleSheet(
            "QFrame{background:%s;border:2px solid %s;border-radius:10px;}"
            "QLabel{background:transparent;}"
            "QPushButton{background:%s;color:%s;border:none;padding:3px 10px;"
            "border-radius:5px;font-size:8pt;}"
            "QPushButton:hover{background:%s;}"
            % (C_BAR_BG, C_ACCENT, C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
        self.setMaximumWidth(430)
        lay = QVBoxLayout(self)
        lay.setContentsMargins(13, 11, 13, 11)
        lay.setSpacing(5)

        self.lbl_title = QLabel()
        self.lbl_title.setStyleSheet("color:%s;font-size:11pt;font-weight:bold;" % C_ACCENT)
        self.lbl_title.setWordWrap(True)
        lay.addWidget(self.lbl_title)

        self.lbl_where = QLabel()
        self.lbl_where.setStyleSheet("color:%s;font-size:8pt;" % dim_fg())
        self.lbl_where.setWordWrap(True)
        lay.addWidget(self.lbl_where)

        self.lbl_short = QLabel()
        self.lbl_short.setStyleSheet("color:%s;font-size:9pt;" % C_BAR_FG)
        self.lbl_short.setWordWrap(True)
        lay.addWidget(self.lbl_short)

        self.lbl_more = QLabel()
        self.lbl_more.setStyleSheet("color:%s;font-size:9pt;" % C_BAR_FG)
        self.lbl_more.setWordWrap(True)
        self.lbl_more.setVisible(False)
        lay.addWidget(self.lbl_more)

        row = QHBoxLayout()
        self.btn_more = QPushButton("More ▾")          # normal colour
        self.btn_more.setCursor(Qt.CursorShape.PointingHandCursor)
        self.btn_more.clicked.connect(self._toggle_more)
        row.addWidget(self.btn_more)
        row.addStretch(1)
        hint = QLabel("? mode — Esc to leave")
        hint.setStyleSheet("color:%s;font-size:8pt;" % dim_fg())
        row.addWidget(hint)
        lay.addLayout(row)

        self._full = ""
        self._expanded = False

    def _toggle_more(self):
        self._expanded = not self._expanded
        self.lbl_more.setVisible(self._expanded and bool(self._full))
        self.btn_more.setText("Less ▴" if self._expanded else "More ▾")
        self.adjustSize()

    def show_for(self, title, where, short, full, pos):
        self.lbl_title.setText(title or "")
        self.lbl_where.setText(("📍  " + where) if where else "")
        self.lbl_where.setVisible(bool(where))
        self.lbl_short.setText(short or "")
        self.lbl_short.setVisible(bool(short))
        self._full = full or ""
        self.lbl_more.setText(self._full)
        # Keep whatever expanded/collapsed state the user chose, so moving from
        # one button to the next doesn't fold the detail away again.
        self.lbl_more.setVisible(self._expanded and bool(self._full))
        self.btn_more.setVisible(bool(self._full))
        self.btn_more.setText("Less ▴" if self._expanded else "More ▾")
        self.adjustSize()
        # Sit clear of the pointer, and stay on the screen.
        x, y = pos.x() + 18, pos.y() + 22
        scr = QApplication.primaryScreen()
        try:
            geo = (QApplication.screenAt(pos) or scr).availableGeometry()
        except Exception:
            geo = scr.availableGeometry()
        if x + self.width() > geo.right():
            x = max(geo.left(), pos.x() - self.width() - 18)
        if y + self.height() > geo.bottom():
            y = max(geo.top(), pos.y() - self.height() - 22)
        self.move(x, y)
        if not self.isVisible():
            self.show()


class WebPage(QWebEnginePage):
    def __init__(self, profile, window):
        super().__init__(profile, window)
        self._window = window
        self.lock_level = 0            # 0=free .. 3=links open in a new tab
                                       # 4 ("3+")=stay within same domain,
                                       #          other domains open a new tab
        self.keep_pinned = False       # pinned tab: keep its page, open links in new tabs

        # ---- Clipboard permission (fixes "paste loses formulas" in Google
        # Sheets etc.) ----------------------------------------------------
        # Real Chrome/Firefox let a page use the async Clipboard API
        # (navigator.clipboard.read/write) to carry rich data - e.g. Sheets
        # uses this to paste actual formulas between two spreadsheet tabs,
        # not just the plain-text result. QtWebEngine asks permission for
        # this exactly like it does for camera/mic, and if nothing answers
        # the signal it is silently DENIED - so the page quietly falls back
        # to plain-text paste (values only), which is exactly the symptom.
        # We auto-grant ONLY the clipboard permission here (not camera/mic/
        # geolocation/etc, which stay as before - unanswered/denied).
        # Two APIs exist depending on Qt/PyQt6-WebEngine version; connect to
        # whichever this build has, matched by enum name so it works across
        # versions without needing the exact enum to exist.
        if hasattr(self, "featurePermissionRequested"):
            try:
                self.featurePermissionRequested.connect(self._on_feature_permission)
            except Exception:
                pass
        if hasattr(self, "permissionRequested"):
            try:
                self.permissionRequested.connect(self._on_permission_requested)
            except Exception:
                pass

    def _on_feature_permission(self, security_origin, feature):
        # Older API (roughly Qt 6.5 - 6.7): QWebEnginePage.Feature enum +
        # setFeaturePermission(). Everything except clipboard is left alone
        # (Qt leaves it pending/denied, same as before this change).
        try:
            if "Clipboard" in feature.name:
                self.setFeaturePermission(
                    security_origin, feature,
                    QWebEnginePage.PermissionPolicy.PermissionGrantedByUser)
        except Exception:
            pass

    def _on_permission_requested(self, permission):
        # Newer API (Qt 6.8+): unified permissionRequested(QWebEnginePermission).
        try:
            if "Clipboard" in permission.permissionType().name:
                permission.grant()
        except Exception:
            pass

    def createWindow(self, _type):
        # ---- Popup guard (DEL 21I) ----------------------------------------
        # Refuse the new tab outright when THIS page's site is set to "no
        # popups". Chromium is handed a probe page instead of a real tab, so
        # the address it wanted is recorded and can be opened later on purpose.
        try:
            if not self._window._popups_allowed_for_page(self):
                return PopupProbePage(self.profile(), self._window,
                                      self._window._view_for_page(self))
        except Exception as e:
            log_line("popup guard: %s" % e)
        # Open links that request a new window/tab in a fresh tab instead.
        # navigate=False: let Chromium drive the new page to the link target.
        view = self._window.add_tab(None, switch=True, navigate=False)
        page = view.page()
        # DEL 42b - THIS page IS the new tab. Mark it, because Chromium hands
        # its first main-frame navigation to acceptNavigationRequest as a plain
        # NavigationTypeLinkClicked with self.url() still empty (measured in the
        # engine, see the flag's use below) - which is exactly what the "links
        # open in a new tab" rule matches. Without the mark that rule fired on
        # the tab that had only just been made FOR this link, handed the address
        # to yet another tab, and left this one blank for good.
        try:
            page._wb_spawned = True
        except Exception:
            pass
        return page

    def chooseFiles(self, mode, oldFiles, acceptedMimeTypes):
        """UPLOAD file-picker. Chromium's own picker opens in whatever folder was
        last used ANYWHERE, which is why a site like Bandcamp kept starting on C:
        when those files live on B:. We take it over so each site can have its own
        upload folder (plus a favourites quick-pick). Falls back to the built-in
        picker if anything goes wrong, so uploading never breaks."""
        try:
            return self._window._choose_upload_files(
                self, mode, oldFiles or [], acceptedMimeTypes or [])
        except Exception as e:
            log_line("chooseFiles error: %s" % e)
            return super().chooseFiles(mode, oldFiles, acceptedMimeTypes)

    def acceptNavigationRequest(self, url, nav_type, is_main_frame):
        try:
            # ---- Crash page's "Try without..." link (DEL 56) ---------------
            if url.scheme() == "wbcrash":
                from urllib.parse import parse_qs as _pq
                _u = (_pq(url.query(QUrl.ComponentFormattingOption.FullyEncoded))
                      .get("u") or [""])[0]
                _v = QWebEngineView.forPage(self)
                if _u and _v is not None:
                    _fn = (self._window._crash_clear_and_retry if url.host() == "clearcache"
                           else self._window._crash_without_dialog)
                    QTimer.singleShot(0, lambda v=_v, u=_u, f=_fn: f(v, u))
                return False
            # ---- Torrent links (DEL 49) ------------------------------------
            # magnet: is a scheme Chromium cannot do anything with, so without
            # this a click on one is simply swallowed - the famous "nothing
            # happens". Checked before everything else, and never handed on.
            _href = url.toString()
            if is_magnet_link(_href) or is_torrent_file_url(_href):
                _w = self._window
                if _w.settings.get("torrent_enabled", True):
                    # Deal with it AFTER this callback has returned: opening a
                    # modal pop-up from inside a navigation callback re-enters
                    # the web engine, and that is a class of trouble worth not
                    # having. The navigation itself is refused here and now.
                    QTimer.singleShot(0, lambda u=_href: _w.handle_torrent_link(
                        u, source="clicked on a page"))
                    return False
            # ---- Junk domains (DEL 21I): never let one load, anywhere -------
            # Checked FIRST, before anything else gets a chance to act on it.
            if is_main_frame and self._window._is_junk_host(url.host()):
                self._window._junk_blocked(self, url.toString())
                return False
            # ---- HTTPS upgrade --------------------------------------------
            # Open http:// links over https://. Some sites (opensubtitles.org)
            # put a proof-of-work wall in front of every page whose verification
            # cookie is Secure - so over plain http:// the cookie is dropped and
            # the wall reports "cookies are disabled" forever. https:// fixes it,
            # and is the right default anyway. A host where https genuinely fails
            # is remembered (https_exceptions) and never upgraded again, so an
            # http-only site still works (see on_load_finished ->
            # _maybe_https_fallback). Only user-initiated top-level GETs are
            # upgraded - never a form POST, a reload or a back/forward step, so
            # no posted data is turned into a GET and no reload loop can form.
            if (is_main_frame and url.scheme() == "http"
                    and self._window.settings.get("https_upgrade", True)):
                _NTu = QWebEnginePage.NavigationType
                _up_types = (_NTu.NavigationTypeTyped,
                             _NTu.NavigationTypeLinkClicked,
                             _NTu.NavigationTypeOther,
                             _NTu.NavigationTypeRedirect)
                _host = (url.host() or "").lower()
                _bare = _host[4:] if _host.startswith("www.") else _host
                _exc = [h.lower() for h in
                        self._window.settings.get("https_exceptions", [])]
                _skip = (url.port() != -1                      # explicit port
                         or _host == "localhost" or _bare == "localhost"
                         or _bare.endswith(".local") or _bare.endswith(".onion")
                         or bool(re.match(r"^\d{1,3}(\.\d{1,3}){3}$", _host))
                         or _bare in _exc)
                if nav_type in _up_types and not _skip:
                    _u2 = QUrl(url)
                    _u2.setScheme("https")
                    _pend = getattr(self._window, "_https_pending", None)
                    if _pend is None:
                        _pend = self._window._https_pending = {}
                    _pend[_bare] = url.toString()
                    QTimer.singleShot(0, lambda q=_u2: self.setUrl(q))
                    return False
            # Apply this site's NoScript-style JS setting BEFORE the page loads.
            if is_main_frame:
                self._window._apply_js_for_host(self, url.host())
            # IMDb: always use the cleaner "reference" layout. A bare title page
            # /title/ttNNN/ is redirected to /title/ttNNN/reference/. Only the
            # bare title page matches, so it never loops and never touches other
            # IMDb sub-pages (fullcredits, ratings, the reference page itself…).
            if (is_main_frame
                    and self._window.settings.get("imdb_reference", True)):
                host = url.host().lower()
                if host.startswith("www."):
                    host = host[4:]
                if host == "imdb.com" or host.endswith(".imdb.com"):
                    parts = [p for p in url.path().split("/") if p]
                    if (len(parts) == 2 and parts[0] == "title"
                            and parts[1].startswith("tt")):
                        new_url = "{}://{}/title/{}/reference/".format(
                            url.scheme() or "https", url.host(), parts[1])
                        QTimer.singleShot(
                            0, lambda u=new_url: self.setUrl(QUrl(u)))
                        return False
            # ---- A tab Chromium JUST made for this link (DEL 42b) ----------
            # createWindow() above already gave a target="_blank" link (or a
            # window.open) its own tab. The navigation arriving here now IS that
            # link, so it must load HERE - anything that sends it to another tab
            # leaves this one blank.
            #
            # MEASURED IN THE ENGINE, because it is not obvious: the opener page
            # gets NO acceptNavigationRequest at all for a target="_blank" click
            # (only createWindow), and the brand-new page then receives it as
            #     NavigationTypeLinkClicked, is_main_frame=True, self.url()==""
            # - indistinguishable, without this flag, from you clicking a link on
            # an ordinary page. That is why "links open in a new tab" fired on it
            # and produced the empty "New" tab beside the page you asked for.
            # Reported on BGG geekmail; it needs target="_blank", which is why
            # sites that use window.open (reported as NavigationTypeOther) never
            # showed it. The flag is cleared at once, so only the FIRST
            # navigation is exempt and every later link in that tab behaves
            # exactly as before.
            if is_main_frame and getattr(self, "_wb_spawned", False):
                self._wb_spawned = False
                return super().acceptNavigationRequest(url, nav_type, is_main_frame)
            # Lock level 3: every outbound navigation in the main frame opens
            # in a NEW tab instead, leaving this tab where it is.
            #
            # We catch both NavigationTypeLinkClicked (plain <a href>) AND
            # other types (NavigationTypeOther, NavigationTypeRedirect) that
            # cover JS-driven navigation (window.location, history.pushState,
            # fetch-then-redirect, etc.) — which is what site menus like
            # Tradera's use.  We only intercept cross-origin navigations so
            # in-site JS nav (same host) is never broken.
            # A PINNED tab also keeps its page: clicking a link there opens a new
            # tab instead of navigating the pinned page away (so a pinned page is
            # always the one you chose). Same behaviour as Lock 3.
            if (self.lock_level >= 3 or self.keep_pinned) and is_main_frame:
                NT = QWebEnginePage.NavigationType
                # Types that represent the user (or JS) trying to leave the page
                outbound_types = (
                    NT.NavigationTypeLinkClicked,
                    NT.NavigationTypeOther,
                    NT.NavigationTypeRedirect,
                )
                if nav_type in outbound_types:
                    current_host = self.url().host()
                    dest_host    = url.host()
                    # NEVER int() a Qt enum here (rev91). PyQt6 6.11 hands
                    # NavigationType out as a plain enum.Enum, not an IntEnum,
                    # so int(nav_type) raises TypeError - and this line sits
                    # inside the big try/except that ends in "pass", so the
                    # whole of lock 3 / 3+ / pinned was skipped without a
                    # sound and every link simply loaded in place. A DIAGNOSTIC
                    # killing the feature it was added to explain is about as
                    # bad as it gets, so it now asks for .value and falls back
                    # to the member itself.
                    log_line("lock-nav: level=%s pinned=%s type=%s cur=%s dest=%s"
                             % (self.lock_level, self.keep_pinned,
                                getattr(nav_type, "value", nav_type),
                                current_host, dest_host))
                    # Always intercept link-clicks regardless of host.
                    # For JS/redirect navigation only intercept cross-origin
                    # moves so in-site menus (same host) keep working.
                    is_link = nav_type == NT.NavigationTypeLinkClicked
                    is_cross = dest_host and dest_host != current_host
                    # ---- Lock level 4 ("3+"): stay within the SAME site -------
                    # Browse freely inside one registered domain (tradera.com
                    # and its www./m./shop. subdomains all count as one site) —
                    # those links load right here in this tab. Only a jump to
                    # ANOTHER domain opens a new tab and leaves this one put.
                    # 3+ WINS OVER PIN: on a tab that is BOTH pinned and 3+, a
                    # same-domain link still navigates here (3+ overrides the
                    # pinned "never leave this page" rule for its own domain);
                    # other domains open a new tab as usual. That is exactly what
                    # "keep me on this site" should do for a pinned home tab.
                    if self.lock_level == 4:
                        same_site = bool(dest_host) and same_registered_domain(
                            current_host, dest_host)
                        # Diagnostic (Lock 3+ only, so it's rare): records why a
                        # link stayed here or went to a new tab, to settle any
                        # "3+ opened a new tab anyway" report.
                        log_line("lock3+ nav: cur=%s dest=%s same=%s -> %s"
                                 % (current_host, dest_host, same_site,
                                    "stay" if same_site else "newtab"))
                        if same_site:
                            # Same site: keep browsing here, even when the global
                            # "links open in a new tab" default (DEL 42) is on —
                            # so we accept it in place and skip that block.
                            return super().acceptNavigationRequest(
                                url, nav_type, is_main_frame)
                        if is_link or is_cross:
                            self._window.add_tab(url.toString(), switch=True)
                            return False
                        # else (same-host non-link, empty host…): fall through.
                    else:
                        # ---- Lock 3 / pinned: every link opens a new tab ------
                        # A PINNED tab must never leave the page you pinned. On top
                        # of link-clicks / cross-origin, also send same-host JS
                        # navigation to a DIFFERENT document (path change) to a new
                        # tab — this is how sites like Vinted open the next item
                        # (window.location, not an <a>). A same-DOCUMENT move (only
                        # #fragment / ?query changes, e.g. switching sheet-tabs in
                        # Google Sheets by gid) keeps the same path, so it stays in
                        # place and works normally.
                        same_host_newdoc = (
                            self.keep_pinned
                            and nav_type == NT.NavigationTypeOther
                            and not is_cross
                            and (url.path() or "") != (self.url().path() or ""))
                        if is_link or is_cross or same_host_newdoc:
                            self._window.add_tab(url.toString(), switch=True)
                            return False
            # ---- Links open in a NEW tab by default (DEL 42) ----
            # A plain link-click opens in a new tab so it's never a guess whether
            # it lands new or same. Exceptions: hosts the user marked "open in the
            # same tab", and same-document jumps (#anchor / ?query only, which
            # must scroll in place, not spawn a tab). A locked(3)/pinned tab was
            # already handled above, so that overrules any "same-tab" rule.
            NT2 = QWebEnginePage.NavigationType
            if (is_main_frame
                    and nav_type == NT2.NavigationTypeLinkClicked
                    and url.scheme() in ("http", "https")
                    and self._window.settings.get("links_open_new_tab", False)):
                cur = self.url()
                same_doc = (url.host() == cur.host()
                            and url.path() == cur.path())
                dest = clean_host(url.host())
                if (not same_doc and dest
                        and dest not in self._window._link_same_tab_domains()):
                    go = (self._window.settings.get(
                        "open_link_default", "new_tab_stay") == "new_tab_go")
                    self._window.add_tab(url.toString(), switch=go)
                    return False
        except Exception:
            pass
        return super().acceptNavigationRequest(url, nav_type, is_main_frame)

    def javaScriptConsoleMessage(self, level, message, line, source):
        # Keep the console quiet. We deliberately do NOT log routine JS console
        # output (every page spams it); swallow it so it never raises.
        return


class BrowserView(QWebEngineView):
    """A web view whose right-click menu we control (View source + Features +
    per-site exceptions)."""
    def __init__(self, window):
        super().__init__()
        self._window = window

    def contextMenuEvent(self, event):
        try:
            self._window.show_page_menu(self, event.globalPos())
        except Exception as e:
            log_line("page menu error: {}".format(e))
            super().contextMenuEvent(event)


class WheelButton(QPushButton):
    """A push button that reports mouse-wheel scrolls (used for the low-vision
    size dial: scroll = zoom, Shift+scroll = font size)."""
    def __init__(self, on_wheel, text=""):
        super().__init__(text)
        self._on_wheel = on_wheel

    def wheelEvent(self, e):
        try:
            delta = 1 if e.angleDelta().y() > 0 else -1
            shift = bool(e.modifiers() & Qt.KeyboardModifier.ShiftModifier)
            self._on_wheel(delta, shift)
            e.accept()
        except Exception:
            super().wheelEvent(e)


# ============================================================================
#  DEL 09 - SUCCESS TOAST  (auto-disappears after 1 second)
# ============================================================================
def show_toast(window, text, duration=1000):
    lbl = QLabel(text, window)
    lbl.setStyleSheet(
        "background:{}; color:{}; padding:8px 16px; border-radius:8px; "
        "font-size:11pt;".format(C_TOAST_BG, C_TOAST_FG))
    lbl.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, True)
    lbl.setWordWrap(True)
    lbl.setMaximumWidth(max(200, min(560, window.width() - 40)))
    lbl.adjustSize()
    x = (window.width() - lbl.width()) // 2
    y = window.height() - lbl.height() - 40
    lbl.move(max(10, x), max(10, y))
    lbl.show()
    lbl.raise_()
    QTimer.singleShot(duration, lbl.deleteLater)   # gone after `duration` ms (default 1s, unchanged)


class MessagePopup(QWidget):
    """Small frameless, always-on-top notification shown at the main window's
    top-right corner when a BACKGROUND 'Messaging' profile gets a new message
    (e.g. WhatsApp '(3)'). Click it to jump straight to that profile/tab. It does
    NOT steal focus (WA_ShowWithoutActivating) so it never interrupts typing."""
    def __init__(self, text, on_click):
        super().__init__(None,
            Qt.WindowType.FramelessWindowHint | Qt.WindowType.Tool
            | Qt.WindowType.WindowStaysOnTopHint)
        self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating, True)
        self._on_click = on_click
        self.setStyleSheet(
            "QWidget{background:#1f6feb; border:1px solid #5fa0ff; border-radius:8px;}"
            "QLabel{color:#ffffff; font-size:10pt; background:transparent; border:none;}")
        self.setFixedWidth(300)
        lay = QVBoxLayout(self)
        lay.setContentsMargins(12, 10, 12, 10)
        lbl = QLabel(text)
        lbl.setWordWrap(True)
        lay.addWidget(lbl)
        hint = QLabel("Click to open · auto-closes")
        hint.setStyleSheet("color:#d6e6ff; font-size:8pt; background:transparent;")
        lay.addWidget(hint)
        QTimer.singleShot(12000, self.close)       # auto-dismiss after 12 s

    def mousePressEvent(self, e):
        try:
            self._on_click()
        except Exception:
            pass
        self.close()


class FloatingTab(QWidget):
    """A small window showing ONE page on a chosen profile's engine. It keeps
    showing that page even after you switch the main window to another
    profile (the engine stays alive), so you can watch a chat / sheet while
    working elsewhere. Shares the profile's cookies/login since it uses the
    same engine.

    Whether it STAYS ON TOP of other windows or behaves like a NORMAL window
    (can be covered by other apps, e.g. when you want it "underneath") is
    chosen per pop-out - see the "Pop out..." submenu - and can still be
    flipped afterwards with the 📌 button in its own title bar."""
    def __init__(self, window, engine, url, title="", always_on_top=True):
        always_on_top = bool(always_on_top)
        flags = Qt.WindowType.Window
        if always_on_top:
            flags |= Qt.WindowType.WindowStaysOnTopHint
        super().__init__(None, flags)
        self._always_on_top = always_on_top
        self._window = window
        self.setWindowTitle((title or "WhyBrowse") + " — floating")
        apply_window_icon(self)
        self.resize(460, 600)
        lay = QVBoxLayout(self)
        lay.setContentsMargins(0, 0, 0, 0)
        lay.setSpacing(0)
        bar = QHBoxLayout()
        bar.setContentsMargins(6, 4, 6, 4)
        self.lbl = QLabel(url)
        self.lbl.setStyleSheet("font-size:8pt;")
        bar.addWidget(self.lbl, 1)
        self.btn_pin = QPushButton()
        self.btn_pin.setFixedSize(24, 24)
        self.btn_pin.setCursor(Qt.CursorShape.PointingHandCursor)
        self.btn_pin.clicked.connect(self._toggle_pin)
        bar.addWidget(self.btn_pin)
        self._paint_pin()
        for txt, fn in (("↻", lambda: self.view.reload()), ("✕", self.close)):
            b = QPushButton(txt)
            b.setFixedSize(24, 24)
            b.setCursor(Qt.CursorShape.PointingHandCursor)
            b.clicked.connect(fn)
            bar.addWidget(b)
        lay.addLayout(bar)
        self.view = QWebEngineView()
        self.view.setPage(WebPage(engine, window))
        self.view.titleChanged.connect(lambda t: self.lbl.setText(t or url))
        self.view.setUrl(QUrl(url))
        lay.addWidget(self.view, 1)

    def _paint_pin(self):
        self.btn_pin.setText("📌" if self._always_on_top else "🪟")
        self.btn_pin.setToolTip(
            "Always on top — click to let it go behind other windows"
            if self._always_on_top else
            "Normal window — click to keep it on top of other windows")

    def _toggle_pin(self):
        self._always_on_top = not self._always_on_top
        flags = Qt.WindowType.Window
        if self._always_on_top:
            flags |= Qt.WindowType.WindowStaysOnTopHint
        was_visible = self.isVisible()
        self.setWindowFlags(flags)
        self._paint_pin()
        if was_visible:
            self.show()   # changing window flags hides the window on most platforms
            self.raise_()
            self.activateWindow()
        show_toast(self._window,
                  "Floating window: always on top" if self._always_on_top
                  else "Floating window: normal (can go behind other windows)")

    def closeEvent(self, e):
        try:
            self.view.page().setAudioMuted(True)
            self.view.stop()
            self.view.page().setUrl(QUrl("about:blank"))
        except Exception:
            pass
        super().closeEvent(e)


class VersionPopup(QWidget):
    """TEMPORARY startup window (sits in the background, closed manually) that
    shows EXACTLY which build is running and whether cookies are being saved to
    disk — so we never argue about versions again, and can see the login-persistence
    state with our own eyes. Remove once the cookie problem is settled."""
    def __init__(self, window):
        super().__init__(None, Qt.WindowType.Window)
        self._window = window
        self.setWindowTitle("WhyBrowse — version / cookie check (temporary)")
        apply_window_icon(self)
        self.resize(600, 340)
        lay = QVBoxLayout(self)
        self.lbl = QLabel()
        self.lbl.setTextInteractionFlags(
            Qt.TextInteractionFlag.TextSelectableByMouse)
        self.lbl.setWordWrap(True)
        self.lbl.setStyleSheet("font-size:10pt;")
        lay.addWidget(self.lbl, 1)
        row = QHBoxLayout()
        b1 = QPushButton("Re-check now")
        b1.clicked.connect(self._refresh)
        # The change log is NOT shown here any more: this label word-wraps, so
        # the old 38 000-character APP_VERSION turned this window several
        # screens TALL instead of wide, with no scroll bar to get back out of.
        b0 = QPushButton("Version history…")
        b0.clicked.connect(lambda: VersionHistoryDialog(self).exec())
        row.addWidget(b0)
        b2 = QPushButton("Close")
        b2.clicked.connect(self.close)
        row.addWidget(b1)
        row.addStretch(1)
        row.addWidget(b2)
        lay.addLayout(row)
        self._refresh()

    def _refresh(self):
        import datetime
        try:
            path = os.path.abspath(
                sys.executable if getattr(sys, "frozen", False) else __file__)
            st = os.stat(path)
            finfo = "%s<br>&nbsp;&nbsp;&nbsp;%d bytes &middot; modified %s" % (
                path, st.st_size,
                datetime.datetime.fromtimestamp(st.st_mtime)
                .strftime("%Y-%m-%d %H:%M:%S"))
        except Exception as e:
            finfo = "unknown (%s)" % e
        self.lbl.setText(
            "<b>VERSION:</b> %s<br><br>"
            "<b>Running file:</b><br>%s<br><br>"
            "<b>Cookie policy:</b> ForcePersistentCookies "
            "(session cookies kept across restarts)<br><br>"
            "<b>%s</b>" % (APP_VERSION, finfo, self._cookie_status()))

    def _cookie_status(self):
        try:
            pid = getattr(self._window, "active_id", "default")
            storage = profile_paths(pid)["storage"]
            for rel in ("Network/Cookies", "Cookies"):
                p = os.path.join(storage, rel.replace("/", os.sep))
                if os.path.isfile(p):
                    kb = max(1, os.path.getsize(p) // 1024)
                    return ("Cookies file: FOUND  (~%d KB)<br>%s<br>"
                            "&rarr; logins SHOULD persist across restarts." % (kb, p))
            return ("Cookies file: MISSING so far (profile '%s')<br>%s<br>"
                    "&rarr; Log in to a site, browse a little, then press "
                    "'Re-check now'. It should appear. If it stays MISSING even "
                    "after logging in, cookie saving is broken in this build and "
                    "I'll fix THAT specifically." % (pid, storage))
        except Exception as e:
            return "Cookie check failed: %s" % e


# ============================================================================
#  DEL 10 - ABOUT DIALOG  (ESC closes; modal; English only)
# ============================================================================
class VersionHistoryDialog(QDialog):
    """The full change log, WRAPPED and SCROLLING.

    This is the only place APP_HISTORY may be shown. Putting it in a plain
    QLabel is what made the About box open wider than the monitor with every
    word on one line - a QLabel asks for the width of its longest line and the
    layout obliges. A QTextBrowser wraps to whatever width it is given and
    scrolls the rest, so the text can be as long as it likes."""

    def __init__(self, parent):
        super().__init__(parent)
        self.setWindowTitle(APP_NAME + " - Version history")
        self.setStyleSheet(dialog_qss())
        apply_window_icon(self)

        lay = QVBoxLayout(self)
        head = QLabel("Running <b>%s</b>" % APP_VERSION)
        head.setWordWrap(True)
        head.setStyleSheet("font-size:11pt;")
        lay.addWidget(head)

        self.txt = QTextBrowser()
        self.txt.setLineWrapMode(QTextBrowser.LineWrapMode.WidgetWidth)
        self.txt.setOpenExternalLinks(False)
        self.txt.setPlainText(version_history_text())
        self.txt.setStyleSheet("font-size:9pt;")
        lay.addWidget(self.txt, 1)

        row = QHBoxLayout()
        btn_copy = QPushButton("Copy all")
        btn_copy.setStyleSheet(
            "QPushButton{background:%s; color:%s; border:none; padding:6px 14px;"
            " border-radius:6px;}QPushButton:hover{background:%s;}"
            % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
        btn_copy.clicked.connect(
            lambda: QApplication.clipboard().setText(version_history_text()))
        row.addWidget(btn_copy)
        row.addStretch(1)
        btn_close = QPushButton("Close")
        btn_close.setStyleSheet(
            "QPushButton{background:%s; color:%s; border:none; padding:6px 18px;"
            " border-radius:6px;}QPushButton:hover{background:%s;}"
            % (C_ACCENT, C_ACCENT_FG, C_ACCENT_HOV))
        btn_close.clicked.connect(self.accept)
        row.addWidget(btn_close)
        lay.addLayout(row)

        self.resize(880, 620)
        fit_to_screen(self)

    def keyPressEvent(self, e):
        if e.key() == Qt.Key.Key_Escape:
            self.accept()
        else:
            super().keyPressEvent(e)


class AboutDialog(QDialog):
    def __init__(self, parent):
        super().__init__(parent)
        self.setWindowTitle("About " + APP_NAME)
        self.setModal(True)                       # grab_set equivalent
        self.setStyleSheet("background:#1b2030; color:#e8edf6;")   # fixed dark (styled HTML)
        apply_window_icon(self)

        lay = QVBoxLayout(self)
        lay.setContentsMargins(26, 22, 26, 22)
        lay.setSpacing(6)

        title = QLabel(APP_NAME)
        title.setAlignment(Qt.AlignmentFlag.AlignCenter)
        title.setStyleSheet("color:{}; font-size:24pt; font-weight:bold;".format(C_ACCENT))
        lay.addWidget(title)

        sub = QLabel(APP_TAGLINE)
        sub.setAlignment(Qt.AlignmentFlag.AlignCenter)
        sub.setStyleSheet("color:#9aa6bf; font-style:italic;")
        lay.addWidget(sub)

        # SHORT version only. This label used to say "Version " + the entire
        # change log - one unbroken 38 000-character line in a QLabel with no
        # word-wrap - which is what made this dialog open many screens wide.
        # The long text now lives in APP_HISTORY and opens in its own scrolling
        # window through the link below.
        ver = QLabel("Version " + APP_VERSION)
        ver.setAlignment(Qt.AlignmentFlag.AlignCenter)
        ver.setWordWrap(True)
        ver.setStyleSheet("color:#6f7c99; font-size:9pt;")
        lay.addWidget(ver)

        hist = QLabel('<a style="color:{};" href="#history">What changed '
                      '(version history)</a>'.format(C_ACCENT))
        hist.setAlignment(Qt.AlignmentFlag.AlignCenter)
        hist.setOpenExternalLinks(False)
        hist.linkActivated.connect(lambda *_: VersionHistoryDialog(self).exec())
        lay.addWidget(hist)

        lay.addSpacing(8)
        lay.addWidget(self._sep())

        author = QLabel(APP_AUTHOR)
        author.setAlignment(Qt.AlignmentFlag.AlignCenter)
        author.setStyleSheet("font-size:11pt; font-weight:bold;")
        lay.addWidget(author)

        # Documentation / help link (opens the in-app Help)
        doc = QLabel('<a style="color:{};" href="#help">View Help &amp; documentation</a>'.format(C_ACCENT))
        doc.setAlignment(Qt.AlignmentFlag.AlignCenter)
        doc.setOpenExternalLinks(False)
        doc.linkActivated.connect(lambda *_: (self.accept(), parent.show_help()))
        lay.addWidget(doc)

        lay.addSpacing(6)
        lay.addWidget(self._sep())

        tip = QLabel("If you enjoy " + APP_NAME + ", a small gift is always welcome!")
        tip.setAlignment(Qt.AlignmentFlag.AlignCenter)
        tip.setWordWrap(True)
        tip.setStyleSheet("color:#9aa6bf; font-style:italic;")
        lay.addWidget(tip)

        box = QFrame()
        box.setStyleSheet("background:#252535; border-radius:8px;")
        bl = QHBoxLayout(box)
        bl.setContentsMargins(14, 10, 14, 10)
        bl.setSpacing(10)
        for name, url in (("Revolut", REVOLUT_URL),
                          ("PayPal", PAYPAL_URL),
                          ("Wise", WISE_URL)):
            b = QPushButton(name)
            b.setCursor(Qt.CursorShape.PointingHandCursor)
            b.setStyleSheet(
                "QPushButton{background:%s; color:%s; border:none; "
                "padding:6px 14px; border-radius:6px; font-weight:bold;}"
                "QPushButton:hover{background:%s;}" % (C_ACCENT, C_ACCENT_FG, "#5ad6e8"))
            b.clicked.connect(lambda _=False, u=url: open_url(u))
            bl.addWidget(b)
        lay.addWidget(box)

        close = QPushButton("Close")
        close.setStyleSheet(
            "QPushButton{background:%s; color:%s; border:none; padding:6px 18px; "
            "border-radius:6px;}QPushButton:hover{background:%s;}"
            % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
        close.clicked.connect(self.accept)
        lay.addSpacing(6)
        lay.addWidget(close, alignment=Qt.AlignmentFlag.AlignCenter)

        self.adjustSize()
        fit_to_screen(self)
        self.activateWindow()
        self.setFocus()                            # focus_force equivalent

    def _sep(self):
        line = QFrame()
        line.setFrameShape(QFrame.Shape.HLine)
        line.setStyleSheet("color:#333a4d; background:#333a4d;")
        line.setFixedHeight(1)
        return line

    def keyPressEvent(self, e):                    # ESC closes
        if e.key() == Qt.Key.Key_Escape:
            self.accept()
        else:
            super().keyPressEvent(e)


# ============================================================================
#  DEL 11 - HELP DIALOG  (hardcoded English explanation; ESC closes)
# ============================================================================
HELP_TEXT = """
<h2 style="color:#39c6da;">WhyBrowse - Help</h2>
<p><b>What is this?</b><br>
WhyBrowse is a full web browser. It uses the same engine as Google Chrome
(Chromium), so any modern website renders exactly as it would in Chrome or
Edge - including video, logins, web apps and JavaScript.</p>

<h3 style="color:#39c6da;">The toolbar</h3>
<ul>
<li><b>&#9664; Back / &#9654; Forward</b> - move through pages you visited.
    <b>Right-click &#9664;</b> and you go all the way back to the FIRST page of
    this tab in one step - the bookmark you opened, the search you ran, the page
    you came in from (blank start pages are skipped).
    <b>Right-click &#9654;</b> and you get a <i>copy</i> of the page you are on
    in a new tab beside this one, and land in the copy - so you can click on in
    the copy and still have the original where you left it. The Forward arrow is
    greyed out when there is nothing forward, but it is still there to
    right-click.</li>
<li><b>&#8635; Reload</b> - reload the current page.</li>
<li><b>&#8962; Home</b> - go to your home page (change it in the menu).</li>
<li><b>Address bar</b> - type a web address <i>or</i> a search. If it looks
    like a website it opens directly; otherwise it searches the web.
    Press <b>Enter</b> to go.</li>
<li><b>&#128221; Saved words / snippets</b> - a menu with the words saved for
    <i>this page</i> and for <i>all sites</i> at the top; click one to drop it
    into the field you're typing in. Below that: <b>Save a new word&hellip;</b>
    and <b>Manage saved words&hellip;</b>. (The same words also live in the page
    right-click menu.)</li>
<li><b>&#128206; File sets</b> - named groups of files (say, the three
    instruction files you give every AI). Pick a set and a small panel opens: drag
    all the files (or just some) from it onto the page - works on a plain chat box
    with no paperclip. Its <i>Attach-button mode</i> instead skips the file dialog
    when you press the site's own attach button. Also: save a new set, copy a set
    to the clipboard (Ctrl+V into a chat box), or
    manage the list. Removing a set only takes it off the list - no file on the
    disk is touched.</li>
<li><b>&#128278; Bookmarks and history</b> - one drop-down: <i>Bookmark this
    page</i>, <i>Bookmarks</i> (open and manage your saved pages) and
    <i>History</i> (revisit recent pages or clear your history).</li>
<li><b>&#9776; Menu</b> - new tab, zoom, home page, About and Help.</li>
</ul>

<h3 style="color:#39c6da;">Tabs</h3>
<p>Use multiple tabs at once. Drag tabs to reorder them. Click the
<b>+</b> button or press <b>Ctrl+T</b> to open a new tab,
<b>Ctrl+W</b> to close the current one.</p>

<h3 style="color:#39c6da;">Keyboard shortcuts</h3>
<table cellpadding="3">
<tr><td><b>Ctrl+T</b></td><td>New tab</td></tr>
<tr><td><b>Ctrl+W / Ctrl+F4</b></td><td>Close tab</td></tr>
<tr><td><b>Ctrl+L</b></td><td>Focus the address bar</td></tr>
<tr><td><b>Ctrl+R / F5</b></td><td>Reload</td></tr>
<tr><td><b>Ctrl+F</b></td><td>Find on page (opens the <i>site's own</i> search on
    Google Sheets/Docs/Notion)</td></tr>
<tr><td><b>Ctrl+Tab / Ctrl+Shift+Tab</b></td><td>Next / previous tab</td></tr>
<tr><td><b>Ctrl+M</b></td><td>Mute / unmute this tab</td></tr>
<tr><td><b>Ctrl+Shift+M</b></td><td>Mute all tabs</td></tr>
<tr><td><b>Ctrl+Shift+T</b></td><td>Reopen the last closed tab</td></tr>
<tr><td><b>Ctrl+Shift+A</b></td><td>Search / list all open tabs</td></tr>
<tr><td><b>Ctrl+Shift+D</b></td><td>Report a bug / log the current page</td></tr>
<tr><td><b>Ctrl+Shift+S</b></td><td>Save the current page as a quick link</td></tr>
<tr><td><b>Ctrl+\\</b></td><td>Split view (a second page beside the tabs)</td></tr>
<tr><td><b>Ctrl + / Ctrl -</b></td><td>Zoom in / out</td></tr>
<tr><td><b>Ctrl+0</b></td><td>Reset zoom</td></tr>
<tr><td><b>Ctrl+P</b></td><td>Print / Save the current page as a PDF</td></tr>
<tr><td><b>Alt+&#9664; / Alt+&#9654;</b></td><td>Back / Forward</td></tr>
<tr><td><b>F1-F12</b></td><td>Switch between profiles (skips F5/F11)</td></tr>
<tr><td><b>F11</b></td><td>Toggle full screen</td></tr>
<tr><td><b>Ctrl+Shift+K</b></td><td>On-screen keyboard (anti-keylogger)</td></tr>
<tr><td><b>Esc</b></td><td>Close this window / stop loading</td></tr>
</table>

<h3 style="color:#39c6da;">New tab</h3>
<p>Click the bright <b>+</b> button at the top-right of the tab strip, or press
<b>Ctrl+T</b>. New tabs open a clean blank start page where you can type an
address or a search.</p>

<h3 style="color:#39c6da;">Privacy, blocking &amp; anti-annoyance (Menu &rarr; Settings)</h3>
<ul>
<li><b>Ad / tracker blocker</b> - blocks known ad and tracking domains. Add your
    own in Settings.</li>
<li><b>Block third-party cookies</b> - stops cross-site tracking cookies while
    keeping the ones a site needs to log you in.</li>
<li><b>Freeze animations / blinking</b> - stops blinking carets (including in
    Google Docs), CSS animations and pauses GIF/video.</li>
<li><b>Hide domains from search results</b> - unlimited block list for Google,
    DuckDuckGo, Bing, etc.</li>
<li><b>Element-hide rules</b> - hide parts of a page with <i>domain##selector</i>
    (e.g. <i>wikipedia.org##.vector-column-end</i> hides Wikipedia's right column).</li>
<li><b>Pretend to be in another city</b> - feed websites/stores a chosen
    location instead of your real one.</li>
<li><b>Import bookmarks from Firefox</b> - Menu &rarr; Import bookmarks from Firefox.</li>
<li><b>&#11088; Favourites (shared list, each link keeps its own login)</b> -
    normal bookmarks live inside one profile. Favourites are ONE global list every
    profile can see, and each favourite <i>remembers which login it opens with</i>.
    Right-click a bookmark (or a page) &rarr; <b>&#11088; Add to Favourites</b> to
    drop a copy in bound to your current profile's login - or use
    <b>&#11088; Add ... using login&hellip;</b> to bind it to another profile or a
    container. Open or remove them from <b>Menu &rarr; &#11088; Favourites</b>
    (grouped by login). Because each entry carries its own login, you can star the
    SAME site twice - e.g. two Gmail accounts - and open BOTH in the same window at
    once, without switching profiles. A favourite bound to a different login opens
    as a tab labelled with that account's name.
    <br><b>The &ldquo;99 Favourites&rdquo; profile:</b> switch to profile <b>99</b> and
    your whole starred list <i>is</i> the bookmarks bar - each link painted in the
    colour of the account it belongs to, and each one still opening
    <i>as that account</i>. Two logins on the same site sit next to each other and
    are labelled by account, since the address alone can't tell them apart.
    <br>Worth knowing <b>why it lends logins instead of holding them</b>: a profile
    IS a cookie jar, and two accounts on one site cannot share a jar - tradera.com
    can only be &ldquo;logged in as&rdquo; one of them at a time. So a profile that
    physically contained every account's logins isn't possible; that's how logins
    work, not a shortcoming here. Profile 99 keeps no logins of its own and lends
    each link the jar it came from, which gives you the thing you actually wanted:
    one place with everything, each item signed in as the right account, several
    accounts of one site open at once in a single window. The catch: a <i>new</i>
    address you type while in profile 99 has no account to guess, so it opens
    signed out - star it from a real profile first. Turn the profile off (or back
    on) from the profile menu; your favourites are never touched.
    <br><b>Where they are:</b> the <b>&#11088; Favourites</b> button at the left end
    of the <b>bookmarks bar</b>, or <b>Ctrl+Shift+B</b> for the full window (search,
    rename, reorder, change which login a link uses, remove). They are also still in
    <b>Menu &rarr; &#11088; Favourites</b>. Don't want the bar button? Right-click the
    bookmarks bar and untick it.</li>
</ul>

<h3 style="color:#39c6da;">&#10067; Help mode &mdash; hover anything</h3>
<p>Press <b>F1</b> (or the <b>&#10067;</b> button) and WhyBrowse explains itself.
Move the mouse over a toolbar button, a menu entry, a bookmark or a field, and a
panel says <b>what it is</b>, <b>where it lives</b> and <b>what it does</b>. Click
<b>More</b> for the full explanation; it stays expanded as you move on to the next
thing, so you can read your way along a row of buttons. <b>Esc</b> leaves the mode.</p>
<p>Nothing is written twice: the panel shows the control's own tooltip, and looks
up the matching entry from the same feature list that <b>Ctrl+Shift+F</b> searches.
So it can't drift out of date - anything documented in one place is explained in
the other.</p>

<h3 style="color:#39c6da;">&#128228; Bulk upload (several pictures in one go)</h3>
<p>For sites that only take <b>one image at a time</b> - posting adverts on
BoardGameGeek being the reason this exists. The clicking was never the real
problem; it was that the file dialog starts from scratch every single time, so
the same folder has to be found and the next picture picked out of it, over and
over.</p>
<p>Right-click the page &rarr; <b>&#128228;&#128228; Upload SEVERAL files here</b>,
pick every picture <i>once</i>, and from then on <b>the file dialog never opens
again</b>. Each time the page asks for a file, WhyBrowse hands over the next one
from the queue. The site receives it by the completely normal route, so nothing
about its upload can behave differently.</p>
<p>It also presses the site's own <b>add image</b> control for you between files,
so a whole batch can go through unattended. If the page is built in a way where
that control can't be found, the run simply waits for you to click it - you still
never see the file dialog. And if the site's input happens to accept several files
at once, the entire queue goes over in a single step.</p>
<p>While a run is going, a <b>&#128228; 3/8</b> button sits in the toolbar. Click it
to see what is still queued, send the next one immediately, skip a file, change how
long to wait between files (raise it if pictures arrive half-uploaded), or stop.
The queue belongs to the site you started it on, so an upload somewhere else can
never eat it, and it is never saved to disk - closing WhyBrowse always clears it.</p>

<h3 style="color:#39c6da;">&#128489; Kill a pop-up box inside the page</h3>
<p><b>This is the one for the advert Vinted throws up after a shipping label</b>,
or the video box on a subtitle site. It is a different thing from the popup guard
below: that one stops a site opening new <i>tabs</i>, and no new-tab rule can ever
touch a box drawn <i>inside</i> the page.</p>
<p>Right-click the page &rarr; <b>&#128489; Kill a pop-up box on this page</b>, then
click the offending box. WhyBrowse highlights the whole overlay (not just the bit
under the pointer) and offers two choices:</p>
<ul>
<li><b>&#128683; Remove it</b> &mdash; the box never appears on that site again.</li>
<li><b>&#10006; Click its own X for me</b> &mdash; the box still appears for a blink,
    but its close button is pressed for you. This is the <b>safer</b> one: the page
    runs its own tidy-up, so anything that depends on the box closing properly
    still works. Use it if removing causes trouble.</li>
</ul>
<p>Two things it handles that a plain element-hide does not. An overlay is normally
a full-screen <b>backdrop</b> with the visible box inside it, and it usually
<b>locks page scrolling</b> &mdash; so hiding only the box leaves a dark sheet over a
page you cannot scroll (the "it went black but did not go away" problem). Removing
takes the whole overlay and unlocks scrolling with it. And because these boxes
appear <i>long after</i> the page has loaded, on an action, the rules are re-applied
continuously rather than once at load.</p>
<p><b>It will not let you hide a QR code by accident.</b> If the description of what
you clicked matches more than one thing on the page, removing is refused outright
and only "click its X" is offered &mdash; a sloppy description could otherwise take
your shipping label's QR code with it. Every rule is listed under the same
right-click menu with a one-click undo, per rule or for the whole site.</p>

<h3 style="color:#39c6da;">&#128070; Click a button for me every time (remember a choice)</h3>
<p><b>This is the right fix for a box you cannot get rid of &mdash; because the site
demands a choice before it will go away.</b> 1177's <i>"Välj region"</i> is the
classic one: remove it and the page won't work; click its X and it pops straight
back, blinking on and off forever.</p>
<p>Instead, right-click the page &rarr; <b>&#128070; Click a button for me every time</b>,
then click the choice you want &mdash; e.g. <b>Västra Götaland</b>. WhyBrowse remembers
it for that site and presses that same button for you whenever the box reappears.
The box gets its answer and closes itself, so <b>there is nothing left to blink</b>.
The highlight is <b>green</b> here (a "do this") rather than the killer's red
("get rid of this").</p>
<p>It only accepts a button it can pin to <b>exactly one</b> element &mdash; auto-clicking
several things at once is never wanted &mdash; and it has the same give-up guard as the
X-clicker, so even a stubborn box can never be made to flash without end. The rule
sits in the same <b>&#128489; Pop-up rules here</b> menu (marked "auto-clicked") with a
one-click undo.</p>

<h3 style="color:#39c6da;">&#128683; Junk sites &amp; popup guard</h3>
<p>Some sites force a new tab full of nonsense on you - the classic being a video
box that won't close, whose <b>Close</b> button opens an advert instead. Chromium's
own popup blocker doesn't stop that, because a popup opened from a <i>click</i>
counts as something you asked for, and you did click something.</p>
<p>There are two separate tools, because they answer different questions:</p>
<ul>
<li><b>&#128683; Junk sites</b> - &ldquo;I never want to see this site again&rdquo;.
    A listed address is refused everywhere, and if the tab was opened purely to
    show it, the tab <b>closes itself at once</b>. Add one while you are standing
    on the junk page: right-click &rarr; <b>&#128295; Troubleshoot &rarr; &#128683;
    Popups &amp; junk sites &rarr; JUNK SITE</b> - it blocks the site and closes the
    tab in one go. Subdomains are included, so <i>togglevpn.org</i> also covers
    <i>ads.togglevpn.org</i>, while lookalikes such as <i>nottogglevpn.org</i> are
    not touched.</li>
<li><b>&#9940; No new tabs from this site</b> - set on the site you are
    <i>reading</i> (e.g. <i>subdl.com</i>), so the junk tab is never created at all,
    whatever address it was going to use. This is the stronger of the two: it
    doesn't matter if the advertiser changes domain tomorrow.</li>
</ul>
<p>A block is never silent - a page quietly crippled just looks broken. When
something is stopped, a <b>&#128683;</b> button appears in the toolbar with a count
for that tab. Click it to see <i>where</i> each blocked popup wanted to go, and
choose: <b>open it anyway</b> (in case the site genuinely needed it), <b>junk that
address for good</b>, or <b>allow popups on this site</b> again. Knowing the address
without visiting it is deliberate - the blocked page is asked where it was going
and refused in the same breath, so the junk site never receives a single request.</p>
<p>Both lists live in one window: the &#128683; button &rarr; <b>Junk sites and popup
rules</b>. You can also block popups everywhere by default and add the few sites
that need them as exceptions.</p>

<h3 style="color:#39c6da;">&#9201; Auction clock (Tradera, eBay, ...)</h3>
<p>An auction site's own countdown is drawn with <i>your computer's</i> clock, and
it can be wrong in ways you cannot see: your clock drifts from the seller's server,
a page restored from cache starts counting from an old "now", and a tick-based
countdown loses time whenever the browser is busy. That is how a bid placed at
"8 seconds left" comes back as <i>auction already closed</i>.</p>
<p>On an auction page WhyBrowse shows its own small panel in the bottom-right corner
&mdash; but only in the <b>closing 3 minutes</b>, and only while the auction is still
running. "8 days left" or "ended two hours ago" is just noise, so the panel stays
hidden until it matters, then appears on its own as the clock drops under 3 minutes.
It reads the auction's <b>absolute</b> end time out of the page's own data (tied to
the item id in the address, so a "related item" in the sidebar can never be picked
by mistake) and measures the offset to the <b>auction site's own server clock</b>.
It shows:</p>
<ul>
<li>the real time left, in <span style="color:#4ade80;">green</span> /
    <span style="color:#fbbf24;">amber</span> / <span style="color:#f87171;">red</span>;</li>
<li><b>Bid before HH:MM:SS</b> - the last safe moment, which is the end time minus
    your margin minus the <i>measured</i> round-trip to the site, because a bid has
    to travel there before the hammer;</li>
<li>the end time it settled on, spelled out, so a wrong pick is visible instead of
    silent (sites often show only <i>22:10</i> when the auction really ends
    <i>22:10:38</i>);</li>
<li>a red warning naming how many seconds the page's own countdown is out, when it
    can be read.</li>
</ul>
<p>Right-click the page &rarr; <b>&#128295; Troubleshoot &rarr; &#9201; Auction
clock</b> to turn it off for a site, change the margin (20 s by default), or force
it onto an auction site this build doesn't know yet. A <b>forced</b> run shows the
panel straight away whatever the time left, so you can check it works. Close the
panel for one page with its &#10005;.</p>

<h3 style="color:#39c6da;">&#128340; The temp tab &mdash; one tab for things you just want to look at</h3>
<p>Opening things breeds tabs. The <b>temp tab</b> is one tab set aside for pages
you only want a look at: opening something "in temp" <b>reuses</b> that tab instead
of making a new one. It sits at the top of the tab strip, right under the pinned
tabs, marked <b>&#128340;</b>.</p>
<p><b>Nothing lands there by itself</b> &mdash; that is the point. Only:</p>
<ul>
<li>a bookmark whose own default you set to <b>Temp</b> (right-click it on the bar
    &rarr; <b>&#9881; A plain click on this one opens&hellip;</b>);</li>
<li>the page right-click menu's <b>&#128340; Open link in the TEMP tab</b>;</li>
<li>the address bar's right-click &rarr; <b>open what's typed here / this page</b>
    in the temp tab;</li>
<li>an <b>"open in the same tab"</b> on a <b>locked</b> or <b>pinned</b> tab &mdash;
    that tab refuses to be navigated away, and the old answer was "then open yet
    another tab"; now it goes to the one spare tab instead.</li>
</ul>
<p>So clicking your way through item after item on <b>Tradera</b> or <b>Vinted</b>
follows the ordinary link rules and can <i>never</i> queue up in the temp tab
writing over itself.</p>
<p>Two more things worth knowing. <b>Settings &rarr; The temp tab</b> lets several
temp tabs take turns (1&ndash;9): with 3, the last three are still there before the
oldest is reused. And a temp tab you <b>pin</b> or <b>lock</b> is never reused &mdash;
that is how you rescue one you decided to keep (or un-tick <b>&#128340; Temp tab</b>
in its own right-click menu).</p>

<h3 style="color:#39c6da;">&#9881; Arrange the page right-click menu</h3>
<p>The menu you get when you right-click a web page has grown to some fifty
entries in a fixed order. It is <b>yours</b> now:</p>
<ul>
<li><b>Drag</b> any entry up or down to put it where you want it;</li>
<li><b>&#128193; New sub-menu</b> makes your own folder &mdash; give it any name
    (add an emoji if you like) and <b>drag entries into it</b>, so a dozen
    rarely-used rows collapse into one line;</li>
<li><b>&#9472; Add separator</b> puts a divider line wherever you want one;</li>
<li><b>&#128065; Hide / Show</b> moves an entry to the <b>Hidden</b> bin (and back)
    &mdash; nothing is ever deleted, so you can always fetch it again;</li>
<li><b>&#128269; Preview the menu</b> shows the result before you save, and
    <b>&#8634; Factory order</b> puts everything back the way it came.</li>
</ul>
<p>Open it from the bottom of the menu itself (<b>&#9881; Arrange this
menu&hellip;</b>) or from <b>&#9881; Settings &rarr; The page right-click
menu</b>. Use <b>&#9650; / &#9660;</b> and <b>&#10145; Move into&hellip;</b> if you
would rather not drag.</p>
<p>Two things make it safe to play with. Entries that only apply <i>sometimes</i>
&mdash; the link actions, "un-hide elements" &mdash; keep the
place you give them and simply stay out of the menu when they don't apply, and
the separators around them close up on their own, so you never get a stray double
line or an empty sub-menu. And an entry a <i>later version</i> of WhyBrowse adds
is appended at the bottom instead of vanishing. <b>&#9881; Arrange this
menu&hellip;</b> itself can be moved anywhere but never hidden, so there is always
a way back. Your arrangement is saved in
<b>Helpfiles/WhyBrowse/page_menu.json</b>.</p>

<h3 style="color:#39c6da;">On-screen keyboard (anti-keylogger)</h3>
<p>Click the <b>&#9000;</b> key icon in the toolbar (or press <b>Ctrl+Shift+K</b>,
or Menu &rarr; Passwords) to open a clickable keyboard. First click into the
login or password box on the page, then type it with the <b>mouse</b>. Because
the characters are inserted directly into the field - never as real key presses -
a hardware or software <b>keylogger captures nothing</b>.</p>
<ul>
<li><b>Swedish</b> and <b>English</b> are built in; pick the language at the top.</li>
<li><b>&#8679; Shift</b> = next key only; <b>&#8682; Caps</b> = stays on (letters).</li>
<li>An extra symbol row keeps <b>@</b> and <b>.</b> one click away for e-mails.</li>
<li><b>Add more languages:</b> drop a small <i>.json</i> layout file into
    <b>Helpfiles/WhyBrowse/keyboard_layouts/</b> (a README there shows the format),
    then click <b>&#8635; Reload layouts</b>.</li>
</ul>

<h3 style="color:#39c6da;">A page that suddenly will not scroll</h3>
<p>Sites stop the page behind a pop-up from scrolling while the pop-up is up,
and lift that again when you close it. If the pop-up gets hidden or removed by
something else &mdash; the cookie/nag hider, the pop-up killer, an element you
zapped, or the site's own script losing its place &mdash; nobody ever lifts the
lock: <b>no scrollbar, and the mouse wheel does nothing</b>, until you reload.</p>
<p>WhyBrowse now notices that and releases the page by itself. It is deliberately
careful: it only acts when the page really is longer than the window <i>and</i>
nothing visible is covering it &mdash; a real, visible dialog is <i>supposed</i>
to stop the page behind it from scrolling, so those are left alone.</p>
<p>If one still sticks, right-click the page and pick
<b>&#128275; Get scrolling back (unlock this page)</b>. That releases it
immediately, no reload, whatever is on screen. Don't want the automatic part?
Turn it off in <b>Settings &rarr; Performance</b>, or for a single site under
<b>&#127760; Exceptions for this site &rarr; "Auto-release a stuck scrollbar
here"</b>.</p>

<h3 style="color:#39c6da;">A page that scrolls you back while you are reading</h3>
<p>You open a page, start scrolling - and a second or two later it drags itself
back to one particular spot. The page is not finished: late stylesheets, fonts,
adverts and lazy images keep arriving for several seconds, and they bring scroll
calls with them (a saved position being restored, a <i>#fragment</i> applied
late, a banner scrolling itself into view). They land <i>after</i> you started
reading, so they take the page away from you.</p>
<p><b>Keep my place</b> settles that by asking who asked last: the moment
<b>you</b> scroll a page, the page does not get to move you again. Anything you
<i>ask</i> for still works - a link, a &quot;back to top&quot; button, an in-page
anchor, a new view inside a web app - and only the main page scroll is guarded,
never an inner panel like a chat list or a spreadsheet grid. If a site fights it
hard it gives up rather than flicker.</p>
<p>It is on by default. Turn it off in <b>Settings &rarr; Performance</b>, or for
one site under <b>&#127760; Exceptions for this site &rarr; &quot;Keep my place
while a page loads here&quot;</b>.</p>

<h3 style="color:#39c6da;">Pictures, video and sound (right-click)</h3>
<p>Right-click a picture on a page and you get <b>&#128444; Copy image</b>,
<b>&#128190; Save image</b>, <b>&#128190; Save image as&hellip;</b>,
<b>&#9112; Copy image address</b> and <b>&#8599; Open image in a new tab</b>.
Right-click a video or a sound and you get its address as well. A drawn
<i>canvas</i> has no address of its own, so there you only get Copy image,
Save image and Save image as &mdash; which is enough, because Chromium hands
over the actual pixels.</p>
<p><b>Save image</b> drops the picture straight into your download folder under
its own name, with no pop-up. <b>Save image as&hellip;</b> opens the download
pop-up instead, where the name is split into a <i>name</i> box and a small
<i>extension</i> box: the name box is focused and selected so you just type,
while the extension box is left alone (change it only when you want to, e.g.
<i>jpeg</i> &rarr; <i>jpg</i>). Either way your download folder and your
<i>"file with that name already exists"</i> choice apply. Don't want these rows?
Move or hide any of them from <b>&#9881; Arrange this menu&hellip;</b> at the
bottom of the same right-click menu.</p>

<h3 style="color:#39c6da;">Saving a file you already have (backup old / overwrite)</h3>
<p>When a download would land on top of a file that is already in the folder,
WhyBrowse asks what to do instead of silently adding a number:</p>
<ul>
<li><b>&#128190; Back up the old one</b> - the old file is renamed
    <b>Backup&lt;CODE&gt;-name</b> and the new one takes the clean name. Nothing is
    lost. This is the same convention <b>File_manager</b> uses, and both programs
    share one list of used codes, so two backups of the same file can never end up
    with the same name.</li>
<li><b>&#128290; Save with a number</b> - what it always did: <i>Foo (2).py</i>.</li>
<li><b>&#9851; Overwrite, no backup</b> - the old file goes.</li>
</ul>
<p>A download that <i>arrives</i> already numbered counts as the same file too:
<b>Foo (3).py</b> landing next to <b>Foo.py</b> is treated as another copy of it,
so "back up the old one" hands you a clean <b>Foo.py</b> again. (Only a 1-3 digit
number in brackets counts, so <i>Report (2024).pdf</i> is left alone.)</p>
<p><b>Nothing is deleted until the download has actually finished.</b> The old file
is moved aside first and only removed once the transfer reports "completed" - if it
fails or you cancel it, your old file is put straight back.</p>
<p>Tick <b>Always do this</b> in the pop-up to stop being asked. To change your
mind, or to turn the question back on, go to <b>Settings &rarr; Downloads &rarr;
"When you already have a file with that name"</b>. It is saved per profile.</p>

<h3 style="color:#39c6da;">Download video &amp; music</h3>
<p>Menu &rarr; <b>&#8595; Download video / audio</b>, or right-click a page/link
&rarr; <b>Download video/audio</b>. It uses <b>yt-dlp</b> (the well-known
downloader) to save clips from YouTube, SoundCloud, Vimeo and ~1800 other sites,
including streams that are <i>hidden inside</i> a page. Pick a format (best video
as MP4, or audio-only as MP3), choose a folder, and press <b>Download</b>.</p>
<ul>
<li><b>First time:</b> if yt-dlp is missing, click <b>Get yt-dlp</b> and it
    downloads the official tool into <b>Helpfiles/WhyBrowse/tools/</b>.</li>
<li><b>ffmpeg</b> (for MP3 and the "best quality" merge) is found automatically if
    it's on your PATH or in the tools / Helpfiles/1---Movie folder; otherwise use a
    "no ffmpeg" option.</li>
<li><b>Members-only / age-gated:</b> tick "Use my Firefox cookies".</li>
<li><b>Honest limit:</b> truly DRM-protected streams (Netflix, Disney+, Spotify,
    etc.) are encrypted and <b>cannot</b> be downloaded by any tool. Only download
    content you have the right to.</li>
</ul>

<h3 style="color:#39c6da;">Torrents &amp; magnet links &#129522;</h3>
<p>A <b>magnet link</b> is not a file. There is nothing stored behind it and no
address to fetch &mdash; it is a fingerprint of what you want plus a hint about
who might have it, which is why clicking one in an ordinary browser looks like
it does nothing. WhyBrowse acts on it instead, in one of three ways (your
choice, per link or once and for all in <b>Settings &rarr; Torrents</b>):</p>
<ul>
<li><b>&#8595; Download the files here</b> &mdash; the built-in engine
    (<b>libtorrent</b>, the same engine qBittorrent and Deluge are built on)
    fetches the real files into your torrent folder. Watch it in
    <b>Menu &rarr; &#129522; Torrents</b>. Needs <code>pip install libtorrent</code>
    once.</li>
<li><b>&#128190; Save the link</b> &mdash; writes a tiny <b>name.magnet</b> file
    into the torrent folder. Point your torrent program's <i>watch folder</i>
    there and it picks the link up by itself.</li>
<li><b>&#8599; Open in my torrent program</b> &mdash; hands it to whatever
    Windows uses for magnet: links.</li>
</ul>
<p>It reacts when you <b>click</b> one on a page, <b>paste</b> one in the address
bar, <b>copy</b> one anywhere (the clipboard watch &mdash; this is the "I just
copied a torrent link" case), when another program hands one to WhyBrowse, or
from the right-click menu (<b>&#129522; Torrent this link</b>). An ordinary
<code>https://&hellip;/x.torrent</code> address counts too, so it never lands in
your normal Downloads folder by mistake.</p>
<ul>
<li><b>Its own folder:</b> torrents can go to a separate folder (X:&#92; or wherever)
    instead of the download folder.</li>
<li><b>Ask, automatic or ignore:</b> the pop-up asks by default; tick "always do
    this" in it, or set it in Settings, and it stops asking.</li>
<li><b>Finished = paused.</b> Nothing keeps uploading from your computer unless
    you turn "keep seeding" on. The Torrents window can also close itself when
    everything is done &mdash; tick <b>Close this window when everything has
    finished</b>, in the window or in Settings.</li>
<li><b>An ordinary window.</b> The Torrents window is not glued on top of the
    browser: click WhyBrowse and it goes behind, it has its own taskbar button,
    and it remembers its size and position.</li>
<li><b>Honest limits:</b> a torrent with no live peers downloads nothing &mdash;
    that is BitTorrent, not a bug (the window says "looking for the torrent
    info&hellip;" while it tries). UPnP is off by default because its shutdown
    would add ~20 seconds to closing WhyBrowse. Only download what you have the
    right to.</li>
<li><b>Interrupted?</b> Downloads only run while WhyBrowse is open. Close it half-way
    and the unfinished torrents are remembered; about 9 seconds after the next start
    they continue by themselves (the files already on disk are checked, so nothing
    starts over) &mdash; unless "continue unfinished torrents at start" is off in
    Settings. (A torrent you paused is also continued at the next start; while
    WhyBrowse stays open it stays paused until you press Resume.) Anything
    that could not be restarted (for example the torrent drive was not plugged in)
    is kept, and the <b>profile circle &rarr; &#128260; Restart</b> section at the
    bottom starts it again with one click.</li>
</ul>

<h3 style="color:#39c6da;">When a page won't load</h3>
<p>If a page fails to load, WhyBrowse can tell you <i>which of its own features</i>
might be blocking it. If the cause is something WhyBrowse controls, a small panel
pops up listing the active features (ad blocker, third-party-cookie block,
JavaScript off, animation freeze) with one click to <b>turn the chosen ones off
for that site only and reload</b>. If WhyBrowse isn't blocking anything, it says
so — then it's the site or your connection. Open it any time from Menu &rarr;
<b>❓ Why isn't this page loading?</b> or the page right-click menu. You can switch
the automatic pop-up off inside that panel.</p>
<p>The automatic pop-up only appears when the page really <i>is</i> empty:
Chromium reports "load failed" for plenty of harmless reasons (a navigation
replaced by the next one, an aborted extra file, a late redirect) and the page
then paints a fraction of a second later. WhyBrowse waits, checks whether the
page actually has content, and stays quiet when it does.</p>

<h3 style="color:#39c6da;">Stuck on "Verify you are human"</h3>
<p>Cloudflare, hCaptcha and friends run their check inside an iframe on their own
domain. It needs its own cookie (which counts as <i>third-party</i> from the site
you are visiting), it needs every one of its scripts to reach the network, and it
needs an unfrozen page. WhyBrowse's ad blocker, third-party-cookie block and
animation freeze each break one of those — so you tick the box, it spins, and you
land back on the check. WhyBrowse now:</p>
<ul>
<li>never blocks a verification provider's cookies or requests, and never applies
    cosmetic hiding/freezing to a challenge page;</li>
<li><b>reports this engine's real Chrome version.</b> WhyBrowse used to rewrite
    the version to a value refreshed from Google at most once a month, so a
    stale number made a Chromium 140 engine advertise itself as Chrome 136 while
    still exposing every Chrome 140 feature. Bot checks feature-detect the engine
    and compare — a version that does not match the feature set is a hard fail.
    It now tells the truth (and only claims a newer version when the engine is
    genuinely years behind);</li>
<li>keeps <b>navigator.userAgentData</b> in step with the user-agent string it
    reports (they used to disagree, which alone is enough for a bot check to
    reject you);</li>
<li>spots a "Verify you are human" wall the first time a site shows one, turns the
    blocking features off <b>for that site only</b>, and reloads once.</li>
</ul>
<p>If a site still won't let you through, right-click the page &rarr;
<b>🔧 Troubleshoot this page</b> &rarr; <b>🤖 Stuck on "Verify you are human"
here — let it through</b>. The automatic version can be switched off in
Settings &rarr; Privacy &amp; blocking. None of this solves, skips or fakes a
challenge — it only stops WhyBrowse standing in its way.</p>
<p>To see <i>why</i> a site still rejects you, use <b>🔧 Troubleshoot &rarr; 🕵 What
this page sees about me</b>. It reads the real values out of the page — user
agent, client hints, the engine's actual version, whether a cookie can be set,
WebGL, time zone — and points at whatever looks wrong. You can also set the user
agent by hand in Settings &rarr; Privacy &amp; blocking (empty = automatic).</p>
<h3 style="color:#39c6da;">Google says "this browser or app may not be secure"</h3>
<p>Google's sign-in refuses browsers it judges to be embedded. If it turns you
away right after the password, there are two things to try, in this order.</p>
<ol>
<li><b>Settings &rarr; Privacy &amp; blocking &rarr; "Present a complete Chrome
identity"</b> (on by default). The engine used to contradict itself: its
user-agent said <i>Chrome</i> while the <code>Sec-CH-UA</code> header sent
beside it said only <i>Chromium</i>, <code>window.chrome</code> was an empty
object, and no <code>Accept-Language</code> header was sent at all. This makes
them agree. It stands down on its own if you set a custom user agent by hand.</li>
<li><b>☰ menu &rarr; 🔑 Bring a Google sign-in over from Firefox…</b> — the one
that always works. Sign in to Google in Firefox, then copy that finished session
into one chosen profile here; Google's check never runs. The dialog says which
of your Firefox profiles are signed in, and names the profile it will write
into — only that profile's Google login is replaced.</li>
</ol>
<p>Note that a profile which is already signed in <i>stays</i> signed in, so
this normally only ever bites a brand-new profile. Chrome and Edge cannot be
used as the source: their cookies have been sealed with app-bound encryption
since Chrome 127.</p>
<p><b>Honest limit:</b> some checks judge things no setting inside the page can
change — the TLS handshake, the exact network fingerprint, your IP's reputation
(a VPN or shared address is often enough on its own). If the report above looks
clean and a site still refuses, that is what is happening, and no browser setting
will fix it: use <b>🌐 Open in my system browser</b> for that site. It is also
worth updating the engine (below), since an old engine both fails feature checks
and reports an old Chrome.</p>

<h3 style="color:#39c6da;">Updating the browser engine</h3>
<p>Menu &rarr; <b>🌐 Browser engine version</b> (also in Settings &rarr; Engine &amp;
dependencies) shows which Chromium is built in and offers three ways to update
it:</p>
<ul>
<li><b>Create updater (.bat)</b> — the reliable one. Writes
    <i>Update_engine.bat</i> next to WhyBrowse's own files and opens the folder.
    <b>Close WhyBrowse, then double-click it.</b></li>
<li><b>Copy</b> — the exact pip command, ready to paste into a Command Prompt or
    PowerShell window.</li>
<li><b>Try updating now</b> — runs pip from inside the program. This often
    fails, and that is normal, not a bug: Windows will not let anything replace
    files that are currently in use, and the engine is in use by the very
    program asking to replace it. If you see "Access is denied", use the .bat.</li>
</ul>
<p>Restart WhyBrowse afterwards to pick up the new engine.</p>
<p><i>Harmless console messages:</i> lines like "Failed to resolve address for
ec2-…amazonaws.com" are just WebRTC/P2P probes failing DNS — they do not affect
page loading and can be ignored (WhyBrowse already quietens most of them).</p>

<h3 style="color:#39c6da;">Saved words / snippets</h3>
<p>Save words or phrases once and re-insert them into any web field with the
mouse — handy for searches you repeat (e.g. <i>Brädspel</i>, <i>Sällskapsspel</i>
on Blocket) or for your name / address / e-mail.</p>
<ul>
<li><b>To use:</b> right-click inside a text box on a page &rarr;
    <b>📝 Saved words / snippets</b> &rarr; pick a word; it's typed into the field.</li>
<li><b>One-click shortcut:</b> if this site has a saved word, the top one now sits
    DIRECTLY on the right-click menu as <b>📝 Insert: …</b> (no sub-menu hop). With
    only one saved word for the site, that single word is right there on the row.</li>
<li><b>To save:</b> select the text first, then right-click &rarr; 📝 &rarr;
    <b>Save "…" for THIS SITE / THIS PROFILE / ALL SITES</b> (three direct choices).
    With nothing selected, use <b>Save a new word…</b> and type it.</li>
<li><b>Three scopes:</b> a word saved for a <b>site</b> only appears on that domain;
    a <b>profile</b> word follows that profile everywhere; an <b>all sites</b> word is
    always available. Passwords are never used here — only what you choose to save.</li>
<li><b>⭐ Favourites (pin the ones you use most):</b> in <b>Manage</b>, select a word
    and press <b>⭐ Pin / unpin</b> (or double-click it). Pinned words sit as a row of
    one-click <b>⭐ …</b> shortcuts at the very TOP of the right-click menu, above the
    “This site” folder — so several favourites are always one click away, on every
    site. Use <b>▲ ▼</b> to set their order.</li>
<li><b>Manage:</b> Menu &rarr; <b>📝 Saved words / snippets…</b> to add, remove, or pin.</li>
</ul>

<h3 style="color:#39c6da;">Tookmarks &amp; Copymarks (other profiles' bookmarks)</h3>
<ul>
<li><b>Tookmarks</b> (Menu → 👻 Tookmarks, also a switch in Settings; off by
    default): mirrors <b>one</b> other profile's bookmarks as a live
    <b>👻 Tookmarks: name</b> folder in the bar, next to your own 📚 Bookmarks
    folder. In <b>Menu → 👻 Tookmarks</b> you turn it on and pick which profile to
    mirror; switch profile any time from the same menu. Click an entry to open —
    nothing is copied, so it always reflects the latest.</li>
<li><b>Copymarks</b> (Settings): physically <b>copies</b> all other profiles'
    bookmarks into this profile (each under a "Copymarks: name" folder). It asks
    first, because Tookmarks usually makes this unnecessary — use it only to keep a
    real copy here, e.g. as a backup before deleting the originals elsewhere.</li>
</ul>

<h3 style="color:#39c6da;">Profiles (multiple accounts)</h3>
<p>The coloured <b>badge</b> left of the address bar is your profile. Each profile
has its own cookies, logins, history and bookmarks, so you can be signed in to the
same site under different accounts at once. Click/hover the badge to switch, create,
edit or pause profiles, or press <b>F1-F12</b>.</p>
<ul>
<li><b>&#129514; Container tabs (several accounts, ONE window, NO profile switch):</b>
    if you don't want to switch profiles just to open a second Gmail / ChatGPT, use a
    <b>container</b>. Right-click a tab &rarr; <b>&#129514; Containers (separate
    logins)</b> &rarr; <b>New container + blank tab</b>, name it (e.g. "Work"), and go.
    A container is its own cookie store, so container tabs stay signed in as their own
    account - two Gmail accounts can sit side by side as two tabs. Container tabs are
    labelled with the container name and come back logged in after a restart. Same
    menu also opens the current page in a container, and renames / recolours / deletes
    containers. (Containers = separate logins in one window; profiles = a whole
    separate window's worth of tabs.)</li>
<li><b>Auto-login:</b> in <b>Edit profile</b> you can store ONE password (encrypted
    to your Windows account) + your e-mail as the login. When a site's session has
    expired, WhyBrowse fills the sign-in form (optionally presses the button). Normal
    e-mail+password sites work; Google's multi-step + 2FA you still do yourself.</li>
<li><b>Messaging profile + notifications:</b> tick "Messaging profile" in Edit
    profile, pin your chat tabs (web.whatsapp.com, messenger.com, messages.google.com/
    web). When a message arrives, a 🔴 lights on the tab, and even from ANOTHER profile
    a small popup appears beside the window — click it to jump there. (Needs
    "Keep other profiles' tabs loaded" ON in Settings &rarr; Performance.)</li>
<li><b>Float a tab:</b> right-click a tab &rarr; <b>🪟 Pop out to floating window</b>
    &rarr; choose <b>📌 Always on top</b> or <b>🪟 Normal window (can go behind
    others)</b> - a small window that keeps showing that page even when you switch
    profiles. Good for watching a chat or sheet while you work elsewhere. Change
    your mind later? Click the 📌/🪟 button in the floating window's own title bar.</li>
</ul>

<h3 style="color:#39c6da;">Tab power tools (right-click a tab)</h3>
<ul>
<li><b>Pin</b> - pinned tabs keep the exact page you chose: clicking a link opens it
    in a NEW tab, and after a restart the tab returns to its pinned page.</li>
<li><b>Lock (1/2/3/3+)</b> - protect a tab: level 1 ignores bookmark clicks, level 2
    also ignores the address bars, level 3 also opens every link in a new tab. Level
    <b>3+</b> is friendlier: you keep browsing <i>within the same domain</i> in this
    same tab (e.g. all of <i>tradera.com</i>, including its www./m./shop. subdomains),
    and only a link to <i>another</i> domain opens a new tab - handy for staying put
    while you click around one site. <b>3+ also overrides a pin</b>: on a tab that is
    both pinned and 3+, same-domain links still open in this tab (only other domains
    open a new tab), so a pinned "home" tab can be browsed within its own site.
    Locked tabs show a red &#10005;.</li>
<li><b>&#9749; Not auto-sleep</b> - every idle background tab sleeps on its own to
    save memory (that is the default, for tabs of other profiles too); tick this
    on a tab or a domain to keep that one loaded. A tab that is making sound,
    and chat/AI/mail/video sites, are skipped without you asking.</li>
<li><b>&#128164; Sleep delay</b> - right under it: give ONE tab or one whole
    domain its own number of idle minutes instead of the general delay. A number
    set by hand also overrides the built-in skip list, so it is how you make a
    chat or video site sleep after all.</li>
<li><b>&#128266; Mute / volume</b> - the toolbar speaker mutes the current tab
    (right-click for a volume slider, or mute/unmute all).</li>
<li><b>&#128269; Jump to a word on this site</b> (right-click a tab &rarr; THIS DOMAIN)
    - every time a page on that site opens, WhyBrowse scrolls to the FIRST place your
    chosen word/phrase appears and briefly highlights it. Pick whether to land on the
    row <i>above</i>, <i>exactly on</i>, or <i>below</i> the word. Read-only (it never
    types anything). Great for landing straight on a section by name. (In Google
    Sheets use its own <b>Ctrl+F</b> instead - the grid is a canvas.)</li>
<li><b>&#128205; Remember scroll position here</b> - reopen a site right where you left
    off (pixel position, including some inner scroll panels).</li>
<li><b>&#128228; Upload folder for this site</b> - when a site asks you to pick a file
    to UPLOAD, a normal browser opens wherever you last picked a file <i>anywhere</i>,
    so a site whose files live on another drive keeps starting in the wrong place.
    Give each site its own start folder here. A pop-up also offers your
    <b>favourite folders</b> as a one-click list (add/remove them right in that
    pop-up), plus <b>Browse the computer&hellip;</b> for a one-off. Tick "Also make this
    the upload folder for &lt;site&gt;" and it opens there directly from then on.
    Choose when the pop-up appears in <b>Settings &rarr; Uploads</b>.
    The file picker itself is WhyBrowse's own: it opens in the folder you last picked
    from <i>on that site</i> (for 3 hours), and its left-hand column holds your
    <b>pinned folders</b> (press <b>Pin this folder</b> under the list; they are the same
    as your favourites), the site's folder, the <b>last 12 folders</b> you picked from,
    Desktop / Documents / Pictures / Downloads and the drives. <b>Remove this folder
    from the list</b> unpins the folder you are in and takes it off the recent list.
    So the 6-7 pictures of one advert are one click each. (Settings &rarr; Uploads can
    switch back to the Windows picker.)
    <i>Downloads are separate</i> - they all keep going to your one download folder.</li>
<li>Also: rename a tab or a whole domain, quick links / saved sub-pages, auto-refresh
    on focus, and "Pop out to floating window" (always-on-top or normal).</li>
</ul>

<h3 style="color:#39c6da;">Google Sheets helpers</h3>
<ul>
<li><b>Ctrl+F</b> opens Sheets' OWN search (not the browser find bar).</li>
<li><b>Go to a row/cell:</b> right-click the Sheets tab &rarr; <b>📊 Go to row / cell</b>
    &rarr; type e.g. <i>A100</i> (or just <i>100</i>) to jump there instantly.</li>
<li><b>Saved jumps</b> (per spreadsheet) and <b>📌 Auto-go to a row every time the tab
    opens/refreshes</b> - so a big sheet always lands where you want.</li>
<li><b>Stay signed in</b> (Settings, cookies section, on by default) keeps Google/
    Microsoft cookies flowing so pinned Sheets don't go blank and demand re-login.</li>
</ul>

<h3 style="color:#39c6da;">Forms, drafts &amp; the address bar</h3>
<ul>
<li><b>Remember a field:</b> right-click a field &rarr; <b>💾 Remember this field's
    value here</b> to auto-fill it next time on that site (manual, per site - never
    search boxes or messages).</li>
<li><b>Message drafts:</b> what you type in message boxes (Vinted, Tradera...) is
    live-saved for 7 days. If a site wipes your half-written reply, get it back from
    Menu &rarr; History &rarr; <b>&#9993; Recover message drafts</b>.</li>
<li><b>Address bar icons:</b> <b>&#127344;</b> selects all the text; <b>&#127346;</b>
    selects all AND copies it to the clipboard.</li>
</ul>

<h3 style="color:#39c6da;">Bookmarks bar extras</h3>
<ul>
<li><b>Coloured sections:</b> right-click the empty bar &rarr; <b>🏷&#10133; New
    section</b> to add a coloured label that groups the bookmarks after it.</li>
<li><b>Open in new vs same tab:</b> bar bookmarks open in a NEW tab by default;
    right-click one &rarr; tick "Open in same tab" for that item.</li>
<li><b>Move a bookmark without the manager (no dragging):</b> right-click a
    bookmark or folder, on the bar <i>or inside a folder's dropdown</i> &rarr;
    <b>&#9986; Move...</b> (it gets a dashed outline on the bar). Then right-click
    where it should go: another bookmark &rarr; <b>Move here &mdash; above / below
    this one</b>, a folder &rarr; <b>Move into this folder</b>, the bar's empty space
    &rarr; <b>Move to the end of the bar</b>, the &#128218; Bookmarks button &rarr;
    <b>Move to the end of the Bookmarks menu</b>. <b>Cancel the move</b> is in the same
    menus. A folder cannot be moved into itself.</li>
</ul>

<h3 style="color:#39c6da;">More handy bits</h3>
<ul>
<li><b>Scroll speed:</b> Settings &rarr; Performance - how far each wheel notch
    scrolls (30-400%).</li>
<li><b>Set as default browser:</b> Settings &rarr; Engine &amp; dependencies - it
    registers WhyBrowse and opens Windows' "Default apps" so you pick it (the last
    step must be yours - Windows blocks apps from doing it).</li>
<li><b>Backup &amp; restore:</b> Menu &rarr; <b>&#128190; Backup &amp; Restore</b> -
    save/restore bookmarks, logins, passwords and settings as one .zip.</li>
<li><b>&#129514; Find what's breaking this page:</b> page right-click - turn WhyBrowse's
    features off one at a time (or all) for THIS site to see which one is interfering.
    The toolbar <b>&#129529;</b> button does a quick all-features-off "plain mode".</li>
<li><b>YouTube ads</b> are skipped/hidden, and <b>IMDb</b> always opens the cleaner
    "reference" layout (both toggleable in Settings &rarr; Anti-annoyance).</li>
</ul>

<h3 style="color:#39c6da;">Profiles overview / stats</h3>
<p>Menu &rarr; <b>📊 Profiles overview / stats</b> opens a dashboard of every
profile whose tabs are live this session (the active profile from the tab bar,
plus any background profile whose tabs are kept alive). For each tab you get
one-click checkboxes to set its behaviour instantly — <b>Pin</b>,
<b>Auto-refresh</b>, <b>Lock</b>, <b>No sleep</b> — and, if
the optional <b>psutil</b> package is installed (<i>pip install psutil</i>),
per-tab <b>memory</b> and <b>CPU</b> with a running total. It stays open while
you browse and updates live. (Tabs on the same site can share one process, so
per-tab memory may repeat; the total counts each process once.)</p>

<h3 style="color:#39c6da;">Report a bug / log a page</h3>
<p>When a page misbehaves — for example a site shows only a few items and will
not scroll — press <b>Ctrl+Shift+D</b> (or Menu &rarr; <b>🐞 Report a bug</b>)
<i>while you are looking at it</i>. The browser has been quietly keeping a short
trail of what happened (which profile, which tab, each page load and whether it
succeeded, tab and profile switches). The dialog shows the current context and
that trail; add a comment describing what you saw and press <b>Save</b>. A
report (a readable <i>.txt</i> plus a <i>.json</i> sidecar) is written to
<b>Helpfiles/WhyBrowse/bug_reports</b>. Nothing is sent anywhere, and no
passwords, vault contents or cookies are included — only tab/setting metadata
and the activity trail, so the exact what / when / how can be reviewed later.</p>

<h3 style="color:#39c6da;">How links open (new tab vs same tab)</h3>
<p>By default a clicked link opens in a <b>new tab</b>, so it is never a guess
whether it replaces the page you are on. To keep a site's own links in the
<b>same</b> tab (handy for a shop you browse around in), right-click any link on
that site &rarr; <b>↩ …except links to &lt;domain&gt; (open in same tab)</b>. The
same menu has <b>🆕 Open links in a new tab by default</b> to turn the whole
behaviour off. A <b>locked</b> (level 3) or <b>pinned</b> tab always opens links
in a new tab, whatever the rule says; a <b>3+</b>-locked tab keeps same-domain
links in this tab and only sends other domains to a new tab (and 3+ wins even when
the tab is also pinned). Whether the new tab
comes to the front or opens in the background follows <i>Settings &rarr;
open-link default</i>.</p>

<h3 style="color:#39c6da;">Missing images / covers (lazy loading)</h3>
<p>Some sites (e.g. Bandcamp) leave a placeholder in a picture and only load the
real image when it scrolls into view. WhyBrowse loads them all straight away so
nothing stays blank. If a page ever loads too many images because of this, turn
it off for that site: right-click the page &rarr; Troubleshoot &rarr; Exceptions
&rarr; <b>🖼 Load lazy (data-src) images here</b>.</p>

<h3 style="color:#39c6da;">Privacy &amp; data</h3>
<p>Your bookmarks, history, cookies and logins are stored next to the program
in the <b>Helpfiles/WhyBrowse</b> folder, so they travel with the program. Logs
go to <b>Helpfiles/0---Empty</b>. Nothing is sent anywhere by WhyBrowse itself.
Saved profile passwords and the password vault are encrypted to your Windows
account (DPAPI); website cookies in this build are stored unencrypted in the
profile folder, so keep that folder private.</p>
"""


class HelpDialog(QDialog):
    def __init__(self, parent):
        super().__init__(parent)
        self.setWindowTitle(APP_NAME + " - Help")
        self.setModal(True)
        self.resize(640, 620)
        self.setStyleSheet("background:#1b2030; color:#e8edf6;")    # fixed dark (styled HTML)
        apply_window_icon(self)

        lay = QVBoxLayout(self)
        lay.setContentsMargins(8, 8, 8, 8)

        view = QTextBrowser()                      # scrollable + mouse wheel
        view.setOpenExternalLinks(True)
        # Fixed dark styling + an explicit, grabbable scrollbar thumb (a bare
        # background rule alone hides the native thumb on Windows).
        view.setStyleSheet(
            "QTextBrowser{background:#11151f; border:none; padding:10px;}"
            + scrollbar_qss(handle="#3a4358", handle_hover="#5a6a8c"))
        view.setHtml(HELP_TEXT)
        lay.addWidget(view)

        close = QPushButton("Close")
        close.setStyleSheet(
            "QPushButton{background:%s; color:%s; border:none; padding:6px 18px; "
            "border-radius:6px;}QPushButton:hover{background:%s;}"
            % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
        close.clicked.connect(self.accept)
        lay.addWidget(close, alignment=Qt.AlignmentFlag.AlignCenter)

        self.activateWindow()
        self.setFocus()

    def keyPressEvent(self, e):
        if e.key() == Qt.Key.Key_Escape:
            self.accept()
        else:
            super().keyPressEvent(e)


# ============================================================================
#  DEL 12 - FIND BAR  (Ctrl+F find-on-page)
# ============================================================================
class FindBar(QWidget):
    def __init__(self, window):
        super().__init__(window)
        self._window = window
        self.setStyleSheet("background:%s;" % C_BAR_BG)
        lay = QHBoxLayout(self)
        lay.setContentsMargins(8, 4, 8, 4)
        lay.setSpacing(6)

        self.edit = QLineEdit()
        self.edit.setPlaceholderText("Find on page...")
        self.edit.setStyleSheet(
            "QLineEdit{background:%s; color:%s; border:1px solid #39456a; "
            "border-radius:6px; padding:4px 8px;}" % (C_ADDR_BG, C_ADDR_FG))
        self.edit.returnPressed.connect(lambda: self.find(True))
        self.edit.textChanged.connect(lambda t: self.find(True))
        lay.addWidget(self.edit, 1)

        for txt, fn in (("Previous", lambda: self.find(False)),
                        ("Next", lambda: self.find(True)),
                        ("Close", self.hide_bar)):
            b = QPushButton(txt)
            b.setStyleSheet(
                "QPushButton{background:%s; color:%s; border:none; padding:4px 12px; "
                "border-radius:6px;}QPushButton:hover{background:%s;}"
                % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
            b.clicked.connect(fn)
            lay.addWidget(b)
        self.hide()

    def open_bar(self):
        # Just show WhyBrowse's find bar. The decision of whether Ctrl+F should
        # open this bar OR pass through to a site with its own find (Sheets/Docs)
        # is made BEFORE this is called, by Browser.eventFilter — so there is no
        # fragile synthetic-key forwarding here anymore.
        self.show()
        self.edit.setFocus()
        self.edit.selectAll()

    def hide_bar(self):
        view = self._window.current_view()
        if view:
            view.findText("")
        self.hide()

    def find(self, forward):
        view = self._window.current_view()
        if not view:
            return
        flags = QWebEnginePage.FindFlag(0)
        if not forward:
            flags |= QWebEnginePage.FindFlag.FindBackward
        view.findText(self.edit.text(), flags)

    def keyPressEvent(self, e):
        if e.key() == Qt.Key.Key_Escape:
            self.hide_bar()
        else:
            super().keyPressEvent(e)


# ============================================================================
#  DEL 12D1 - UPLOAD FOLDER CHOOSER  (per-site upload folders + favourites)
# ----------------------------------------------------------------------------
#  Shown when a page asks you to pick a file to UPLOAD. Chromium's own picker
#  always opens in the folder you last used ANYWHERE - which is why a site whose
#  files live on B: kept starting on C: just because the last download went
#  there. Here you get, in one small popup:
#     - this site's own saved folder (if set) at the top,
#     - your favourite folders, for a one-click pick,
#     - Browse... for a one-off folder that isn't worth saving,
#     - and a tick to make the picked folder THIS SITE'S folder from now on
#       (after which uploads on that site open there directly, no popup).
#  ENTER opens the highlighted folder; ESC cancels the upload.
#  NOTE: this is UPLOAD only. Downloads keep going to the one place you set
#  (profile save_dir / "Often-used save folders") - deliberately separate.
# ============================================================================
class UploadFolderDialog(QDialog):
    def __init__(self, parent, host, site_dir, favs, for_site_setup=False):
        super().__init__(parent)
        self._host = host or ""
        self._favs = [dict(f) for f in (favs or [])]
        self._site_dir = site_dir or ""
        self.chosen_dir = None          # folder the picker should start in
        self.remember = for_site_setup  # also save it as this site's folder

        self.setWindowTitle(
            ("Upload folder for %s" % self._host) if for_site_setup
            else ("Where are the files for %s?" % (self._host or "this site")))
        self.setMinimumWidth(600)

        lay = QVBoxLayout(self)
        lay.addWidget(QLabel(
            "Choose the folder the upload picker should start in for "
            "<b>%s</b>:" % (self._host or "this site")))

        self.list = QListWidget()
        self.list.itemActivated.connect(lambda _i: self._accept_selected())
        lay.addWidget(self.list, 1)
        self._reload_list()

        self.chk = QCheckBox(
            "Also make this the upload folder for %s  "
            "(then it opens here directly next time)" % (self._host or "this site"))
        self.chk.setChecked(not self._site_dir)
        if for_site_setup:
            self.chk.hide()             # in "set the site's folder" mode it's implied
        lay.addWidget(self.chk)

        row = QHBoxLayout()
        b_open = QPushButton("Open")            # normal colour: default button
        b_open.setDefault(True)
        b_open.clicked.connect(self._accept_selected)
        b_browse = QPushButton("📂  Browse the computer...")   # normal colour
        b_browse.clicked.connect(self._browse)
        b_cancel = QPushButton("Cancel")        # normal colour
        b_cancel.clicked.connect(self.reject)
        row.addWidget(b_open)
        row.addWidget(b_browse)
        row.addStretch(1)
        row.addWidget(b_cancel)
        lay.addLayout(row)

        row2 = QHBoxLayout()
        b_add = QPushButton("⭐  Add a favourite folder...")    # normal colour
        b_add.clicked.connect(self._add_fav)
        b_del = QPushButton("🗑  Remove favourite")             # normal colour
        b_del.clicked.connect(self._remove_fav)
        row2.addWidget(b_add)
        row2.addWidget(b_del)
        row2.addStretch(1)
        lay.addLayout(row2)

        QShortcut(QKeySequence("Esc"), self, self.reject)
        self.list.setFocus()

    # -- helpers ----------------------------------------------------------
    def favourites(self):
        return self._favs

    def _reload_list(self):
        self.list.clear()
        if self._site_dir:
            it = QListWidgetItem("★   This site's folder        %s" % self._site_dir)
            it.setData(Qt.ItemDataRole.UserRole, self._site_dir)
            self.list.addItem(it)
        for f in self._favs:
            p = f.get("path", "")
            if not p:
                continue
            it = QListWidgetItem("⭐   %s        %s" % (f.get("name") or p, p))
            it.setData(Qt.ItemDataRole.UserRole, p)
            self.list.addItem(it)
        if not self.list.count():
            it = QListWidgetItem("(no favourites yet - use “Add a favourite folder...”)")
            it.setFlags(Qt.ItemFlag.NoItemFlags)
            self.list.addItem(it)
        else:
            self.list.setCurrentRow(0)

    def _selected_dir(self):
        it = self.list.currentItem()
        return it.data(Qt.ItemDataRole.UserRole) if it else None

    def _accept_selected(self):
        d = self._selected_dir()
        if not d:
            self._browse()              # nothing to pick -> go straight to Browse
            return
        self.chosen_dir = d
        self.remember = self.chk.isChecked() or self.remember
        self.accept()

    def _browse(self):
        start = self._selected_dir() or self._site_dir or os.path.expanduser("~")
        d = QFileDialog.getExistingDirectory(self, "Folder to upload from", start)
        if d:
            self.chosen_dir = d
            self.remember = self.chk.isChecked() or self.remember
            self.accept()

    def _add_fav(self):
        d = QFileDialog.getExistingDirectory(
            self, "Add a favourite upload folder",
            self._selected_dir() or os.path.expanduser("~"))
        if not d:
            return
        name, ok = QInputDialog.getText(
            self, "Favourite name", "Short name for this folder:",
            text=os.path.basename(d.rstrip("/\\")) or d)
        if not ok:
            return
        if not any(f.get("path") == d for f in self._favs):
            self._favs.append({"name": (name.strip() or d)[:40], "path": d})
        self._reload_list()

    def _remove_fav(self):
        d = self._selected_dir()
        if not d:
            return
        before = len(self._favs)
        self._favs = [f for f in self._favs if f.get("path") != d]
        if len(self._favs) != before:
            self._reload_list()


# *************** DEL 54 - UPLOAD PICKER WITH RECENT FOLDERS *****************
#  The case: an advert (Tradera, Vinted, BGG) takes 6-7 pictures ONE AT A TIME, so
#  the file dialog opens again and again - and the Windows one always starts in a
#  place the pictures are not, so every picture meant walking up three folders and
#  down two or three again. Two fixes, both automatic:
#   * the picker STARTS in the folder last used on this site (for 3 hours - after
#     that the site's own pinned folder takes over again), so picture 2..7 open
#     right next to picture 1;
#   * the picker is WhyBrowse's own (the Windows one cannot be given extra places)
#     and its left-hand column holds your PINNED folders (= the favourite upload
#     folders), the site's folder, the last UPLOAD_RECENT_MAX folders you picked
#     from, Desktop / Documents / Pictures / Downloads and the drives - fixed
#     shortcuts, like Documents is. Two buttons under the list: "Pin this folder"
#     and "Remove this folder from the list" (takes it off the pins AND off the
#     recent list; it comes back on its own if you pick from it again).
#  Settings -> Uploads can switch back to the Windows picker.
#  ToDo: thumbnails (QFileDialog has none).
UPLOAD_RESUME_SECONDS = 3 * 3600
UPLOAD_RECENT_MAX = 12


def _upload_key(p):
    return os.path.normcase(os.path.normpath(p))


def upload_picker_places(recent, site_dir, favs):
    """Folders for the picker's left-hand column, in this order, no duplicates,
    missing folders left out: pinned (favourites), the site's folder, recent,
    the standard places, the drives."""
    out, seen = [], set()

    def add(p, check=True):
        if not p:
            return
        p = os.path.normpath(p)
        key = os.path.normcase(p)
        if key in seen or (check and not os.path.isdir(p)):
            return
        seen.add(key)
        out.append(p)

    for f in favs or []:
        add(f.get("path") if isinstance(f, dict) else f)
    add(site_dir)
    for p in recent or []:
        add(p)
    SP = QStandardPaths.StandardLocation
    for loc in (SP.DesktopLocation, SP.DocumentsLocation,
                SP.PicturesLocation, SP.DownloadLocation):
        add(QStandardPaths.writableLocation(loc))
    for info in QDir.drives():
        add(info.absoluteFilePath(), check=False)   # DEL 59: no disk touch (a sleeping HDD / lost network drive stalls)
    return out


class _FastIcons(QFileIconProvider):
    """DEL 59: the picker's icon source. The default one asks Windows for a
    shell icon of EVERY file it lists - in a folder with hundreds of pictures
    that is what makes the picker take minutes to open. This one hands out two
    cached icons (folder / file) and never touches the files."""

    def __init__(self):
        super().__init__()
        self._dir = super().icon(QFileIconProvider.IconType.Folder)
        self._file = super().icon(QFileIconProvider.IconType.File)

    def icon(self, arg):
        try:
            if isinstance(arg, QFileIconProvider.IconType):
                return super().icon(arg)
            return self._dir if arg.isDir() else self._file
        except Exception:
            return self._file


def pick_upload_files(parent, kind, title, start, name_filter, recent, site_dir, favs):
    """The upload picker. kind: 'dir' | 'save' | 'multi' | 'one'.
    Returns the chosen paths ([] = cancelled).

    `recent` (list of paths) and `favs` (list of {"name","path"}) are changed IN
    PLACE by the Pin / Remove buttons - the caller saves its settings afterwards,
    whether or not a file was picked."""
    dlg = QFileDialog(parent, title, start)
    dlg.setOption(QFileDialog.Option.DontUseNativeDialog, True)
    dlg.setViewMode(QFileDialog.ViewMode.Detail)
    try:
        dlg.setIconProvider(_FastIcons())           # DEL 59: no per-file shell icons
    except Exception:
        pass
    try:
        dlg.setOption(QFileDialog.Option.DontResolveSymlinks, True)
    except Exception:
        pass

    def refresh():
        dlg.setSidebarUrls([QUrl.fromLocalFile(p) for p in
                            upload_picker_places(recent, site_dir, favs)])
        cur = _upload_key(dlg.directory().absolutePath())
        pinned = any(_upload_key(f.get("path", "")) == cur for f in favs if f.get("path"))
        listed = pinned or any(_upload_key(r) == cur for r in recent)
        b_pin.setEnabled(not pinned)
        b_del.setEnabled(listed)

    def pin():
        cur = os.path.normpath(dlg.directory().absolutePath())
        favs.append({"name": os.path.basename(cur.rstrip("\\/")) or cur, "path": cur})
        refresh()

    def unpin():
        cur = _upload_key(dlg.directory().absolutePath())
        favs[:] = [f for f in favs if _upload_key(f.get("path", "")) != cur]
        recent[:] = [r for r in recent if _upload_key(r) != cur]
        refresh()

    row = QWidget(dlg)
    rl = QHBoxLayout(row)
    rl.setContentsMargins(0, 0, 0, 0)
    b_pin = QPushButton("📌  Pin this folder")
    b_del = QPushButton("✖  Remove this folder from the list")
    b_pin.clicked.connect(pin)
    b_del.clicked.connect(unpin)
    rl.addWidget(b_pin)
    rl.addWidget(b_del)
    rl.addStretch(1)
    try:
        lay = dlg.layout()
        lay.addWidget(row, lay.rowCount(), 0, 1, max(1, lay.columnCount()))
    except Exception:
        row.hide()                          # layout changed in a new Qt: buttons optional
    dlg.directoryEntered.connect(lambda _d: refresh())
    refresh()
    if kind == "dir":
        dlg.setFileMode(QFileDialog.FileMode.Directory)
        dlg.setOption(QFileDialog.Option.ShowDirsOnly, True)
    else:
        if kind == "save":
            dlg.setAcceptMode(QFileDialog.AcceptMode.AcceptSave)
            dlg.setFileMode(QFileDialog.FileMode.AnyFile)
        elif kind == "multi":
            dlg.setFileMode(QFileDialog.FileMode.ExistingFiles)
        else:
            dlg.setFileMode(QFileDialog.FileMode.ExistingFile)
        dlg.setNameFilter(name_filter)
    dlg.resize(1100, 640)
    try:                                    # folder names need room in the left column
        sp = dlg.findChild(QSplitter, "splitter")
        if sp is not None:
            sp.setSizes([280, 820])
    except Exception:
        pass
    if dlg.exec() != QDialog.DialogCode.Accepted:
        return []
    return list(dlg.selectedFiles())


# ============================================================================
#  DEL 12D2 - BOOKMARK DUPLICATE DIALOG
# ----------------------------------------------------------------------------
#  Shown when the user tries to bookmark a URL that already exists somewhere
#  in the bookmark tree and the duplicate_mode setting is "ask".
#  Returns one of three string choices: "duplicate", "move", or "cancel".
# ============================================================================
class _BookmarkDuplicateDialog(QDialog):
    """Modal dialog asking the user what to do about a duplicate bookmark."""

    def __init__(self, parent, title, url, existing_location):
        super().__init__(parent)
        self._choice = "cancel"
        self.setWindowTitle("Bookmark already saved")
        self.setModal(True)
        self.setMinimumWidth(420)
        self.setStyleSheet(dialog_qss())
        apply_window_icon(self)

        lay = QVBoxLayout(self)
        lay.setSpacing(10)

        # ---- Info label ----
        lbl_info = QLabel(
            "<b>This page is already bookmarked.</b><br><br>"
            "Found in: <i>%s</i><br><br>"
            "What would you like to do?" % (existing_location[:80] or url[:80])
        )
        lbl_info.setWordWrap(True)
        lbl_info.setStyleSheet("color:%s;" % C_BAR_FG)
        lay.addWidget(lbl_info)

        lay.addSpacing(4)

        # ---- Buttons ----
        def _btn(label, tip, slot, accent=False):
            b = QPushButton(label)
            b.setToolTip(tip)
            if accent:
                b.setStyleSheet(
                    "QPushButton{background:%s; color:%s; border:none; padding:8px 16px; "
                    "border-radius:6px; font-weight:bold;}"
                    "QPushButton:hover{background:%s;}" % (C_ACCENT, C_ACCENT_FG, C_ACCENT_HOV))
            else:
                b.setStyleSheet(
                    "QPushButton{background:%s; color:%s; border:none; padding:8px 16px; "
                    "border-radius:6px;}"
                    "QPushButton:hover{background:%s;}" % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
            b.clicked.connect(slot)
            return b

        row = QHBoxLayout()
        row.setSpacing(8)
        row.addWidget(_btn(
            "Add duplicate to bar",
            "Add another copy of this bookmark to the bookmarks bar",
            self._choose_duplicate,
            accent=True,
        ))
        row.addWidget(_btn(
            "Move existing to bar",
            "Remove the existing bookmark and re-add it at the top of the bar",
            self._choose_move,
        ))
        row.addWidget(_btn(
            "Cancel",
            "Do not add a bookmark",
            self.reject,
        ))
        lay.addLayout(row)

        # ---- Small hint about the setting ----
        lbl_hint = QLabel(
            "Tip: You can change this behaviour in Settings → Bookmarks "
            "(allow duplicates silently, or always deny)."
        )
        lbl_hint.setWordWrap(True)
        lbl_hint.setStyleSheet("color:%s; font-size:8pt;" % C_STATUS_FG)
        lay.addWidget(lbl_hint)

    def _choose_duplicate(self):
        self._choice = "duplicate"
        self.accept()

    def _choose_move(self):
        self._choice = "move"
        self.accept()

    def exec_choice(self):
        """Run the dialog and return 'duplicate', 'move', or 'cancel'."""
        self.exec()
        return self._choice


# ============================================================================
#  DEL 12E - BOOKMARK DROPDOWN MENU  (folder items: new-tab + right-click)
# ----------------------------------------------------------------------------
#  A QMenu whose link items (QActions carrying their URL in .data()) support:
#    - left click     -> open in the current tab  (normal triggered signal)
#    - middle / Ctrl  -> open in a new background tab
#    - right click    -> a small Open / Open-in-new-tab context menu
#  Folder submenus (added via addMenu, no .data()) behave as normal submenus.
# ============================================================================
class BookmarkMenu(QMenu):
    def __init__(self, window, parent=None):
        super().__init__(parent or window)
        self.win = window

    def mouseReleaseEvent(self, e):
        act = self.actionAt(e.pos())
        url = act.data() if act else None
        # DEL 55: _folder_menu tags every real bookmark/folder entry with its
        # index in self.nodes, so a right-click knows the exact node (also for
        # folders, and for two bookmarks that share one address).
        has_idx = bool(act) and act.property("wb_idx") is not None
        if url or has_idx:
            btn, mods = e.button(), e.modifiers()
            new_tab = (btn == Qt.MouseButton.MiddleButton or
                       (btn == Qt.MouseButton.LeftButton and
                        mods & Qt.KeyboardModifier.ControlModifier))
            if url and new_tab:
                self.win.add_tab(url, switch=False, adjacent=True)
                self.close()
                return
            if btn == Qt.MouseButton.RightButton:
                self._ctx(act, e.globalPosition().toPoint())
                return
        super().mouseReleaseEvent(e)

    def _node_of(self, act):
        nodes = getattr(self, "nodes", None)
        idx = act.property("wb_idx") if act else None
        if nodes is not None and isinstance(idx, int) and 0 <= idx < len(nodes):
            return nodes[idx]
        return None

    def _ctx(self, act, gpos):
        url = act.data()
        node = self._node_of(act)
        m = QMenu(self)
        m.setStyleSheet(self.styleSheet())
        if url:
            m.addAction("Open", lambda: (self._go(url), self.win._open_in_current(url)))
            m.addAction("Open in new tab", lambda: (self._go(url), self.win.add_tab(url, switch=True)))
            m.addAction("Open in new background tab",
                        lambda: self.win.add_tab(url, switch=False, adjacent=True))
            m.addSeparator()
        # DEL 55: move targets first (only while a move is pending) ...
        # (a node that is not in THIS profile's own tree - Tookmarks, the
        #  generated Favourites - is read-only: no rename/move/delete)
        mine = node is not None and self.win._bm_parent_list(node) is not None
        if mine and self.win._bm_move_target_items(m, node, self._go):
            m.addSeparator()
        if mine:
            m.addAction("✎  Rename...", lambda: (self._go(), self.win._bm_rename(node)))
            self.win._bm_move_start_item(m, node, self._go)
            if url:
                m.addAction("🗑  Delete", lambda: (self._go(), self.win._bm_delete(node)))
        elif node is None and url:
            m.addAction("✎  Rename...", lambda: (self._go(), self.win._bm_rename_url(url)))
            m.addAction("🗑  Delete", lambda: (self._go(), self.win._bm_delete_url(url)))
        m.exec(gpos)

    def _go(self, *_a):
        # Close the whole dropdown chain after a context-menu choice: this
        # menu AND the parent menus it hangs from (they are all popups).
        self.close()
        try:
            for _ in range(10):
                w = QApplication.activePopupWidget()
                if w is None:
                    break
                w.close()
        except Exception:
            pass


# ============================================================================
#  DEL 12G - VERTICAL TAB BAR  (left-side tabs with HORIZONTAL text, sidebar)
# ----------------------------------------------------------------------------
#  Qt's native side-tabs draw the label rotated 90° (sideways). This bar, when
#  the tabs are on the left, draws each tab as a fixed-size horizontal rectangle
#  with normal horizontal text + the favicon/colour-dot in front. On Top it
#  behaves like a normal tab bar. Middle-click closes a tab (no 'x' is shown
#  in vertical mode).
# ============================================================================
class VerticalTabBar(QTabBar):
    RESIZE_MARGIN = 6                                # px hot-zone at the right edge

    def __init__(self, window):
        super().__init__()
        self._win = window
        self._fixed_w = 150
        self._fixed_h = 28
        self._resizing = False
        self.setMouseTracking(True)                  # so we can show the resize cursor
        self._hover_idx = -1
        self._ql_timer = QTimer(self)                # hover a tab -> its quick links
        self._ql_timer.setSingleShot(True)
        self._ql_timer.setInterval(600)
        self._ql_timer.timeout.connect(self._fire_quicklinks)

    def _fire_quicklinks(self):
        if self._hover_idx >= 0:
            try:
                self._win._hover_tab_quicklinks(self._hover_idx)
            except Exception:
                pass

    def set_fixed_size(self, w, h):
        self._fixed_w, self._fixed_h = int(w), int(h)
        # Tell Qt's layout engine the new required width by constraining the
        # tab bar itself.  updateGeometry() alone is insufficient because
        # QTabWidget caches the bar's size on its own layout pass.
        if self._vertical():
            self.setMinimumWidth(w)
            self.setMaximumWidth(w)
        self.updateGeometry()
        # Also nudge the parent QTabWidget so it recalculates immediately.
        p = self.parent()
        if p is not None:
            p.updateGeometry()

    def _vertical(self):
        return self.shape() in (QTabBar.Shape.RoundedWest, QTabBar.Shape.RoundedEast,
                                QTabBar.Shape.TriangularWest, QTabBar.Shape.TriangularEast)

    def _on_edge(self, x):
        return self._vertical() and abs(x - self.width()) <= self.RESIZE_MARGIN

    def tabSizeHint(self, index):
        if self._vertical():
            return QSize(self._fixed_w, self._fixed_h)
        return super().tabSizeHint(index)

    def _close_zone(self, i, pos):
        """True if pos is over the ✕ drawn at the right of vertical tab i."""
        if not self._vertical():
            return False
        r = self.tabRect(i)
        return (r.right() - 26) <= pos.x() <= (r.right() - 8)

    def mousePressEvent(self, e):
        x = int(e.position().x())
        if e.button() == Qt.MouseButton.LeftButton and self._on_edge(x):
            self._resizing = True                    # start dragging the column wider/narrower
            return
        if e.button() == Qt.MouseButton.LeftButton and self._vertical():
            i = self.tabAt(e.position().toPoint())
            if i >= 0 and self._close_zone(i, e.position().toPoint()):
                self._win.close_tab(i)               # clicked the ✕
                return
        if e.button() == Qt.MouseButton.MiddleButton:
            i = self.tabAt(e.position().toPoint())
            if i >= 0:
                self._win.close_tab(i)
                return
        super().mousePressEvent(e)

    def mouseMoveEvent(self, e):
        if self._resizing:
            self.set_fixed_size(max(70, min(520, int(e.position().x()))), self._fixed_h)
            return
        if self._vertical():
            self.setCursor(Qt.CursorShape.SizeHorCursor if self._on_edge(int(e.position().x()))
                           else Qt.CursorShape.ArrowCursor)
        # Track which tab we're hovering to offer its quick links after a pause.
        i = self.tabAt(e.position().toPoint())
        if i != self._hover_idx:
            self._hover_idx = i
            if i >= 0:
                self._ql_timer.start()
            else:
                self._ql_timer.stop()
        super().mouseMoveEvent(e)

    def mouseReleaseEvent(self, e):
        if self._resizing:
            self._resizing = False
            self._win._save_tab_width(self._fixed_w)   # remember the dragged width
            return
        super().mouseReleaseEvent(e)

    def paintEvent(self, event):
        if not self._vertical():
            return super().paintEvent(event)
        try:
            p = QStylePainter(self)
            opt = QStyleOptionTab()
            cur = self.currentIndex()
            pc = self._win._pinned_count()          # how many pinned tabs at front
            for i in range(self.count()):
                self.initStyleOption(opt, i)
                opt.text = ""                       # we draw text ourselves (horizontal)
                opt.icon = QIcon()
                p.drawControl(QStyle.ControlElement.CE_TabBarTabShape, opt)
                r = self.tabRect(i)
                x = r.left() + 8
                view = self._win.tabs.widget(i)
                # Plain favicon first...
                fav = getattr(view, "_favicon", None) if view else None
                if fav is not None and not fav.isNull():
                    p.drawPixmap(x, r.center().y() - 8, fav.pixmap(16, 16))
                    x += 20
                elif not self.tabIcon(i).isNull():
                    p.drawPixmap(x, r.center().y() - 8, self.tabIcon(i).pixmap(16, 16))
                    x += 20
                # ...then the colour dot BETWEEN the icon and the text.
                ckey = self._win._combo_key(view) if view else ""
                if ckey:
                    color = self._win.COMBO_COLORS.get(ckey, "#9aa6bf")
                    p.setBrush(QColor(color))
                    p.setPen(Qt.PenStyle.NoPen)
                    p.drawEllipse(x, r.center().y() - 4, 9, 9)
                    x += 13
                selected = (i == cur)
                p.setPen(QColor(C_ACCENT_FG if selected else C_TAB_FG))
                f = self.font()
                f.setBold(selected)
                p.setFont(f)
                tr = QRect(x, r.top(), max(10, r.right() - x - 28), r.height())
                txt = p.fontMetrics().elidedText(
                    self.tabText(i), Qt.TextElideMode.ElideRight, tr.width())
                p.drawText(tr, Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft, txt)
                # Close ✕ at the right edge. Its COLOUR encodes tab state (so we
                # don't spend tab width on extra glyphs):
                #   • LOCKED  -> red ✕  (links open in new tabs / can't navigate away)
                #   • PINNED  -> dimmed ✕ (protected from closing)
                #   • normal  -> default colour
                pinned = bool(getattr(view, "_pinned", False)) if view else False
                locked = (self._win._lock(view) > 0) if view else False
                if locked:
                    xcol = "#ef4444"             # red = locked
                elif pinned:
                    xcol = "#5a6273"             # dim = pinned/protected
                else:
                    xcol = C_TAB_FG
                p.setPen(QColor(xcol))
                f.setBold(False)
                p.setFont(f)
                p.drawText(QRect(r.right() - 26, r.top(), 18, r.height()),
                           Qt.AlignmentFlag.AlignCenter, "✕")
                # Divider line just below the LAST pinned tab, so the pinned
                # group is visually separated from the rest of the strip.
                if pc and i == pc - 1 and pc < self.count():
                    p.setPen(QColor(C_ACCENT))
                    y = r.bottom()
                    p.drawLine(r.left() + 4, y, r.right() - 4, y)
        except Exception:
            super().paintEvent(event)


# ============================================================================
#  DEL 12H - ON-SCREEN KEYBOARD  (anti-keylogger virtual keyboard)
# ----------------------------------------------------------------------------
#  Purpose: let you type a username / password with the MOUSE instead of the
#  physical keys, so a hardware/software keylogger that hooks the keyboard
#  captures NOTHING. Every key is inserted straight into the focused web field
#  via JavaScript (BrowserWindow._osk_type), never as a real OS keystroke.
#
#  Languages: Swedish + English are built in. More layouts are "add-ons":
#  drop a small .json file into  Helpfiles/WhyBrowse/keyboard_layouts/  and it
#  shows up in the language dropdown (see the README written there on first run).
#  A layout file looks like:
#      {"name": "Norwegian",
#       "rows": [ [["1","!"],["2","\""], ...],          # each key = [normal, shift]
#                 [["q","Q"], ...], ... ]}
# ============================================================================
def _kb_letters(s):
    """Helper: turn a string of letters into [lower, UPPER] key pairs."""
    return [[c, c.upper()] for c in s]


# Built-in layouts (always present, even if the add-ons folder is empty).
BUILTIN_KB_LAYOUTS = [
    {"name": "English (US)",
     "rows": [
         [["1", "!"], ["2", "@"], ["3", "#"], ["4", "$"], ["5", "%"],
          ["6", "^"], ["7", "&"], ["8", "*"], ["9", "("], ["0", ")"],
          ["-", "_"], ["=", "+"]],
         _kb_letters("qwertyuiop") + [["[", "{"], ["]", "}"]],
         _kb_letters("asdfghjkl") + [[";", ":"], ["'", "\""]],
         _kb_letters("zxcvbnm") + [[",", "<"], [".", ">"], ["/", "?"]],
     ]},
    {"name": "Swedish",
     "rows": [
         [["1", "!"], ["2", "\""], ["3", "#"], ["4", "¤"], ["5", "%"],
          ["6", "&"], ["7", "/"], ["8", "("], ["9", ")"], ["0", "="],
          ["+", "?"]],
         _kb_letters("qwertyuiop") + [["å", "Å"]],
         _kb_letters("asdfghjkl") + [["ö", "Ö"], ["ä", "Ä"]],
         _kb_letters("zxcvbnm") + [[",", ";"], [".", ":"], ["-", "_"]],
     ]},
]

# A small fixed symbol row added under every layout, so the characters you
# most need for logins (notably @ and . for e-mail) are always one click away,
# even on layouts where they normally hide behind AltGr.
KB_SYMBOL_ROW = [["@", "@"], [".", "."], ["_", "_"], ["-", "-"], ["/", "/"],
                 [":", ":"], ["?", "?"], ["!", "!"], ["+", "+"], ["#", "#"]]

KB_README = """On-screen keyboard layouts
==========================

WhyBrowse has a built-in virtual keyboard (toolbar key icon, or Ctrl+Shift+K).
Its main job is anti-keylogging: clicking the keys with the MOUSE types your
login/password straight into the web field, so a keylogger captures nothing.

Swedish and English are built in. To ADD a language, drop a .json file in THIS
folder. It appears in the keyboard's language dropdown after you click
"Reload layouts" (or restart). Each key is a pair: [normal, shifted].

Example (save as e.g. "Norwegian.json"):

{
  "name": "Norwegian",
  "rows": [
    [["1","!"],["2","\\""],["3","#"],["4","$"],["5","%"],
     ["6","&"],["7","/"],["8","("],["9",")"],["0","="]],
    [["q","Q"],["w","W"],["e","E"],["r","R"],["t","T"],
     ["y","Y"],["u","U"],["i","I"],["o","O"],["p","P"],["å","Å"]],
    [["a","A"],["s","S"],["d","D"],["f","F"],["g","G"],
     ["h","H"],["j","J"],["k","K"],["l","L"],["ø","Ø"],["æ","Æ"]],
    [["z","Z"],["x","X"],["c","C"],["v","V"],["b","B"],
     ["n","N"],["m","M"],[",",";"],[".",":"],["-","_"]]
  ]
}
"""


def load_keyboard_layouts():
    """Return the built-in layouts plus any valid .json add-on layouts found in
    KBD_LAYOUTS_DIR. Never raises; a broken file is simply skipped."""
    layouts = [dict(l) for l in BUILTIN_KB_LAYOUTS]
    # Write a README once so the user knows the format.
    try:
        readme = os.path.join(KBD_LAYOUTS_DIR, "README.txt")
        if not os.path.isfile(readme):
            with open(readme, "w", encoding="utf-8") as f:
                f.write(KB_README)
    except Exception:
        pass
    try:
        for path in sorted(glob.glob(os.path.join(KBD_LAYOUTS_DIR, "*.json"))):
            try:
                with open(path, "r", encoding="utf-8") as f:
                    data = json.load(f)
                rows = data.get("rows")
                name = data.get("name") or os.path.splitext(os.path.basename(path))[0]
                if not isinstance(rows, list) or not rows:
                    continue
                # Normalise: every key must be a [normal, shift] pair of strings.
                clean_rows = []
                for row in rows:
                    if not isinstance(row, list):
                        continue
                    clean = []
                    for k in row:
                        if isinstance(k, str):
                            clean.append([k, k.upper()])
                        elif isinstance(k, list) and k:
                            n = str(k[0])
                            s = str(k[1]) if len(k) > 1 else n.upper()
                            clean.append([n, s])
                    if clean:
                        clean_rows.append(clean)
                if clean_rows:
                    layouts.append({"name": str(name), "rows": clean_rows})
            except Exception as e:
                log_line("keyboard layout load failed (%s): %s" % (path, e))
    except Exception:
        pass
    return layouts


class OnScreenKeyboard(QWidget):
    """A clickable, non-focus-stealing keyboard. It is a Tool window that does
    NOT take focus from the page (WA_ShowWithoutActivating + DoesNotAcceptFocus
    + every button is NoFocus), so the web field you clicked in stays the active
    element and the typed characters land there."""

    def __init__(self, win):
        super().__init__(None)
        self.win = win
        self.setWindowTitle("On-Screen Keyboard — type with the mouse (anti-keylogger)")
        self.setWindowFlags(Qt.WindowType.Tool
                            | Qt.WindowType.WindowStaysOnTopHint
                            | Qt.WindowType.WindowDoesNotAcceptFocus)
        self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating, True)
        try:
            apply_window_icon(self)
        except Exception:
            pass

        self.layouts = win._kb_layouts
        self._shift = False          # one-shot shift (auto-clears after a key)
        self._caps = False           # sticky caps lock (letters only)
        self._key_rows = []          # [(button, [normal, shift]), ...] for relabel
        self._lang_index = 0

        # Pick the remembered language if it still exists.
        want = win.settings.get("osk_language", "Swedish")
        for i, l in enumerate(self.layouts):
            if l.get("name") == want:
                self._lang_index = i
                break

        self._build()
        self._apply_theme()
        self._relabel()

    # ---- build the widget tree -------------------------------------------
    def _build(self):
        outer = QVBoxLayout(self)
        outer.setContentsMargins(8, 8, 8, 8)
        outer.setSpacing(6)

        # Top bar: language picker + reload + caps indicator.
        top = QHBoxLayout()
        top.setSpacing(6)
        lbl = QLabel("Language:")
        self.combo = QComboBox()
        self.combo.setFocusPolicy(Qt.FocusPolicy.NoFocus)
        for l in self.layouts:
            self.combo.addItem(l.get("name", "?"))
        self.combo.setCurrentIndex(self._lang_index)
        self.combo.currentIndexChanged.connect(self._change_lang)
        btn_reload = QPushButton("↻ Reload layouts")
        btn_reload.setFocusPolicy(Qt.FocusPolicy.NoFocus)
        btn_reload.setToolTip("Re-scan the keyboard_layouts add-ons folder")
        btn_reload.clicked.connect(self._reload_layouts)
        self.caps_lbl = QLabel("")
        self.caps_lbl.setStyleSheet("color:%s;font-weight:bold;" % C_ACCENT)
        top.addWidget(lbl)
        top.addWidget(self.combo, 1)
        top.addWidget(self.caps_lbl)
        top.addWidget(btn_reload)
        outer.addLayout(top)

        # The key grid (rebuilt whenever the language changes).
        self.grid_host = QWidget()
        self.grid = QVBoxLayout(self.grid_host)
        self.grid.setContentsMargins(0, 0, 0, 0)
        self.grid.setSpacing(4)
        outer.addWidget(self.grid_host)
        self._build_keys()

    def _mk_key(self, label, slot, width=38, wide=False):
        b = QPushButton(label)
        b.setFocusPolicy(Qt.FocusPolicy.NoFocus)     # never steal focus from the page
        b.setCursor(Qt.CursorShape.PointingHandCursor)
        b.setFixedHeight(36)
        if wide:
            b.setMinimumWidth(width)
            b.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
        else:
            b.setFixedWidth(width)
        b.clicked.connect(slot)
        return b

    def _clear_grid(self):
        while self.grid.count():
            item = self.grid.takeAt(0)
            w = item.widget()
            if w:
                w.deleteLater()
            elif item.layout():
                lay = item.layout()
                while lay.count():
                    it2 = lay.takeAt(0)
                    if it2.widget():
                        it2.widget().deleteLater()
        self._key_rows = []

    def _build_keys(self):
        self._clear_grid()
        layout = self.layouts[self._lang_index]
        for row in layout.get("rows", []):
            hb = QHBoxLayout()
            hb.setSpacing(4)
            for pair in row:
                b = self._mk_key(pair[0], lambda _=False, p=pair: self._press(p))
                self._key_rows.append((b, pair))
                hb.addWidget(b)
            hb.addStretch(1)
            self.grid.addLayout(hb)

        # Shared symbol row (so @ and . are always reachable for e-mail logins).
        hb = QHBoxLayout()
        hb.setSpacing(4)
        for pair in KB_SYMBOL_ROW:
            b = self._mk_key(pair[0], lambda _=False, p=pair: self._press(p))
            self._key_rows.append((b, pair))
            hb.addWidget(b)
        hb.addStretch(1)
        self.grid.addLayout(hb)

        # Action row: Shift / Caps / Space / Backspace / Clear / Enter / Hide.
        hb = QHBoxLayout()
        hb.setSpacing(4)
        self.btn_shift = self._mk_key("⇧ Shift", lambda: self._toggle_shift(), width=80)
        self.btn_caps = self._mk_key("⇪ Caps", lambda: self._toggle_caps(), width=70)
        space = self._mk_key("Space", lambda: self._press([" ", " "]), width=180, wide=True)
        bksp = self._mk_key("⌫ Back", lambda: self.win._osk_backspace(), width=80)
        clr = self._mk_key("Clear", lambda: self.win._osk_clear_field(), width=70)
        enter = self._mk_key("⏎ Enter", lambda: self.win._osk_enter(), width=90)
        hide = self._mk_key("✕ Hide", lambda: self.hide(), width=70)
        for b in (self.btn_shift, self.btn_caps, space, bksp, clr, enter, hide):
            hb.addWidget(b, 1 if b is space else 0)
        self.grid.addLayout(hb)
        self._sync_modifier_buttons()
        self._relabel()

    # ---- behaviour --------------------------------------------------------
    def _is_letter(self, pair):
        return len(pair[0]) == 1 and pair[0].isalpha()

    def _effective(self, pair):
        """The character to send for this key given shift/caps state."""
        if self._is_letter(pair):
            up = self._shift ^ self._caps
            return pair[1] if up else pair[0]
        return pair[1] if self._shift else pair[0]

    def _press(self, pair):
        ch = self._effective(pair)
        self.win._osk_type(ch)
        if self._shift:                      # one-shot shift clears after a key
            self._shift = False
            self._sync_modifier_buttons()
            self._relabel()

    def _toggle_shift(self):
        self._shift = not self._shift
        self._sync_modifier_buttons()
        self._relabel()

    def _toggle_caps(self):
        self._caps = not self._caps
        self._sync_modifier_buttons()
        self._relabel()

    def _sync_modifier_buttons(self):
        if hasattr(self, "btn_shift"):
            self.btn_shift.setStyleSheet(self._key_css(active=self._shift))
            self.btn_caps.setStyleSheet(self._key_css(active=self._caps))
        self.caps_lbl.setText("CAPS" if self._caps else "")

    def _relabel(self):
        """Show the character each key will actually type right now."""
        for b, pair in self._key_rows:
            try:
                b.setText(self._effective(pair))
            except Exception:
                pass

    def _change_lang(self, idx):
        if 0 <= idx < len(self.layouts):
            self._lang_index = idx
            self.win.settings["osk_language"] = self.layouts[idx].get("name", "")
            save_json(SETTINGS_FILE, self.win.settings)
            self._build_keys()

    def _reload_layouts(self):
        cur = self.layouts[self._lang_index].get("name") if self.layouts else None
        self.win._kb_layouts = load_keyboard_layouts()
        self.layouts = self.win._kb_layouts
        self.combo.blockSignals(True)
        self.combo.clear()
        for l in self.layouts:
            self.combo.addItem(l.get("name", "?"))
        self._lang_index = 0
        for i, l in enumerate(self.layouts):
            if l.get("name") == cur:
                self._lang_index = i
                break
        self.combo.setCurrentIndex(self._lang_index)
        self.combo.blockSignals(False)
        self._build_keys()
        show_toast(self.win, "Keyboard layouts reloaded (%d)" % len(self.layouts))

    # ---- theme / styling --------------------------------------------------
    def _key_css(self, active=False):
        if active:
            return ("QPushButton{background:%s;color:%s;border:none;border-radius:6px;"
                    "font-size:14px;}QPushButton:hover{background:%s;}"
                    % (C_ACCENT, C_ACCENT_FG, C_ACCENT_HOV))
        return ("QPushButton{background:%s;color:%s;border:1px solid %s;border-radius:6px;"
                "font-size:14px;}QPushButton:hover{background:%s;}"
                % (C_BTN_BG, C_BTN_FG, C_BORDER, C_BTN_BG_HOV))

    def _apply_theme(self):
        self.setStyleSheet(
            "QWidget{background:%s;color:%s;}"
            "QComboBox{background:%s;color:%s;border:1px solid %s;border-radius:6px;padding:4px;}"
            "QComboBox QAbstractItemView{background:%s;color:%s;"
            "selection-background-color:%s;selection-color:%s;}"
            % (C_BAR_BG, C_BAR_FG, C_ADDR_BG, C_ADDR_FG, C_BORDER,
               C_ADDR_BG, C_ADDR_FG, C_ACCENT, C_ACCENT_FG))
        css = self._key_css()
        for b, _pair in self._key_rows:
            b.setStyleSheet(css)
        self._sync_modifier_buttons()

    # ---- window plumbing --------------------------------------------------
    def _restore_pos(self):
        pos = self.win.settings.get("osk_pos")
        if isinstance(pos, list) and len(pos) == 2:
            self.move(int(pos[0]), int(pos[1]))
        else:
            # Default: centred near the bottom of the main window.
            g = self.win.geometry()
            self.adjustSize()
            self.move(g.x() + (g.width() - self.width()) // 2,
                      g.y() + g.height() - self.height() - 60)

    def _save_pos(self):
        self.win.settings["osk_pos"] = [self.x(), self.y()]
        save_json(SETTINGS_FILE, self.win.settings)

    def keyPressEvent(self, e):
        if e.key() == Qt.Key.Key_Escape:
            self.hide()
        else:
            super().keyPressEvent(e)

    def hideEvent(self, e):
        self._save_pos()
        super().hideEvent(e)

    def closeEvent(self, e):
        self._save_pos()
        super().closeEvent(e)


# ============================================================================
#  DEL 12I - MEDIA DOWNLOADER  (download video / audio via yt-dlp)
# ----------------------------------------------------------------------------
#  Saves video/music from YouTube, SoundCloud, Vimeo, and ~1800 other sites by
#  shelling out to the well-known tool **yt-dlp** (the maintained successor to
#  youtube-dl). yt-dlp also finds streams that are "hidden" inside a page (it
#  parses the page and the embedded players), and can use your Firefox cookies
#  for members-only / age-gated clips.
#
#  yt-dlp / ffmpeg lookup order: Helpfiles/WhyBrowse/tools  →  next to the .py/.exe
#  →  Helpfiles/1---Movie (the shared movie-tools folder)  →  the system PATH.
#  If yt-dlp is missing, the dialog has a one-click "Get yt-dlp" button that
#  downloads the official single-file yt-dlp.exe into the tools folder.
#
#  HONEST LIMIT: truly DRM-protected streams (Netflix, Disney+, Spotify, etc.)
#  are encrypted and CANNOT be downloaded — no tool can, and this won't either.
# ============================================================================
MOVIE_TOOLS_DIR = os.path.join(HELP_DIR, "1---Movie")          # shared movie helpers
YTDLP_DOWNLOAD_URL = "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp.exe"

# Hidden-console flag for child processes on Windows (no flashing black window).
_NO_WINDOW = 0x08000000 if os.name == "nt" else 0


def _find_exe(names, extra_dirs):
    """Return the first existing path to one of `names` (with/without .exe) in
    `extra_dirs`, else whatever is on PATH, else None."""
    cands = []
    for d in extra_dirs:
        for n in names:
            cands.append(os.path.join(d, n))
    for c in cands:
        if os.path.isfile(c):
            return c
    for n in names:
        w = shutil.which(n)
        if w:
            return w
    return None


def _real_python():
    """A REAL python.exe, or None.  NEVER sys.executable in a build.

    In a PyInstaller build sys.executable is WhyBrowse.exe, so handing it to
    subprocess with  -m yt_dlp  starts another BROWSER instead of yt-dlp -
    and find_spec() below finds yt_dlp inside the bundle, so in a build that
    branch was always the one taken: every download opened a new window
    instead of downloading anything.  (PyManager had the same shape and
    fork-bombed the machine on 2026-09-04.)
    """
    if not getattr(sys, "frozen", False):
        return sys.executable
    me = os.path.basename(os.path.abspath(sys.executable)).lower()

    def _usable(c):
        # %LOCALAPPDATA%\Microsoft\WindowsApps\python.exe is a ZERO-BYTE App
        # Execution Alias, not an interpreter - and which() finds it first on
        # a machine where the Store stub is on PATH.
        try:
            return (bool(c) and os.path.isfile(c) and os.path.getsize(c) > 0
                    and os.path.basename(c).lower() != me)
        except OSError:
            return False

    for cand in (shutil.which("python"), shutil.which("python3")):
        if _usable(cand):
            return cand
    base = os.path.join(os.environ.get("LOCALAPPDATA", ""), "Programs", "Python")
    try:
        for d in sorted(os.listdir(base), reverse=True):
            p = os.path.join(base, d, "python.exe")
            if _usable(p):
                return p
    except OSError:
        pass
    return None


def find_ytdlp():
    """Locate yt-dlp. Returns a command-prefix LIST ([exe] or [python,-m,yt_dlp])
    or None if it is not available anywhere."""
    exe = _find_exe(["yt-dlp.exe", "yt-dlp"],
                    [MEDIA_TOOLS_DIR, BASE_DIR, MOVIE_TOOLS_DIR])
    if exe:
        return [exe]
    # Fall back to a pip-installed module if present - but only with a REAL
    # interpreter.  None here is the right answer in a build: the download
    # dialog then offers its own one-click "Get yt-dlp" button.
    try:
        import importlib.util
        py = _real_python()
        if py and importlib.util.find_spec("yt_dlp") is not None:
            return [py, "-m", "yt_dlp"]
    except Exception:
        pass
    return None


def find_ffmpeg_dir():
    """Directory that contains ffmpeg(.exe), for yt-dlp's --ffmpeg-location, or
    None. ffmpeg is needed to MERGE best-video+best-audio and to make MP3."""
    exe = _find_exe(["ffmpeg.exe", "ffmpeg"],
                    [MEDIA_TOOLS_DIR, BASE_DIR, MOVIE_TOOLS_DIR])
    return os.path.dirname(exe) if exe else None


class MediaWorker(QObject):
    """Runs a yt-dlp command in a background thread, streaming its output to the
    GUI line by line (queued signal = thread-safe).  Both signals carry the job
    they belong to, so ONE queue object can listen to any number of workers."""
    line = pyqtSignal(object, str)      # job, one line of output
    done = pyqtSignal(object, int)      # job, process return code (-1 on failure)

    def __init__(self, cmd, job=None):
        super().__init__()
        self.cmd = cmd
        self.job = job
        self._proc = None
        self._stop = False

    def start(self):
        threading.Thread(target=self._run, daemon=True).start()

    def _run(self):
        try:
            self._proc = subprocess.Popen(
                self.cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                text=True, encoding="utf-8", errors="replace", bufsize=1,
                creationflags=_NO_WINDOW)
            if self._stop:                  # Stop was pressed before the process existed
                self._kill()
            for line in self._proc.stdout:
                if self._stop:
                    break
                self.line.emit(self.job, line.rstrip("\r\n"))
            self._proc.wait()
            self.done.emit(self.job, self._proc.returncode if self._proc else -1)
        except FileNotFoundError as e:
            self.line.emit(self.job, "ERROR: could not start the tool: %s" % e)
            self.done.emit(self.job, -1)
        except Exception as e:
            self.line.emit(self.job, "ERROR: %s" % e)
            self.done.emit(self.job, -1)

    def _kill(self):
        """Kill yt-dlp AND what it started.  The single-file yt-dlp.exe is a
        bootloader that runs a child, and merging/MP3 runs ffmpeg - terminate()
        on the parent alone leaves those running (and the file locked)."""
        p = self._proc
        try:
            if p and p.poll() is None:
                if os.name == "nt":
                    tk = os.path.join(os.environ.get("SystemRoot", r"C:\Windows"),
                                      "System32", "taskkill.exe")
                    subprocess.run([tk, "/PID", str(p.pid), "/T", "/F"],
                                   creationflags=_NO_WINDOW, capture_output=True,
                                   timeout=10)
                else:
                    p.terminate()
        except Exception:
            try:
                p.terminate()
            except Exception:
                pass

    def stop(self):
        self._stop = True
        self._kill()


class MediaJob:
    """One yt-dlp run in the queue: a download, or a 'list formats' look-up."""
    _counter = 0

    def __init__(self, kind, url, cmd, what, dest=""):
        MediaJob._counter += 1
        self.id = MediaJob._counter
        self.kind = kind                # "Download" | "List"
        self.url = url
        self.cmd = cmd
        self.what = what                # short text for the 'What' column
        self.dest = dest
        self.key = None                 # (url, format, playlist) - duplicate check
        self.state = "queued"           # queued | running | done | failed | stopped
        self.pct = 0.0
        self.speed = ""
        self.part = 0                   # yt-dlp fetches video and audio as separate parts
        self.name = ""                  # the file name, once yt-dlp announces it
        self.lines = []                 # its whole output (capped)
        self.worker = None
        self.stop_asked = False


class MediaQueue(QObject):
    """All media jobs of the browser window.  It lives with the WINDOW, not the
    dialog: closing or hiding the dialog does not touch a running download, and
    up to `media_parallel` (default 3) downloads run side by side - the rest wait
    their turn.  'List formats' look-ups are quick and never wait."""
    added = pyqtSignal(object)
    removed = pyqtSignal(object)
    changed = pyqtSignal(object)
    line = pyqtSignal(object, str)

    LOG_CAP = 4000
    _RX_PCT = re.compile(r"^\[download\]\s+(\d+(?:\.\d+)?)%")
    _RX_SPEED = re.compile(r"\bat\s+(\S+/s)")
    _RX_DEST = re.compile(r'^\[(?:download|ExtractAudio)\]\s+Destination:\s+(.+)$')
    _RX_MERGE = re.compile(r'^\[Merger\]\s+Merging formats into\s+"(.+)"$')

    def __init__(self, window):
        super().__init__()
        self.win = window
        self.jobs = []

    def max_parallel(self):
        try:
            n = int(self.win.settings.get("media_parallel", 3) or 3)
        except Exception:
            n = 3
        return max(1, min(8, n))

    def active_count(self):
        """Downloads that are running or still waiting."""
        return sum(1 for j in self.jobs
                   if j.kind == "Download" and j.state in ("queued", "running"))

    def waiting_count(self):
        return sum(1 for j in self.jobs if j.kind == "Download" and j.state == "queued")

    def find(self, job_id):
        for j in self.jobs:
            if j.id == job_id:
                return j
        return None

    def is_duplicate(self, key):
        return any(j.key == key and j.state in ("queued", "running") for j in self.jobs)

    # ---- adding, starting -------------------------------------------------
    def add(self, job):
        self.jobs.append(job)
        self.added.emit(job)
        self.pump()

    def pump(self):
        """Start waiting jobs until `max_parallel` downloads are running."""
        running = sum(1 for j in self.jobs if j.kind == "Download" and j.state == "running")
        limit = self.max_parallel()
        for j in self.jobs:
            if j.state != "queued":
                continue
            if j.kind == "Download" and running >= limit:
                continue
            self._start(j)
            if j.kind == "Download":
                running += 1

    def _start(self, job):
        job.state = "running"
        job.stop_asked = False
        job.pct, job.speed, job.part = 0.0, "", 0
        w = MediaWorker(job.cmd, job)
        w.line.connect(self._on_line)
        w.done.connect(self._on_done)
        job.worker = w
        self.changed.emit(job)
        w.start()

    # ---- worker callbacks (GUI thread) ------------------------------------
    def _log(self, job, text):
        job.lines.append(text)
        if len(job.lines) > self.LOG_CAP:
            del job.lines[:len(job.lines) - self.LOG_CAP]
        self.line.emit(job, text)

    def _on_line(self, job, text):
        self._log(job, text)
        m = self._RX_PCT.match(text)
        if m:
            try:
                job.pct = float(m.group(1))
            except ValueError:
                pass
            s = self._RX_SPEED.search(text)
            job.speed = s.group(1) if s else ""
            self.changed.emit(job)
            return
        m = self._RX_DEST.match(text) or self._RX_MERGE.match(text)
        if m:
            job.name = os.path.basename(m.group(1).strip())
            if text.startswith("[download]"):
                job.part += 1
            self.changed.emit(job)

    def _on_done(self, job, rc):
        job.worker = None
        if job.stop_asked:
            job.state = "stopped"
            self._log(job, "\n■ Stopped.")
        elif rc == 0:
            job.state = "done"
            job.pct = 100.0
            job.speed = ""
            self._log(job, "\n✓ %s finished." % ("Download" if job.kind == "Download" else "List"))
            if job.kind == "Download":
                show_toast(self.win, "Download finished ✓  %s" % (job.name or "")[:60], 2500)
        else:
            job.state = "failed"
            self._log(job, "\n✗ %s failed (exit code %s)." % (job.kind, rc))
            if job.kind == "Download":
                show_toast(self.win, "Download FAILED ✗  %s" % (job.name or job.url)[:60], 3000)
        self.changed.emit(job)
        self.pump()

    # ---- user actions -----------------------------------------------------
    def stop(self, job):
        if job.state == "queued":
            job.state = "stopped"
            self.changed.emit(job)
        elif job.state == "running" and job.worker:
            job.stop_asked = True
            self._log(job, "\n… stopping.")
            job.worker.stop()

    def retry(self, job):
        """Run a failed/stopped job again.  yt-dlp continues a half-finished file."""
        if job.state in ("failed", "stopped"):
            job.state = "queued"
            self._log(job, "\n↻ Queued again.")
            self.changed.emit(job)
            self.pump()

    def remove(self, job):
        if job.state == "running":
            return
        if job in self.jobs:
            self.jobs.remove(job)
            self.removed.emit(job)

    def clear_finished(self):
        for j in [j for j in self.jobs if j.state in ("done", "failed", "stopped")]:
            self.remove(j)

    def shutdown(self):
        """The browser is closing: stop everything that is still going."""
        for j in self.jobs:
            if j.state == "running" and j.worker:
                j.stop_asked = True
                j.worker.stop()
            elif j.state == "queued":
                j.state = "stopped"


class MediaDownloadDialog(QDialog):
    """Download video/audio with yt-dlp.  This window is only a VIEW of the
    window's MediaQueue: put an address in, press Enter, put the next one in -
    each becomes a line in the list and downloads on its own.  Closing the window
    just hides it; the downloads carry on and the browser shows a toast when one
    finishes.  It is also not owned by the browser window, so it can be put behind
    it, minimised or moved to another screen like any other program window."""

    # label -> (needs_ffmpeg, [yt-dlp format args])
    FORMATS = [
        ("Video — best quality (MP4, merges video+audio)",
         (True,  ["-f", "bv*+ba/b", "--merge-output-format", "mp4"])),
        ("Video — best single file (no ffmpeg needed)",
         (False, ["-f", "b"])),
        ("Audio only — MP3 (needs ffmpeg)",
         (True,  ["-x", "--audio-format", "mp3", "--audio-quality", "0"])),
        ("Audio only — best original (M4A/Opus, no convert)",
         (False, ["-f", "ba/b"])),
    ]
    STATE_TXT = {"queued": "⏳ Waiting", "running": "⬇ Running", "done": "✓ Done",
                 "failed": "✗ Failed", "stopped": "■ Stopped"}

    def __init__(self, window, url=""):
        super().__init__(None)           # deliberately NOT a child of the browser window
        self.win = window
        self.q = window.media_queue()
        self._getting = False
        self._items = {}                 # job id -> QTreeWidgetItem
        self._log_job = None             # the job whose output the log shows
        self.setWindowTitle(APP_NAME + " - Download video / audio")
        self.setModal(False)             # let the user keep browsing while it runs
        self.setWindowFlag(Qt.WindowType.WindowMinimizeButtonHint, True)
        self.setWindowFlag(Qt.WindowType.WindowMaximizeButtonHint, True)
        self.resize(780, 740)
        self.setStyleSheet(dialog_qss())
        apply_window_icon(self)

        lay = QVBoxLayout(self)
        lay.setSpacing(8)

        title = QLabel("⬇  Download video / music")
        title.setStyleSheet("font-size:14pt; font-weight:bold; color:%s;" % C_ACCENT)
        lay.addWidget(title)

        # ---- URL ----
        lay.addWidget(QLabel("Address of the page or media  (Enter adds it to the queue):"))
        self.url = QLineEdit(url)
        self.url.setPlaceholderText("https://...  (the page that shows the video/song)")
        self.url.returnPressed.connect(self.add_to_queue)
        lay.addWidget(self.url)

        # ---- Format ----
        row = QHBoxLayout()
        row.addWidget(QLabel("What to download:"))
        self.fmt = QComboBox()
        for label, _ in self.FORMATS:
            self.fmt.addItem(label)
        self.fmt.setCurrentIndex(int(self.win.settings.get("media_format_index", 0) or 0))
        row.addWidget(self.fmt, 1)
        lay.addLayout(row)

        # ---- Destination ----
        row2 = QHBoxLayout()
        row2.addWidget(QLabel("Save to:"))
        self.dest = QLineEdit(self._default_dest())
        row2.addWidget(self.dest, 1)
        btn_browse = QPushButton("Browse…")
        btn_browse.clicked.connect(self._pick_dest)
        row2.addWidget(btn_browse)
        lay.addLayout(row2)

        # ---- Options ----
        row3 = QHBoxLayout()
        self.cb_playlist = QCheckBox("If it is a playlist, download every item")
        self.cb_cookies = QCheckBox("Use my Firefox cookies (for members-only / age-gated)")
        col = QVBoxLayout()
        col.addWidget(self.cb_playlist)
        col.addWidget(self.cb_cookies)
        row3.addLayout(col, 1)
        row3.addWidget(QLabel("Download at once:"))
        self.spin_par = QSpinBox()
        self.spin_par.setRange(1, 8)
        self.spin_par.setValue(self.q.max_parallel())
        self.spin_par.setToolTip("How many downloads run side by side. The rest wait in "
                                 "the list and start by themselves.")
        self.spin_par.valueChanged.connect(self._par_changed)
        row3.addWidget(self.spin_par)
        lay.addLayout(row3)

        note = QLabel("Note: DRM-protected streams (Netflix, Disney+, Spotify, etc.) are "
                      "encrypted and cannot be downloaded by any tool — this is not a way "
                      "around that. Only download where you have the right to.")
        note.setWordWrap(True)
        note.setStyleSheet("color:%s; font-size:8pt; font-style:italic;" % dim_fg())
        lay.addWidget(note)

        # ---- Tool status ----
        self.status = QLabel("")
        self.status.setWordWrap(True)
        self.status.setStyleSheet("font-size:9pt;")
        lay.addWidget(self.status)

        # ---- The queue + the output of the selected line ----
        self.tree = QTreeWidget()
        self.tree.setColumnCount(4)
        self.tree.setHeaderLabels(["State", "Progress", "Name / address", "What"])
        self.tree.setRootIsDecorated(False)
        self.tree.setUniformRowHeights(True)
        self.tree.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection)
        self.tree.setColumnWidth(0, 105)
        self.tree.setColumnWidth(1, 150)
        self.tree.setColumnWidth(2, 330)
        self.tree.itemSelectionChanged.connect(self._on_select)

        self.log = QPlainTextEdit()
        self.log.setReadOnly(True)
        self.log.setStyleSheet("background:%s; color:%s; border:1px solid %s; "
                               "font-family:Consolas,monospace; font-size:9pt;"
                               % (C_ADDR_BG, C_ADDR_FG, C_BORDER))
        spl = QSplitter(Qt.Orientation.Vertical)
        spl.addWidget(self.tree)
        spl.addWidget(self.log)
        spl.setStretchFactor(0, 3)
        spl.setStretchFactor(1, 2)
        lay.addWidget(spl, 1)

        # ---- Buttons on the list ----
        qrow = QHBoxLayout()
        self.btn_stop = QPushButton("Stop")
        self.btn_stop.setToolTip("Stop the selected lines (partly downloaded files are kept)")
        self.btn_stop.clicked.connect(self.stop_selected)
        self.btn_retry = QPushButton("Try again")
        self.btn_retry.setToolTip("Queue the selected failed/stopped lines again - yt-dlp "
                                  "continues where it left off")
        self.btn_retry.clicked.connect(self.retry_selected)
        self.btn_remove = QPushButton("Remove")
        self.btn_remove.setToolTip("Take the selected lines out of the list (not running ones)")
        self.btn_remove.clicked.connect(self.remove_selected)
        self.btn_clear = QPushButton("Clear finished")
        self.btn_clear.clicked.connect(self.q.clear_finished)
        for b in (self.btn_stop, self.btn_retry, self.btn_remove, self.btn_clear):
            qrow.addWidget(b)
        qrow.addStretch(1)
        self.lbl_count = QLabel("")
        self.lbl_count.setStyleSheet("font-size:9pt; color:%s;" % dim_fg())
        qrow.addWidget(self.lbl_count)
        lay.addLayout(qrow)

        # ---- Buttons ----
        btns = QHBoxLayout()
        self.btn_formats = QPushButton("List formats")
        self.btn_formats.setToolTip("Show every quality/format yt-dlp can see for this URL")
        self.btn_formats.clicked.connect(self.list_formats)
        self.btn_get = QPushButton("Get yt-dlp")
        self.btn_get.setToolTip("Download the official yt-dlp.exe into the tools folder")
        self.btn_get.clicked.connect(self.get_ytdlp)
        self.btn_dl = QPushButton("⬇  Add to queue")
        self.btn_dl.setStyleSheet("QPushButton{background:%s; color:%s; border:none; "
                                  "padding:6px 16px; border-radius:6px;}"
                                  "QPushButton:hover{background:%s;}"
                                  % (C_ACCENT, C_ACCENT_FG, C_ACCENT_HOV))
        self.btn_dl.clicked.connect(self.add_to_queue)
        self.btn_openfolder = QPushButton("Open folder")
        self.btn_openfolder.clicked.connect(self._open_dest)
        self.btn_close = QPushButton("Close")
        self.btn_close.setToolTip("Hides this window - the downloads keep running")
        self.btn_close.clicked.connect(self.close)
        for b in (self.btn_formats, self.btn_get, self.btn_openfolder):
            btns.addWidget(b)
        btns.addStretch(1)
        btns.addWidget(self.btn_dl)
        btns.addWidget(self.btn_close)
        lay.addLayout(btns)

        # ---- follow the queue ----
        for j in self.q.jobs:
            self._add_item(j)
        self.q.added.connect(self._add_item)
        self.q.removed.connect(self._remove_item)
        self.q.changed.connect(self._update_item)
        self.q.line.connect(self._on_line)

        self._refresh_tool_status()
        self._update_buttons()
        self.url.setFocus()

    # ---- helpers ----------------------------------------------------------
    def _default_dest(self):
        d = self.win.settings.get("media_download_dir")
        if d and os.path.isdir(d):
            return d
        downloads = os.path.join(os.path.expanduser("~"), "Downloads")
        return downloads if os.path.isdir(downloads) else os.path.expanduser("~")

    def _pick_dest(self):
        d = QFileDialog.getExistingDirectory(self, "Choose a download folder", self.dest.text())
        if d:
            self.dest.setText(d)

    def _open_dest(self):
        d = self.dest.text().strip()
        jobs = self._selected_jobs()
        if jobs and jobs[0].dest:
            d = jobs[0].dest             # the folder THAT line went to
        if d and os.path.isdir(d):
            try:
                open_path(d)           # whatever DefaultHub says opens a folder
            except Exception:
                open_url("file:///" + d.replace("\\", "/"))

    def _par_changed(self, n):
        self.win.settings["media_parallel"] = int(n)
        save_json(SETTINGS_FILE, self.win.settings)
        self.q.pump()                    # a higher number may let waiting lines start now

    def _refresh_tool_status(self):
        cmd = find_ytdlp()
        ff = find_ffmpeg_dir()
        if cmd:
            where = cmd[0] if cmd[0].lower().endswith(("yt-dlp", "yt-dlp.exe")) else "python -m yt_dlp"
            txt = "✓ yt-dlp found (%s)." % os.path.basename(where)
            txt += ("  ✓ ffmpeg found." if ff else
                    "  ⚠ ffmpeg NOT found — MP3 and 'best quality (merge)' need it; "
                    "use a 'no ffmpeg' option, or drop ffmpeg.exe in the tools folder.")
            self.status.setStyleSheet("font-size:9pt; color:%s;" % dim_fg())
            self.btn_dl.setEnabled(True)
            self.btn_formats.setEnabled(True)
            self.btn_get.setVisible(cmd[0] != sys.executable)  # hide if it's the pip module
        else:
            txt = ("⚠ yt-dlp is not installed. Click 'Get yt-dlp' to download the official "
                   "tool (one ~30 MB file) into the program's tools folder.")
            self.status.setStyleSheet("font-size:9pt; color:#d98a00;")
            self.btn_dl.setEnabled(False)
            self.btn_formats.setEnabled(False)
        self.status.setText(txt)

    # ---- the list ---------------------------------------------------------
    def _row_texts(self, j):
        if j.kind == "List":
            prog = ""
        elif j.state == "running":
            prog = "%.1f%%" % j.pct
            if j.speed:
                prog += "  ·  " + j.speed
            if j.part > 1:
                prog += "  ·  part %d" % j.part
        elif j.state == "done":
            prog = "100%"
        elif j.pct:
            prog = "%.0f%%" % j.pct
        else:
            prog = "—"
        return [self.STATE_TXT.get(j.state, j.state), prog, j.name or j.url, j.what]

    def _add_item(self, j):
        it = QTreeWidgetItem(self._row_texts(j))
        it.setData(0, Qt.ItemDataRole.UserRole, j.id)
        it.setToolTip(2, j.url)
        self._items[j.id] = it
        self.tree.addTopLevelItem(it)
        if not self.tree.selectedItems():
            self.tree.setCurrentItem(it)         # show its output straight away
        self._update_buttons()

    def _remove_item(self, j):
        it = self._items.pop(j.id, None)
        if it is not None:
            self.tree.takeTopLevelItem(self.tree.indexOfTopLevelItem(it))
        if self._log_job is j:
            self._log_job = None
            self.log.clear()
        self._update_buttons()

    def _update_item(self, j):
        it = self._items.get(j.id)
        if it is not None:
            for c, t in enumerate(self._row_texts(j)):
                it.setText(c, t)
        self._update_buttons()

    def _selected_jobs(self):
        out = []
        for it in self.tree.selectedItems():
            j = self.q.find(it.data(0, Qt.ItemDataRole.UserRole))
            if j is not None:
                out.append(j)
        return out

    def _on_select(self):
        jobs = self._selected_jobs()
        self._log_job = jobs[0] if jobs else None
        self.log.setPlainText("\n".join(self._log_job.lines) if self._log_job else "")
        sb = self.log.verticalScrollBar()
        sb.setValue(sb.maximum())
        self._update_buttons()

    def _on_line(self, j, text):
        if j is self._log_job:
            self.log.appendPlainText(text)
            sb = self.log.verticalScrollBar()
            sb.setValue(sb.maximum())

    def _update_buttons(self):
        jobs = self._selected_jobs()
        self.btn_stop.setEnabled(any(j.state in ("queued", "running") for j in jobs))
        self.btn_retry.setEnabled(any(j.state in ("failed", "stopped") for j in jobs))
        self.btn_remove.setEnabled(any(j.state != "running" for j in jobs))
        self.btn_clear.setEnabled(any(j.state in ("done", "failed", "stopped")
                                      for j in self.q.jobs))
        run = sum(1 for j in self.q.jobs if j.kind == "Download" and j.state == "running")
        self.lbl_count.setText("%d running, %d waiting" % (run, self.q.waiting_count()))

    def stop_selected(self):
        for j in self._selected_jobs():
            self.q.stop(j)

    def retry_selected(self):
        for j in self._selected_jobs():
            self.q.retry(j)

    def remove_selected(self):
        for j in self._selected_jobs():
            self.q.remove(j)

    # ---- build & queue yt-dlp commands ------------------------------------
    def _base_cmd(self):
        cmd = find_ytdlp()
        if not cmd:
            return None
        cmd = list(cmd) + ["--newline", "--no-color", "--ignore-config"]
        ff = find_ffmpeg_dir()
        if ff:
            cmd += ["--ffmpeg-location", ff]
        if self.cb_cookies.isChecked():
            cmd += ["--cookies-from-browser", "firefox"]
        return cmd

    def add_to_queue(self):
        url = self.url.text().strip()
        if not url:
            show_toast(self.win, "Enter an address first")
            return
        cmd = self._base_cmd()
        if not cmd:
            self._refresh_tool_status()
            return
        idx = self.fmt.currentIndex()
        playlist = self.cb_playlist.isChecked()
        key = (url, idx, playlist)
        if self.q.is_duplicate(key):
            show_toast(self.win, "That one is already in the queue")
            return
        dest = self.dest.text().strip() or self._default_dest()
        try:
            os.makedirs(dest, exist_ok=True)
        except Exception:
            pass
        self.win.settings["media_download_dir"] = dest
        self.win.settings["media_format_index"] = idx
        save_json(SETTINGS_FILE, self.win.settings)

        label, (needs_ff, fmt_args) = self.FORMATS[idx]
        if needs_ff and not find_ffmpeg_dir():
            if QMessageBox.question(
                    self, "ffmpeg missing",
                    "This option needs ffmpeg, which was not found.\n\n"
                    "Download anyway? (yt-dlp may fail to merge or convert.)\n"
                    "Tip: pick a 'no ffmpeg' option, or put ffmpeg.exe in:\n%s"
                    % MEDIA_TOOLS_DIR) != QMessageBox.StandardButton.Yes:
                return
        out_tmpl = os.path.join(dest, "%(title)s.%(ext)s")
        cmd += list(fmt_args) + ["-o", out_tmpl]
        cmd += ["--yes-playlist"] if playlist else ["--no-playlist"]
        cmd += [url]

        job = MediaJob("Download", url, cmd, label.split(" (")[0], dest)
        job.key = key
        job.lines.append("$ " + " ".join('"%s"' % c if " " in c else c for c in cmd))
        job.lines.append("")
        self.q.add(job)
        self.url.clear()                 # ready for the next address
        self.url.setFocus()
        waiting = self.q.waiting_count()
        show_toast(self.win, "Added to the queue" +
                   ("  (%d waiting)" % waiting if waiting else ""))

    def list_formats(self):
        url = self.url.text().strip()
        if not url:
            show_toast(self.win, "Enter an address first")
            return
        cmd = self._base_cmd()
        if not cmd:
            self._refresh_tool_status()
            return
        cmd += ["-F", url]
        job = MediaJob("List", url, cmd, "List formats", "")
        job.lines.append("Listing available formats…\n")
        self.q.add(job)
        self.tree.setCurrentItem(self._items[job.id])    # the answer is the point here

    # ---- one-click yt-dlp install ----------------------------------------
    def get_ytdlp(self):
        if self._getting:
            return
        if os.name != "nt":
            QMessageBox.information(
                self, "Get yt-dlp",
                "Automatic download is Windows-only here.\n"
                "On other systems install yt-dlp with:  pip install -U yt-dlp")
            return
        self._getting = True
        self.btn_get.setEnabled(False)
        target = os.path.join(MEDIA_TOOLS_DIR, "yt-dlp.exe")
        self.status.setText("Downloading yt-dlp.exe from the official GitHub release…")

        def work():
            ok, msg = True, ""
            try:
                os.makedirs(MEDIA_TOOLS_DIR, exist_ok=True)
                req = urllib.request.Request(
                    YTDLP_DOWNLOAD_URL, headers={"User-Agent": "WhyBrowse"})
                tmp = target + ".part"
                with urllib.request.urlopen(req, timeout=60) as r, open(tmp, "wb") as f:
                    shutil.copyfileobj(r, f)
                os.replace(tmp, target)
            except Exception as e:
                ok, msg = False, str(e)
            QTimer.singleShot(0, lambda: self._get_done(ok, msg))

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

    def _get_done(self, ok, msg):
        self._getting = False
        self.btn_get.setEnabled(True)
        if ok:
            show_toast(self.win, "yt-dlp installed ✓")
        else:
            QMessageBox.warning(self, "Get yt-dlp",
                                "Download failed:\n%s\n\nYou can also install it manually "
                                "with:  pip install -U yt-dlp" % msg)
        self._refresh_tool_status()

    # ---- window plumbing --------------------------------------------------
    def keyPressEvent(self, e):
        if e.key() == Qt.Key.Key_Escape:
            self.close()
        else:
            super().keyPressEvent(e)

    # closeEvent: none on purpose. Closing only HIDES the window; the queue (owned
    # by the browser window) keeps downloading and is stopped in its closeEvent.


# ============================================================================
#  DEL 49 - TORRENTS & MAGNET LINKS  (🧲 magnet:… links and .torrent files)
# ----------------------------------------------------------------------------
#  WHAT A MAGNET LINK IS, AND WHY THAT MATTERS HERE
#  A magnet link is NOT a file. Nothing is stored behind it and there is no
#  address to fetch: it is a 40-character fingerprint (the "info hash") plus,
#  usually, a display name and a few tracker addresses. Turning that into real
#  files means speaking BitTorrent — finding other computers that already have
#  the pieces and collecting the pieces from them. A web browser cannot do that
#  on its own, which is why every other browser just hands magnet links to some
#  other program and forgets about them.
#
#  WhyBrowse does all three things, and you choose which one per link (or once
#  and for all, in Settings ▸ Torrents):
#
#    1. DOWNLOAD IT HERE - the built-in engine (the libtorrent library, the same
#       engine qBittorrent and Deluge are built on) fetches the actual files
#       into the folder you picked. Progress is shown in the Torrents window.
#    2. SAVE THE LINK - writes a tiny "<name>.magnet" text file into your
#       torrent folder. Every torrent program can open one, and qBittorrent /
#       Deluge / Transmission can be pointed at that folder as a WATCH folder,
#       in which case they pick it up by themselves, seconds later.
#    3. OPEN IN MY TORRENT PROGRAM - hands the magnet to whichever program
#       Windows has registered for magnet: links, exactly like other browsers.
#
#  A .torrent FILE link (an ordinary https://…/something.torrent) is recognised
#  as well and follows the same three choices - it is just the other packaging
#  of the same thing, so it never lands in your normal Downloads folder by
#  mistake.
#
#  WHERE THINGS ARRIVE
#  Either your normal download folder, or a separate torrent folder (the reason
#  this exists: torrents want their own drive). Set in Settings ▸ Torrents.
#
#  WHEN IT REACTS
#    * you CLICK a magnet / .torrent link on a page,
#    * you PASTE one into the address bar and press Enter,
#    * you COPY one anywhere (the clipboard watch, on by default - this is the
#      "I copied it, now deal with it" case),
#    * another program hands one to WhyBrowse on the command line,
#    * you right-click a magnet link → "🧲 Torrent this link…".
#  In every case the "When I meet a torrent link" setting decides: ASK me
#  (default), do it AUTOMATICALLY, or IGNORE it completely.
#
#  HONEST LIMITS, so nothing here is a surprise:
#    * a magnet with no live peers downloads nothing, ever - that is BitTorrent,
#      not a bug. The window says "looking for the torrent info…" while it is
#      still trying to find someone who has it;
#    * UPnP (asking your router to open a port) is OFF by default because
#      libtorrent's UPnP shutdown blocks for ~20 seconds - measured - which
#      would make CLOSING WhyBrowse take 20 seconds. Downloading works fine
#      without it; turn it on in Settings if you want more incoming peers and
#      can live with the slow close;
#    * seeding (keeping the upload going after the download is finished) is OFF
#      by default. A finished torrent is paused, not silently left uploading;
#    * a resumed torrent is re-checked against the files already on disk
#      (fast), so a half-finished download continues where it stopped.
# ============================================================================

MAGNET_SCHEME = "magnet:"

# The three things that can be done with a torrent link.
TORRENT_ACTIONS = [
    ("download", "⬇  Download the files here  (built-in torrent engine)"),
    ("savelink", "💾  Save the link as a .magnet file in the torrent folder"),
    ("client",   "↗  Open it in my own torrent program"),
]
TORRENT_ACTION_LABELS = dict(TORRENT_ACTIONS)

# What happens when a torrent link turns up at all.
TORRENT_MODES = [
    ("ask",    "Ask me what to do  (recommended)"),
    ("auto",   "Do it automatically, no pop-up"),
    ("ignore", "Ignore torrent links completely"),
]
TORRENT_MODE_LABELS = dict(TORRENT_MODES)


def is_magnet_link(text):
    """True for a magnet: URI (the only scheme a browser gets handed)."""
    return bool(text) and str(text).strip().lower().startswith(MAGNET_SCHEME)


def is_torrent_file_url(text):
    """True for an ordinary http(s) address that points at a .torrent FILE."""
    t = (text or "").strip().lower()
    if not t.startswith(("http://", "https://", "file://")):
        return False
    path = t.split("#", 1)[0].split("?", 1)[0]
    return path.endswith(".torrent")


def is_local_torrent_file(text):
    """True for a .torrent file that is already on this computer (double-clicked
    in Explorer, or handed to us on the command line)."""
    t = (text or "").strip().strip('"')
    try:
        return t.lower().endswith(".torrent") and os.path.isfile(t)
    except Exception:
        return False


def is_torrent_link(text):
    """Every packaging of the same thing: a magnet link, a .torrent address, or
    a .torrent file sitting on this computer."""
    return (is_magnet_link(text) or is_torrent_file_url(text)
            or is_local_torrent_file(text))


def parse_magnet(uri):
    """Pull the readable parts out of a magnet URI.

    Returns {"hash", "name", "trackers", "uri"}. Everything is optional in a
    magnet except the info hash, and even that comes in two spellings (40-char
    hex, or 32-char base32), so nothing here assumes anything is present."""
    from urllib.parse import parse_qs, unquote_plus
    out = {"hash": "", "name": "", "trackers": [], "uri": (uri or "").strip()}
    try:
        query = out["uri"].split("?", 1)[1] if "?" in out["uri"] else ""
        q = parse_qs(query, keep_blank_values=False)
        for xt in q.get("xt", []):
            low = xt.lower()
            if low.startswith("urn:btih:"):
                out["hash"] = xt.split(":", 2)[2].strip().lower()
            elif low.startswith("urn:btmh:") and not out["hash"]:
                out["hash"] = xt.split(":", 2)[2].strip().lower()   # v2 hash
        names = q.get("dn", [])
        if names:
            out["name"] = unquote_plus(names[0]).strip()
        out["trackers"] = [unquote_plus(t) for t in q.get("tr", [])]
    except Exception as e:
        log_line("parse_magnet failed: %s" % e)
    return out


def torrent_link_title(link):
    """A readable name for any torrent link, for menus and pop-ups."""
    if is_magnet_link(link):
        info = parse_magnet(link)
        if info["name"]:
            return info["name"]
        return "Torrent %s" % (info["hash"][:16] or "(unknown)")
    try:
        from urllib.parse import unquote
        base = unquote(link.split("#", 1)[0].split("?", 1)[0].rstrip("/").rsplit("/", 1)[-1])
        return base or "torrent"
    except Exception:
        return "torrent"


def torrent_safe_name(name, fallback="torrent"):
    """A filename Windows will actually accept (the same rule downloads use)."""
    cleaned = re.sub(r'[<>:"/\\|?*]', "-", (name or "").strip())
    cleaned = re.sub(r"\s+", " ", cleaned).rstrip(" .")
    return (cleaned or fallback)[:150]


def _t_size(n):
    """1234567 -> '1.18 MB'."""
    try:
        n = float(n or 0)
    except Exception:
        return "-"
    if n < 1024:
        return "%d B" % int(n)
    for unit in ("KB", "MB", "GB"):
        n /= 1024.0
        if n < 1024:
            return "%.1f %s" % (n, unit)
    return "%.2f TB" % (n / 1024.0)


def _t_rate(n):
    """Bytes per second, as a speed."""
    try:
        n = float(n or 0)
    except Exception:
        return ""
    if n <= 0:
        return ""
    return _t_size(n) + "/s"


def _t_eta(remaining, rate):
    """Time left, or '' when nothing is moving."""
    try:
        if rate <= 0 or remaining <= 0:
            return ""
        secs = int(remaining / float(rate))
    except Exception:
        return ""
    if secs < 60:
        return "%ds" % secs
    if secs < 3600:
        return "%dm %ds" % (secs // 60, secs % 60)
    if secs < 86400:
        return "%dh %dm" % (secs // 3600, (secs % 3600) // 60)
    return "%dd %dh" % (secs // 86400, (secs % 86400) // 3600)


# ---------------------------------------------------------------------------
#  The engine itself (optional dependency)
# ---------------------------------------------------------------------------
_LT_MODULE = None
_LT_TRIED = False


def find_libtorrent():
    """The libtorrent module, or None if it is not installed.

    Imported LAZILY, on first real use: importing it costs time and, more to
    the point, nobody who never touches a torrent link should pay for it."""
    global _LT_MODULE, _LT_TRIED
    if _LT_TRIED:
        return _LT_MODULE
    _LT_TRIED = True
    try:
        import libtorrent as _lt
        _LT_MODULE = _lt
        log_line("libtorrent %s available" % getattr(_lt, "version", "?"))
    except Exception as e:
        _LT_MODULE = None
        log_line("libtorrent not available: %s" % e)
    return _LT_MODULE


def libtorrent_version():
    lt = find_libtorrent()
    return str(getattr(lt, "version", "")) if lt else ""


class TorrentEngine(QObject):
    """Owns the one BitTorrent session and the list of torrents in it.

    Nothing here starts by itself: the session (which opens a listening port
    and joins the DHT) is created the first time a torrent is actually added,
    and never before. Status is polled once a second from the GUI thread -
    libtorrent does its own work in its own threads, and reading a handle's
    status is cheap, so no worker thread of our own is needed."""

    changed  = pyqtSignal()             # something in the list moved
    finished = pyqtSignal(str, str)     # name, folder  (a torrent completed)

    POLL_MS = 1000

    def __init__(self, window):
        super().__init__(window)
        self.win = window
        self.lt = None
        self.ses = None
        self.error = ""
        self.items = []            # [{handle,uri,name,folder,hash,added,done,...}]
        # DEL 55: unfinished torrents from last time that are remembered in
        # torrents.json but NOT running right now (resume-on-start is off, the
        # drive was missing, the engine was not installed ...). They are kept
        # in the file on every save, so adding a new torrent can no longer wipe
        # them, and the profile menu's "Restart" section can start them again.
        self.waiting = [r for r in self.saved_items() if not r.get("done")]
        self._save_due = 0
        self.timer = QTimer(self)
        self.timer.setInterval(self.POLL_MS)
        self.timer.timeout.connect(self._poll)

    # ---- session ---------------------------------------------------------
    def available(self):
        return find_libtorrent() is not None

    def _ensure_session(self):
        """Create the session on first use. False + self.error if impossible."""
        if self.ses is not None:
            return True
        lt = find_libtorrent()
        if lt is None:
            self.error = ("The torrent engine is not installed.\n\n"
                          "WhyBrowse downloads torrents with libtorrent - the "
                          "same engine qBittorrent and Deluge use. Install it "
                          "once with:\n\n    pip install libtorrent\n\n"
                          "Until then, \"Save the link\" and \"Open in my "
                          "torrent program\" still work.")
            return False
        s = self.win.settings
        port = int(s.get("torrent_port", 6881) or 6881)
        conf = {
            "listen_interfaces": "0.0.0.0:%d,[::]:%d" % (port, port),
            "alert_mask": 0,                       # we poll; we don't read alerts
            "enable_dht": True,
            "enable_lsd": True,
            "enable_natpmp": True,
            # OFF unless asked for: libtorrent's UPnP shutdown blocks for ~20 s
            # (measured), and it blocks the whole process - i.e. closing the
            # browser. See the section header.
            "enable_upnp": bool(s.get("torrent_upnp", False)),
            "download_rate_limit": max(0, int(s.get("torrent_dl_limit_kbs", 0) or 0)) * 1024,
            "upload_rate_limit":   max(0, int(s.get("torrent_ul_limit_kbs", 0) or 0)) * 1024,
        }
        try:
            self.lt = lt
            self.ses = lt.session(conf)
            log_line("Torrent session started on port %d (upnp=%s)"
                     % (port, conf["enable_upnp"]))
            return True
        except Exception as e:
            self.ses = None
            self.error = "Could not start the torrent engine: %s" % e
            log_line("torrent session failed: %s" % e)
            return False

    def apply_limits(self):
        """Push changed speed limits onto a session that is already running."""
        if self.ses is None:
            return
        try:
            st = self.ses.get_settings()
            st["download_rate_limit"] = max(0, int(
                self.win.settings.get("torrent_dl_limit_kbs", 0) or 0)) * 1024
            st["upload_rate_limit"] = max(0, int(
                self.win.settings.get("torrent_ul_limit_kbs", 0) or 0)) * 1024
            self.ses.apply_settings(st)
        except Exception as e:
            log_line("torrent apply_limits failed: %s" % e)

    # ---- adding ----------------------------------------------------------
    def add_magnet(self, uri, folder, name=""):
        """Start (or resume) a magnet. Returns (ok, message)."""
        if not self._ensure_session():
            return False, self.error
        try:
            os.makedirs(folder, exist_ok=True)
        except Exception as e:
            return False, "Cannot use the folder %s: %s" % (folder, e)
        info = parse_magnet(uri)
        # The fingerprint comes in two spellings - 40 hex characters, or 32
        # base32 ones. libtorrent always reports the hex one, so the base32
        # spelling is converted here; otherwise the same torrent, linked to
        # both ways, would look like two different ones.
        ihash = (info.get("hash") or "").lower()
        if len(ihash) == 32:
            try:
                import base64
                ihash = base64.b32decode(ihash.upper()).hex()
            except Exception:
                pass
        existing = self._by_hash(ihash)
        if existing:
            return True, "Already in the list: %s" % (existing.get("name") or "torrent")
        # A magnet we have downloaded before may already have its .torrent
        # saved next to us - starting from that skips the whole "find someone
        # who can tell me what this even is" phase.
        meta = self._meta_path(ihash)
        try:
            if meta and os.path.isfile(meta):
                return self.add_torrent_file(meta, folder, uri=uri,
                                             name=name or info.get("name"))
            p = self.lt.parse_magnet_uri(uri)
            p.save_path = folder
            h = self.ses.add_torrent(p)
        except Exception as e:
            log_line("add_magnet failed: %s" % e)
            return False, "Could not start this torrent: %s" % e
        self._track(h, uri=uri, folder=folder,
                    name=name or info.get("name") or "", hash_=ihash)
        return True, ""

    def add_torrent_file(self, path, folder, uri="", name=""):
        """Start (or resume) a .torrent FILE. Returns (ok, message)."""
        if not self._ensure_session():
            return False, self.error
        try:
            os.makedirs(folder, exist_ok=True)
            ti = self.lt.torrent_info(path)
            p = self.lt.add_torrent_params()
            p.ti = ti
            p.save_path = folder
            h = self.ses.add_torrent(p)
        except Exception as e:
            log_line("add_torrent_file failed: %s" % e)
            return False, "Could not read that .torrent file: %s" % e
        self._track(h, uri=uri, folder=folder, name=name or "", path=path)
        return True, ""

    def _track(self, handle, uri="", folder="", name="", hash_="", path=""):
        item = {"handle": handle, "uri": uri, "folder": folder,
                "name": name or "", "hash": hash_ or self._hash_of(handle),
                "path": path, "added": time.time(), "done": False,
                "meta_saved": False, "status": "starting", "progress": 0.0,
                "size": 0, "down": 0, "up": 0, "peers": 0, "seeds": 0,
                "eta": ""}
        self.items.append(item)
        k = self._rec_key(item)
        if k:                      # now running -> no longer "waiting" (DEL 55)
            self.waiting = [r for r in self.waiting if self._rec_key(r) != k]
        if not self.timer.isActive():
            self.timer.start()
        self._save_state()
        self.changed.emit()

    # ---- the once-a-second update ---------------------------------------
    def _hash_of(self, handle):
        try:
            st = handle.status()
            ih = getattr(st, "info_hashes", None)
            return str(ih.v1) if ih is not None else str(st.info_hash)
        except Exception:
            return ""

    def _by_hash(self, h):
        if not h:
            return None
        for it in self.items:
            if it.get("hash") and it["hash"].lower() == str(h).lower():
                return it
        return None

    def _meta_path(self, hash_):
        if not hash_:
            return ""
        try:
            os.makedirs(TORRENT_META_DIR, exist_ok=True)
        except Exception:
            return ""
        return os.path.join(TORRENT_META_DIR, "%s.torrent" % hash_)

    def _save_metadata(self, item):
        """Once the torrent's own description has arrived, keep a copy so a
        later resume does not have to fetch it from the network again."""
        path = self._meta_path(item.get("hash"))
        if not path or os.path.isfile(path):
            item["meta_saved"] = True
            return
        try:
            ti = item["handle"].torrent_file()
            if ti is None:
                return
            blob = self.lt.bencode(self.lt.create_torrent(ti).generate())
            with open(path, "wb") as f:
                f.write(blob)
            item["meta_saved"] = True
        except Exception as e:
            log_line("torrent metadata save failed: %s" % e)
            item["meta_saved"] = True          # don't retry every second

    def _poll(self):
        if not self.items:
            self.timer.stop()
            return
        seed_after = bool(self.win.settings.get("torrent_seed_after", False))
        for it in list(self.items):
            h = it.get("handle")
            if h is None:
                continue
            try:
                st = h.status()
            except Exception:
                continue
            state = str(st.state).split(".")[-1]
            it["name"] = st.name or it.get("name") or ""
            it["progress"] = float(st.progress or 0.0)
            it["size"] = int(st.total_wanted or 0)
            it["got"] = int(st.total_wanted_done or 0)
            it["down"] = int(st.download_rate or 0)
            it["up"] = int(st.upload_rate or 0)
            it["peers"] = int(st.num_peers or 0)
            it["seeds"] = int(st.num_seeds or 0)
            it["paused"] = bool(getattr(st, "paused", False))
            it["eta"] = _t_eta(it["size"] - it["got"], it["down"])
            if not it.get("hash"):
                it["hash"] = self._hash_of(h)
            if state == "downloading_metadata":
                it["status"] = "looking for the torrent info…"
            elif it["paused"] and not it.get("done"):
                it["status"] = "paused"
            elif state in ("checking_files", "checking_resume_data"):
                it["status"] = "checking what is already on disk…"
            elif state in ("finished", "seeding"):
                it["status"] = "seeding" if (seed_after and not it["paused"]) else "finished"
            else:
                it["status"] = state.replace("_", " ")
            if getattr(st, "has_metadata", False) and not it.get("meta_saved"):
                self._save_metadata(it)
            # Finished: stop uploading unless the user asked to keep seeding.
            if (st.is_seeding or state in ("finished", "seeding")) and not it.get("done"):
                it["done"] = True
                if not seed_after:
                    try:
                        h.pause()
                    except Exception:
                        pass
                self._save_state()
                self.finished.emit(it["name"] or "Torrent", it.get("folder", ""))
        # Periodic state save so a crash cannot lose the list.
        if time.time() > self._save_due:
            self._save_due = time.time() + 30
            self._save_state()
        self.changed.emit()

    # ---- controls --------------------------------------------------------
    def rows(self):
        return list(self.items)

    def pause(self, item):
        try:
            item["handle"].pause()
            item["status"] = "paused"
            self.changed.emit()
        except Exception as e:
            log_line("torrent pause failed: %s" % e)

    def resume(self, item):
        try:
            item["handle"].resume()
            self.changed.emit()
            if not self.timer.isActive():
                self.timer.start()
        except Exception as e:
            log_line("torrent resume failed: %s" % e)

    def remove(self, item, delete_files=False):
        try:
            if delete_files:
                self.ses.remove_torrent(item["handle"], self.lt.session.delete_files)
            else:
                self.ses.remove_torrent(item["handle"])
        except Exception as e:
            log_line("torrent remove failed: %s" % e)
        try:
            self.items.remove(item)
        except ValueError:
            pass
        self._save_state()
        self.changed.emit()

    # ---- remembering across restarts -------------------------------------
    @staticmethod
    def _rec_key(rec):
        return str(rec.get("hash") or rec.get("uri") or rec.get("path") or "").lower()

    def _save_state(self):
        rows = [{
            "uri": it.get("uri", ""), "name": it.get("name", ""),
            "folder": it.get("folder", ""), "hash": it.get("hash", ""),
            "path": it.get("path", ""), "added": it.get("added", 0),
            "done": bool(it.get("done")),
        } for it in self.items]
        # DEL 55: remembered-but-not-running torrents stay in the file.
        have = {self._rec_key(r) for r in rows}
        for rec in self.waiting:
            k = self._rec_key(rec)
            if k and k in have:
                continue
            have.add(k)
            rows.append(rec)
        save_json(TORRENTS_FILE, {"items": rows})

    @staticmethod
    def saved_items():
        data = load_json(TORRENTS_FILE, {}) or {}
        return [x for x in (data.get("items") or []) if isinstance(x, dict)]

    def resume_unfinished(self):
        """Put every unfinished torrent from last time back in the session.
        libtorrent re-checks the files already on disk, so a half-finished
        download continues instead of starting over. Returns how many."""
        n = 0
        for rec in list(self.waiting):
            ok, _msg = self._resume_record(rec)
            if ok:
                n += 1
        return n

    # ---- DEL 55: restart things that are remembered but not running -------
    def _resume_record(self, rec):
        """Start ONE remembered torrent. Returns (ok, message). On failure the
        record stays in self.waiting (and so in the file) - never dropped."""
        folder = rec.get("folder") or ""
        name = rec.get("name") or rec.get("uri") or "a torrent"
        if not folder:
            return False, "%s: no download folder was saved" % name
        if rec in self.waiting:
            self.waiting.remove(rec)         # so _save_state does not write it twice
        meta = self._meta_path(rec.get("hash"))
        ok, msg = False, "%s: nothing to start it from (no link, no .torrent)" % name
        if meta and os.path.isfile(meta):
            ok, msg = self.add_torrent_file(meta, folder, uri=rec.get("uri", ""),
                                            name=rec.get("name", ""))
        elif rec.get("path") and os.path.isfile(rec["path"]):
            ok, msg = self.add_torrent_file(rec["path"], folder,
                                            name=rec.get("name", ""))
        elif rec.get("uri"):
            ok, msg = self.add_magnet(rec["uri"], folder, rec.get("name", ""))
        if not ok:
            self.waiting.append(rec)
            msg = "%s: %s" % (name, msg)
        return ok, msg

    def restart_count(self):
        """How many torrents a 'restart' would touch: remembered-but-stopped
        ones plus unfinished ones that are paused in this session."""
        paused = [it for it in self.items
                  if it.get("paused") and not it.get("done")]
        return len(self.waiting) + len(paused)

    def restart_all(self):
        """Resume every paused unfinished torrent and start every remembered one
        that is not running. Returns (started, [problem messages])."""
        started, problems = 0, []
        if not self._ensure_session():
            return 0, [self.error]
        for it in list(self.items):
            if it.get("paused") and not it.get("done"):
                self.resume(it)
                started += 1
        for rec in list(self.waiting):
            ok, msg = self._resume_record(rec)
            if ok:
                started += 1
            else:
                problems.append(msg)
        self._save_state()
        return started, problems

    def forget_waiting(self):
        """Drop the remembered-but-not-running torrents (files stay on disk)."""
        n = len(self.waiting)
        self.waiting = []
        self._save_state()
        return n

    def shutdown(self):
        """Called when the window closes. Pause first (so nothing is mid-write),
        then let the session go. With UPnP off this returns immediately."""
        try:
            self._save_state()
        except Exception:
            pass
        try:
            if self.ses is not None:
                self.ses.pause()
        except Exception:
            pass
        self.timer.stop()
        self.items = []
        self.ses = None


# ---------------------------------------------------------------------------
#  "I found a torrent link" - the pop-up
# ---------------------------------------------------------------------------
class TorrentAskDialog(QDialog):
    """Shown when a magnet / .torrent link turns up and the mode is ASK.

    Everything it asks is also a setting, so ticking "always do this" turns
    the pop-up off for good (Settings ▸ Torrents brings it back)."""

    def __init__(self, window, link, source=""):
        super().__init__(window)
        self.win = window
        self.link = link
        self.setWindowTitle(APP_NAME + " - Torrent link")
        self.setModal(True)
        self.resize(660, 420)
        self.setStyleSheet(dialog_qss())
        apply_window_icon(self)

        s = window.settings
        info = parse_magnet(link) if is_magnet_link(link) else {}
        name = torrent_link_title(link)

        lay = QVBoxLayout(self)
        head = QLabel("🧲  Torrent link" + ("  (%s)" % source if source else ""))
        head.setStyleSheet("color:%s; font-size:13pt; font-weight:bold;" % C_ACCENT)
        lay.addWidget(head)

        nm = QLabel(name)
        nm.setWordWrap(True)
        nm.setStyleSheet("font-size:11pt; font-weight:bold;")
        lay.addWidget(nm)

        bits = []
        if info.get("hash"):
            bits.append("fingerprint %s" % info["hash"])
        if info.get("trackers"):
            bits.append("%d tracker%s" % (len(info["trackers"]),
                                          "" if len(info["trackers"]) == 1 else "s"))
        if is_torrent_file_url(link):
            bits.append(".torrent file")
        sub = QLabel("   ·   ".join(bits) if bits else link[:120])
        sub.setWordWrap(True)
        sub.setStyleSheet("color:%s; font-size:8pt;" % C_STATUS_FG)
        lay.addWidget(sub)

        lay.addWidget(QLabel("What should I do with it?"))
        self.cmb_action = QComboBox()
        for key, label in TORRENT_ACTIONS:
            self.cmb_action.addItem(label, key)
        idx = self.cmb_action.findData(s.get("torrent_action", "download"))
        self.cmb_action.setCurrentIndex(idx if idx >= 0 else 0)
        lay.addWidget(self.cmb_action)

        eng = QLabel("")
        eng.setWordWrap(True)
        eng.setStyleSheet("color:%s; font-size:8pt;" % C_STATUS_FG)
        v = libtorrent_version()
        if v:
            eng.setText("Built-in engine ready (libtorrent %s)." % v)
        else:
            eng.setText("The built-in engine (libtorrent) is not installed, so "
                        "\"Download the files here\" cannot run yet — "
                        "pip install libtorrent. The other two choices work "
                        "regardless.")
        lay.addWidget(eng)

        lay.addWidget(QLabel("Folder:"))
        row = QHBoxLayout()
        self.ed_folder = QLineEdit(window._torrent_folder())
        row.addWidget(self.ed_folder, 1)
        b_br = QPushButton("Browse…")
        b_br.setStyleSheet(self._btn_qss())
        b_br.clicked.connect(self._browse)
        row.addWidget(b_br)
        lay.addLayout(row)

        self.chk_folder = QCheckBox("Use this folder for every torrent from now on")
        lay.addWidget(self.chk_folder)

        self.chk_always = QCheckBox(
            "Always do this, don't ask again  (Settings ▸ Torrents changes it back)")
        lay.addWidget(self.chk_always)

        lnk = QLabel(link)
        lnk.setWordWrap(True)
        lnk.setStyleSheet("color:%s; font-size:7pt;" % C_STATUS_FG)
        lay.addWidget(lnk)

        lay.addStretch(1)
        brow = QHBoxLayout()
        brow.addStretch(1)
        b_ign = QPushButton("Ignore this one")
        b_ign.setStyleSheet(self._btn_qss())
        b_ign.clicked.connect(self.reject)
        brow.addWidget(b_ign)
        b_go = QPushButton("🧲  Go")
        b_go.setDefault(True)
        b_go.setStyleSheet(
            "QPushButton{background:%s; color:%s; border:none; padding:6px 18px;"
            "border-radius:6px; font-weight:bold;}QPushButton:hover{background:%s;}"
            % (C_ACCENT, C_ACCENT_FG, C_ACCENT_HOV))
        b_go.clicked.connect(self.accept)
        brow.addWidget(b_go)
        lay.addLayout(brow)

    @staticmethod
    def _btn_qss():
        return ("QPushButton{background:%s; color:%s; border:none; padding:6px 14px;"
                "border-radius:6px;}QPushButton:hover{background:%s;}"
                % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))

    def _browse(self):
        start = self.ed_folder.text().strip() or os.path.expanduser("~")
        d = QFileDialog.getExistingDirectory(self, "Folder for this torrent", start)
        if d:
            self.ed_folder.setText(d)

    def get(self):
        """Modal. Returns {"action","folder","always","set_folder"} or None."""
        if self.exec() != QDialog.DialogCode.Accepted:
            return None
        return {"action": self.cmb_action.currentData() or "download",
                "folder": self.ed_folder.text().strip(),
                "always": self.chk_always.isChecked(),
                "set_folder": self.chk_folder.isChecked()}

    def keyPressEvent(self, e):
        if e.key() == Qt.Key.Key_Escape:
            self.reject()
        else:
            super().keyPressEvent(e)


# ---------------------------------------------------------------------------
#  The Torrents window
# ---------------------------------------------------------------------------
class TorrentManagerDialog(QDialog):
    """Everything that is downloading, with the controls for it.

    A WINDOW IN ITS OWN RIGHT, not a dialog stuck on top of the browser. That
    distinction is the whole point of the two odd-looking lines below: on
    Windows a window that HAS a parent is always kept above that parent by the
    window manager, whatever you click - so a parented Torrents window would
    sit permanently in front of the page you are trying to read. Passing no
    parent, plus the plain Window flag, makes it an ordinary window: it can go
    behind WhyBrowse, it has its own taskbar button, and Alt+Tab treats it like
    anything else. (The browser still closes it on the way out - see
    Browser.closeEvent - so nothing is left running with no window to show it.)
    """

    COLS = ["Name", "Size", "Done", "Down", "Up", "Peers", "Left", "Status", "Folder"]

    def __init__(self, window):
        super().__init__(None)                       # NO parent - see above
        self.setWindowFlags(Qt.WindowType.Window)    # a normal window, not a dialog
        self.win = window
        self.setWindowTitle(APP_NAME + " - Torrents")
        self.setModal(False)
        # Remember where it was and how big it was last time.
        geo = window.settings.get("torrent_window", {}) or {}
        self.resize(int(geo.get("w") or 1000), int(geo.get("h") or 520))
        if geo.get("x") is not None and geo.get("y") is not None:
            self.move(int(geo["x"]), int(geo["y"]))
        # ToDo (2026-10-27): a saved position can lie off the screen (it was
        # y=1293 on a 1080 screen) and then the window exists but can never be
        # reached. Pull it back on-screen every time it is created.
        fit_to_screen(self)
        self.setStyleSheet(dialog_qss())
        apply_window_icon(self)

        lay = QVBoxLayout(self)

        v = libtorrent_version()
        self.lbl_engine = QLabel("")
        self.lbl_engine.setWordWrap(True)
        self.lbl_engine.setStyleSheet("color:%s; font-size:9pt;" % C_STATUS_FG)
        if v:
            self.lbl_engine.setText(
                "Engine: libtorrent %s   ·   torrent folder: %s   ·   a finished "
                "torrent is paused unless \"keep seeding\" is on (Settings ▸ Torrents)."
                % (v, window._torrent_folder()))
        else:
            self.lbl_engine.setText(
                "The built-in engine (libtorrent) is NOT installed, so nothing can "
                "download here yet. Install it once with:   pip install libtorrent   "
                "— then reopen this window. Saving links as .magnet files and "
                "handing them to your own torrent program work without it.")
        lay.addWidget(self.lbl_engine)

        # ---- add a link by hand ----
        row_add = QHBoxLayout()
        self.ed_add = QLineEdit()
        self.ed_add.setPlaceholderText("Paste a magnet:… link here")
        self.ed_add.returnPressed.connect(self._add_typed)
        row_add.addWidget(self.ed_add, 1)
        for txt, fn in (("➕  Add", self._add_typed),
                        ("📄  Add .torrent file…", self._add_file)):
            b = QPushButton(txt)
            b.setStyleSheet(self._btn_qss())
            b.clicked.connect(fn)
            row_add.addWidget(b)
        lay.addLayout(row_add)

        self.tree = QTreeWidget()
        self.tree.setHeaderLabels(self.COLS)
        self.tree.setRootIsDecorated(False)
        self.tree.setAlternatingRowColors(False)
        self.tree.setStyleSheet(
            "QTreeWidget{background:%s; border:1px solid %s; border-radius:6px;}"
            "QTreeWidget::item{padding:4px;}"
            "QTreeWidget::item:selected{background:%s; color:%s;}"
            % (C_ADDR_BG, C_BORDER, C_ACCENT, C_ACCENT_FG) + scrollbar_qss())
        self.tree.itemDoubleClicked.connect(lambda *_: self._open_folder())
        lay.addWidget(self.tree, 1)

        row_tot = QHBoxLayout()
        self.lbl_tot = QLabel("")
        self.lbl_tot.setStyleSheet("color:%s; font-size:9pt;" % C_STATUS_FG)
        row_tot.addWidget(self.lbl_tot)
        row_tot.addStretch(1)
        # Saved the moment you tick it (it is also in Settings ▸ Torrents), so
        # the choice is made where you actually notice it: in this window.
        self.chk_auto = QCheckBox("Close this window when everything has finished")
        self.chk_auto.setChecked(bool(window.settings.get("torrent_autoclose", False)))
        self.chk_auto.toggled.connect(self._toggle_autoclose)
        row_tot.addWidget(self.chk_auto)
        lay.addLayout(row_tot)

        row = QHBoxLayout()
        for txt, fn in (("⏸  Pause", self._pause), ("▶  Resume", self._resume),
                        ("📂  Open folder", self._open_folder),
                        ("⎘  Copy link", self._copy_link),
                        ("🗑  Remove (keep files)", lambda: self._remove(False)),
                        ("🗑  Remove + delete files", lambda: self._remove(True)),
                        ("⚙  Settings…", self._settings),
                        ("Close", self.close)):
            b = QPushButton(txt)
            b.setStyleSheet(self._btn_qss())
            b.clicked.connect(fn)
            row.addWidget(b)
        lay.addLayout(row)

        self._eng = window.torrent_engine(create=False)
        self._last_count = -1
        self._had_active = False        # was anything ever actually running?
        self._closing = False           # auto-close already on its way
        if self._eng is not None:
            self._eng.changed.connect(self._refresh)
        self._refresh()

    @staticmethod
    def _btn_qss():
        return ("QPushButton{background:%s; color:%s; border:none; padding:6px 12px;"
                "border-radius:6px;}QPushButton:hover{background:%s;}"
                % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))

    # ---- list ------------------------------------------------------------
    def _rows(self):
        eng = self.win.torrent_engine(create=False)
        return eng.rows() if eng is not None else []

    def _refresh(self):
        rows = self._rows()
        keep = self.tree.currentIndex().row()
        self.tree.clear()
        tot_d = tot_u = 0
        for it in rows:
            pct = "%.1f %%" % (it.get("progress", 0.0) * 100.0)
            node = QTreeWidgetItem([
                it.get("name") or torrent_link_title(it.get("uri", "")),
                _t_size(it.get("size", 0)),
                pct,
                _t_rate(it.get("down", 0)),
                _t_rate(it.get("up", 0)),
                "%d (%d seeds)" % (it.get("peers", 0), it.get("seeds", 0)),
                it.get("eta", ""),
                it.get("status", ""),
                it.get("folder", ""),
            ])
            self.tree.addTopLevelItem(node)
            tot_d += it.get("down", 0)
            tot_u += it.get("up", 0)
        # Only re-measure the columns when the LIST changes. Doing it on every
        # one-second update makes the columns twitch while you try to click.
        if len(rows) != self._last_count:
            self._last_count = len(rows)
            for i in range(len(self.COLS)):
                self.tree.resizeColumnToContents(i)
        if 0 <= keep < self.tree.topLevelItemCount():
            self.tree.setCurrentItem(self.tree.topLevelItem(keep))
        if rows:
            self.lbl_tot.setText("%d torrent%s   ·   down %s   ·   up %s"
                                 % (len(rows), "" if len(rows) == 1 else "s",
                                    _t_rate(tot_d) or "0", _t_rate(tot_u) or "0"))
        else:
            self.lbl_tot.setText("Nothing here yet. Paste a magnet link above, or "
                                 "click one on a page.")

        # ---- "close when everything has finished" -------------------------
        # Only ever closes a window that had something RUNNING in it: opening
        # the window on a list of already-finished torrents (or an empty one)
        # must not make it shut itself in your face.
        if rows and any(not r.get("done") for r in rows):
            self._had_active = True
        elif (rows and self._had_active and not self._closing
                and self.chk_auto.isChecked()):
            self._closing = True
            show_toast(self.win, "🧲  All torrents finished — closing the window")
            QTimer.singleShot(2500, self.close)

    def _selected(self):
        i = self.tree.currentIndex().row()
        rows = self._rows()
        return rows[i] if 0 <= i < len(rows) else None

    # ---- actions ---------------------------------------------------------
    def _add_typed(self):
        text = self.ed_add.text().strip()
        if not text:
            return
        if not is_torrent_link(text):
            QMessageBox.information(self, "Add torrent",
                                    "That is not a magnet link or a .torrent address.")
            return
        self.ed_add.clear()
        self.win.handle_torrent_link(text, source="the Torrents window",
                                     force_action="download")
        self._refresh()

    def _add_file(self):
        start = self.win._torrent_folder()
        path, _f = QFileDialog.getOpenFileName(self, "Open a .torrent file", start,
                                               "Torrent files (*.torrent);;All files (*)")
        if not path:
            return
        eng = self.win.torrent_engine()
        ok, msg = eng.add_torrent_file(path, self.win._torrent_folder())
        if not ok:
            QMessageBox.warning(self, "Add torrent", msg)
        self._refresh()

    def _pause(self):
        it = self._selected()
        if it:
            self.win.torrent_engine().pause(it)

    def _resume(self):
        it = self._selected()
        if it:
            self.win.torrent_engine().resume(it)

    def _open_folder(self):
        it = self._selected()
        if not it:
            return
        path = it.get("folder") or ""
        if os.path.isdir(path):
            try:
                open_path(path)
            except Exception:
                show_toast(self.win, "Folder: %s" % path)

    def _copy_link(self):
        it = self._selected()
        if it and it.get("uri"):
            QApplication.clipboard().setText(it["uri"])
            show_toast(self.win, "Magnet link copied")

    def _remove(self, delete_files):
        it = self._selected()
        if not it:
            return
        name = it.get("name") or "this torrent"
        if delete_files:
            q = QMessageBox.question(
                self, "Remove torrent",
                "Remove \"%s\" AND delete the files it has already written to\n%s ?"
                % (name, it.get("folder", "")),
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
                QMessageBox.StandardButton.No)
            if q != QMessageBox.StandardButton.Yes:
                return
        self.win.torrent_engine().remove(it, delete_files=delete_files)
        self._refresh()

    def _settings(self):
        self.win.open_settings()
        # The Settings page carries the same switch - show what it says now.
        try:
            self.chk_auto.blockSignals(True)
            self.chk_auto.setChecked(bool(self.win.settings.get("torrent_autoclose", False)))
            self.chk_auto.blockSignals(False)
        except Exception:
            pass

    def _toggle_autoclose(self, on):
        self.win.settings["torrent_autoclose"] = bool(on)
        save_json(SETTINGS_FILE, self.win.settings)

    def closeEvent(self, e):
        # Let go of the engine's signal: a closed window that keeps rebuilding
        # its list once a second is both waste and, once Qt has deleted the
        # widgets underneath it, a crash waiting to happen.
        try:
            if self._eng is not None:
                self._eng.changed.disconnect(self._refresh)
        except Exception:
            pass
        self._eng = None
        # Remember size and position for next time (the house rule for every
        # window in this program).
        try:
            g = self.geometry()
            self.win.settings["torrent_window"] = {
                "x": g.x(), "y": g.y(), "w": g.width(), "h": g.height()}
            save_json(SETTINGS_FILE, self.win.settings)
        except Exception as ex:
            log_line("torrent window geometry not saved: %s" % ex)
        super().closeEvent(e)

    def keyPressEvent(self, e):
        if e.key() == Qt.Key.Key_Escape:
            self.close()
        else:
            super().keyPressEvent(e)


# ============================================================================
#  DEL 12J - SNIPPET MANAGER  (view/add/remove saved words; ESC closes)
# ----------------------------------------------------------------------------
#  A tree of every saved word grouped by scope: All sites / each Profile / each
#  Domain. Select a word + Remove, or Add a new one to a chosen scope.
# ============================================================================
class SnippetManagerDialog(QDialog):
    def __init__(self, window):
        super().__init__(window)
        self.win = window
        self.setWindowTitle(APP_NAME + " - Saved words / snippets")
        self.setModal(True)
        self.resize(560, 560)
        self.setStyleSheet(dialog_qss())
        apply_window_icon(self)
        QShortcut(QKeySequence("Esc"), self, self.close)

        lay = QVBoxLayout(self)
        hint = QLabel("Words you saved for re-use. Right-click a text field on a page to "
                      "insert them with the mouse. Select one here and press Remove, or Add "
                      "a new one.\n"
                      "⭐ Pin your favourites — they sit at the very top of the right-click "
                      "menu (above the “This site” folder). Use ▲ ▼ to set their order.")
        hint.setWordWrap(True)
        hint.setStyleSheet("color:%s; font-size:9pt;" % C_STATUS_FG)
        lay.addWidget(hint)

        self.tree = QTreeWidget()
        self.tree.setHeaderHidden(True)
        self.tree.itemDoubleClicked.connect(lambda *_: self._toggle_fav())
        lay.addWidget(self.tree, 1)
        self._reload_tree()

        row = QHBoxLayout()

        def btn(txt, fn, tip=""):
            b = QPushButton(txt)
            b.clicked.connect(fn)
            if tip:
                b.setToolTip(tip)
            return b
        row.addWidget(btn("➕  Add word...", self._add))
        row.addWidget(btn("✎  Edit...", self._edit,
                          "Change the selected word / phrase (fix a typo or a "
                          "phrase that got split)"))
        row.addWidget(btn("🗑  Remove selected", self._remove))
        row.addWidget(btn("⭐  Pin / unpin", self._toggle_fav,
                          "Pin the selected word to the top of the menu "
                          "(double-click a word does the same)"))
        row.addWidget(btn("▲", self._fav_up, "Move favourite up"))
        row.addWidget(btn("▼", self._fav_down, "Move favourite down"))
        row.addStretch(1)
        close = btn("Close", self.close)
        row.addWidget(close)
        lay.addLayout(row)

    def _reload_tree(self):
        self.tree.clear()
        store = self.win._snip_store()
        favs = self.win._snip_favs()

        def group(title, words, scope, host=""):
            top = QTreeWidgetItem([title])
            top._scope = None
            self.tree.addTopLevelItem(top)
            for w in words:
                # Mark pinned words with a ⭐ everywhere they appear.
                label = ("⭐  " + w) if (scope != "fav" and w in favs) else w
                it = QTreeWidgetItem([label])
                it._scope = scope
                it._host = host
                it._word = w
                top.addChild(it)
            top.setExpanded(True)

        if favs:
            group("⭐  Favourites  (pinned to top of the menu — ▲▼ to reorder)",
                  favs, "fav")
        group("✳  All sites", store.get("global", []), "global")
        for pid, words in store.get("profiles", {}).items():
            if words:
                prof = self.win._profile_by_id(pid)
                name = prof.get("name", pid) if prof else pid
                group("👤  Profile: %s" % name, words, "profile_%s" % pid)
        for host, words in store.get("domains", {}).items():
            if words:
                group("🌐  %s" % host, words, "domain", host)

    def _add(self):
        scopes = ["All sites", "This profile (%s)"
                  % self.win._active_profile().get("name", "?")]
        # Offer the current page's domain too, if any.
        cur = self.win.current_view()
        host = clean_host(cur.url().host()) if cur else ""
        if host:
            scopes.append("Domain: %s" % host)
        choice, ok = QInputDialog.getItem(self, "Add word", "Save for:", scopes, 0, False)
        if not ok:
            return
        res = self.win._ask_words("Add word(s)", "Word(s) to save:")
        if not res:
            return
        text, split = res
        if choice.startswith("All"):
            self.win._snip_add_many("global", "", text, split)
        elif choice.startswith("This profile"):
            self.win._snip_add_many("profile", "", text, split)
        else:
            self.win._snip_add_many("domain", host, text, split)
        self._reload_tree()

    def _remove(self):
        it = self.tree.currentItem()
        if not it or getattr(it, "_scope", None) is None:
            return
        scope = it._scope
        if scope == "fav":
            # In the Favourites group, "Remove" just un-pins (the word still
            # lives in its real scope below).
            self.win._snip_fav_toggle(it._word)
        elif scope == "global":
            self.win._snip_remove("global", "", it._word)
        elif scope.startswith("profile_"):
            pid = scope.split("_", 1)[1]
            lst = self.win._snip_store()["profiles"].get(pid, [])
            if it._word in lst:
                lst.remove(it._word)
                save_json(SETTINGS_FILE, self.win.settings)
        elif scope == "domain":
            self.win._snip_remove("domain", it._host, it._word)
        # A deleted word should not linger as a dangling favourite.
        if scope != "fav" and it._word in self.win._snip_favs():
            self.win._snip_fav_toggle(it._word)
        self._reload_tree()

    def _sel_item(self):
        it = self.tree.currentItem()
        if not it or getattr(it, "_scope", None) is None:
            return None
        return it

    def _edit(self):
        it = self._sel_item()
        if not it:
            return
        if it._scope == "fav":
            show_toast(self.win, "Edit a word in its own folder below "
                                 "(All sites / a profile / a site)")
            return
        old = it._word
        new, ok = QInputDialog.getText(self, "Edit word",
                                       "Word or phrase:", text=old)
        if not ok:
            return
        new = new.strip()
        if not new or new == old:
            return
        self.win._snip_rename(it._scope, getattr(it, "_host", ""), old, new)
        show_toast(self.win, "Updated")
        self._reload_tree()

    def _toggle_fav(self):
        it = self._sel_item()
        if not it:
            return
        pinned = self.win._snip_fav_toggle(it._word)
        self._reload_tree()
        show_toast(self.win, ("Pinned  ⭐ " if pinned else "Un-pinned  ")
                   + it._word[:24])

    def _fav_up(self):
        self._fav_move(-1)

    def _fav_down(self):
        self._fav_move(1)

    def _fav_move(self, delta):
        it = self._sel_item()
        if not it or it._scope != "fav":
            show_toast(self.win, "Select a word under ⭐ Favourites to reorder")
            return
        word = it._word
        self.win._snip_fav_move(word, delta)
        self._reload_tree()
        # Keep the moved word selected so ▲/▼ can be pressed repeatedly.
        fav_root = self.tree.topLevelItem(0)
        if fav_root is not None:
            for i in range(fav_root.childCount()):
                c = fav_root.child(i)
                if getattr(c, "_scope", None) == "fav" and c._word == word:
                    self.tree.setCurrentItem(c)
                    break


# *************** DEL 52 - FILE SETS: DRAG PANEL *****************
# For sites with no paperclip at all (a plain chat box that takes dropped files):
# a small always-on-top panel whose handle / list items are real file DRAG
# sources, so the files can be dropped straight onto the page.
def _start_file_drag(widget, files):
    """Start a drag of `files`. True if the drop was accepted by a target."""
    files = [f for f in files if os.path.isfile(f)]
    if not files:
        return False
    md = QMimeData()
    md.setUrls([QUrl.fromLocalFile(f) for f in files])
    d = QDrag(widget)
    d.setMimeData(md)
    return d.exec(Qt.DropAction.CopyAction) != Qt.DropAction.IgnoreAction


class _FileDragHandle(QLabel):
    """Press and drag: ALL the set's files leave as one drag."""
    def __init__(self, get_files, parent=None):
        super().__init__(parent)
        self._get = get_files
        self.on_dropped = None          # called after an accepted drop
        self._press = None
        self.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.setCursor(Qt.CursorShape.OpenHandCursor)
        self.setFixedHeight(70)
        self.setStyleSheet("border:2px dashed %s; border-radius:10px; font-size:11pt;"
                           % C_ACCENT)

    def mousePressEvent(self, ev):
        if ev.button() == Qt.MouseButton.LeftButton:
            self._press = ev.position().toPoint()

    def mouseMoveEvent(self, ev):
        if self._press is None or not (ev.buttons() & Qt.MouseButton.LeftButton):
            return
        if ((ev.position().toPoint() - self._press).manhattanLength()
                < QApplication.startDragDistance()):
            return
        self._press = None
        if _start_file_drag(self, self._get()) and self.on_dropped:
            self.on_dropped()

    def mouseReleaseEvent(self, ev):
        self._press = None


class _FileDragList(QListWidget):
    """Drag one file, or several selected ones, out of the list."""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection)
        self.setDragEnabled(True)
        self.on_dropped = None          # called after an accepted drop

    def startDrag(self, actions):
        sel = self.selectedItems() or []
        if (_start_file_drag(self, [it.data(Qt.ItemDataRole.UserRole) for it in sel])
                and self.on_dropped):
            self.on_dropped()


class FileSetDragPanel(QWidget):
    def __init__(self, window, name):
        super().__init__(window, Qt.WindowType.Tool
                         | Qt.WindowType.WindowStaysOnTopHint)
        self.win = window
        self.name = name
        self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose)
        self.setWindowTitle("📎  " + name[:40])
        self.setStyleSheet(dialog_qss())
        self.resize(360, 320)
        QShortcut(QKeySequence("Esc"), self, self.close)
        self.files, gone = window._fs_existing(name)

        lay = QVBoxLayout(self)
        handle = _FileDragHandle(lambda: self.files)
        handle.setText("✋  Drag all %d file%s from here\nonto the page (chat box)"
                       % (len(self.files), "" if len(self.files) == 1 else "s"))
        lay.addWidget(handle)
        if gone:
            warn = QLabel("⚠ %d file%s missing from the disk and left out"
                          % (gone, "" if gone == 1 else "s"))
            warn.setStyleSheet("color:%s; font-size:9pt;" % C_STATUS_FG)
            lay.addWidget(warn)
        lst = _FileDragList()
        for f in self.files:
            it = QListWidgetItem("📄  " + (os.path.basename(f) or f))
            it.setData(Qt.ItemDataRole.UserRole, f)
            it.setToolTip(f)
            lst.addItem(it)
        lay.addWidget(lst, 1)
        tip = QLabel("Or select some of the files above and drag just those.")
        tip.setWordWrap(True)
        tip.setStyleSheet("color:%s; font-size:9pt;" % C_STATUS_FG)
        lay.addWidget(tip)
        self.auto_close = QCheckBox("Close this panel after the files are dropped")
        self.auto_close.setToolTip("Untick to keep the panel open and drop the same "
                                   "files on several tabs")
        self.auto_close.setChecked(bool(window.settings.get("fileset_autoclose", True)))
        self.auto_close.toggled.connect(self._set_auto_close)
        lay.addWidget(self.auto_close)
        handle.on_dropped = self._dropped
        lst.on_dropped = self._dropped
        row = QHBoxLayout()
        b1 = QPushButton("📎  Attach-button mode")
        b1.setToolTip("Instead of dragging: the next file dialog on any site is "
                      "answered with these files")
        b1.clicked.connect(lambda: window._fs_use(name))
        b2 = QPushButton("📋  Copy")
        b2.setToolTip("Put the files on the clipboard (Ctrl+V into a chat box)")
        b2.clicked.connect(lambda: window._fs_copy(name))
        b3 = QPushButton("Close")
        b3.clicked.connect(self.close)
        row.addWidget(b1)
        row.addWidget(b2)
        row.addStretch(1)
        row.addWidget(b3)
        lay.addLayout(row)

    def _set_auto_close(self, on):
        self.win.settings["fileset_autoclose"] = bool(on)
        save_json(SETTINGS_FILE, self.win.settings)

    def _dropped(self):
        if self.auto_close.isChecked():
            QTimer.singleShot(0, self.close)


# *************** DEL 52 - FILE SETS: MANAGER DIALOG *****************
# ToDo: a file set is a NAMED LIST OF PATHS kept in settings.json ("file_sets").
#       The files themselves are never copied, moved or deleted by WhyBrowse.
class FileSetManagerDialog(QDialog):
    def __init__(self, window):
        super().__init__(window)
        self.win = window
        self.setWindowTitle(APP_NAME + " - File sets")
        self.setModal(True)
        self.resize(640, 560)
        self.setStyleSheet(dialog_qss())
        apply_window_icon(self)
        QShortcut(QKeySequence("Esc"), self, self.close)

        lay = QVBoxLayout(self)
        hint = QLabel("Named groups of files you attach again and again, e.g. the three "
                      "instruction files you give every AI. Double-click a set to open "
                      "the DRAG panel (drop the files onto any chat box), or press "
                      "Attach-button mode and the next file dialog on ANY site is "
                      "answered with these files.\n"
                      "Removing a set or a file here only takes it off this list; "
                      "nothing is ever deleted from the disk.")
        hint.setWordWrap(True)
        hint.setStyleSheet("color:%s; font-size:9pt;" % C_STATUS_FG)
        lay.addWidget(hint)

        self.tree = QTreeWidget()
        self.tree.setHeaderHidden(True)
        self.tree.itemDoubleClicked.connect(lambda *_: self._drag())
        lay.addWidget(self.tree, 1)

        def btn(txt, fn, tip=""):
            b = QPushButton(txt)
            b.clicked.connect(fn)
            if tip:
                b.setToolTip(tip)
            return b
        row1 = QHBoxLayout()
        row1.addWidget(btn("➕  New set...", self._new))
        row1.addWidget(btn("📄  Add files...", self._add_files,
                           "Add more files to the selected set"))
        row1.addWidget(btn("✎  Rename...", self._rename))
        row1.addWidget(btn("🗑  Remove", self._remove,
                           "Remove the selected file - or the whole set if a set is "
                           "selected - from this list (the disk is not touched)"))
        row1.addWidget(btn("▲", lambda: self._move(-1), "Move the set up"))
        row1.addWidget(btn("▼", lambda: self._move(1), "Move the set down"))
        row1.addStretch(1)
        lay.addLayout(row1)
        row2 = QHBoxLayout()
        row2.addWidget(btn("✋  Drag panel", self._drag,
                           "Open a panel to drag the files onto a page (chat boxes "
                           "that take dropped files)"))
        row2.addWidget(btn("📎  Attach-button mode", self._use,
                           "Arm this set: the next file dialog on any site gets these files"))
        row2.addWidget(btn("📋  Copy to clipboard", self._copy,
                           "Put the files on the clipboard so Ctrl+V pastes them into "
                           "a chat box that accepts pasted files"))
        row2.addStretch(1)
        row2.addWidget(btn("Close", self.close))
        lay.addLayout(row2)
        self._reload()

    def _sets(self):
        return self.win._fs_sets()

    def _reload(self, select=None):
        self.tree.clear()
        keep = None
        for i, s in enumerate(self._sets()):
            files = s.get("files", [])
            top = QTreeWidgetItem(["📎  %s   (%d file%s)"
                                   % (s.get("name", "?"), len(files),
                                      "" if len(files) == 1 else "s")])
            top._si = i
            top._fi = None
            self.tree.addTopLevelItem(top)
            for j, f in enumerate(files):
                gone = not os.path.isfile(f)
                it = QTreeWidgetItem(["%s%s" % (os.path.basename(f) or f,
                                                "     ⚠ missing" if gone else "")])
                it.setToolTip(0, f)
                it._si = i
                it._fi = j
                top.addChild(it)
            top.setExpanded(True)
            if select == i:
                keep = top
        if keep is not None:
            self.tree.setCurrentItem(keep)

    def _cur(self):
        it = self.tree.currentItem()
        if it is None or not hasattr(it, "_si"):
            return None, None
        return it._si, it._fi

    def _new(self):
        name, ok = QInputDialog.getText(
            self, "New file set",
            "Name of the set  (e.g. Instruction - Paperdoll):")
        name = (name or "").strip()
        if not ok or not name:
            return
        files = self.win._fs_pick_files(self, "Pick the files for “%s”" % name)
        if not files:
            return
        self.win._fs_add_set(name, files)
        self._reload(len(self._sets()) - 1)

    def _add_files(self):
        si, _fi = self._cur()
        if si is None:
            show_toast(self.win, "Select a set first")
            return
        files = self.win._fs_pick_files(self, "Add files to “%s”"
                                        % self._sets()[si].get("name", "?"))
        if not files:
            return
        cur = self._sets()[si].setdefault("files", [])
        for f in files:
            if f not in cur:
                cur.append(f)
        self.win._fs_save()
        self._reload(si)

    def _rename(self):
        si, _fi = self._cur()
        if si is None:
            return
        old = self._sets()[si].get("name", "")
        new, ok = QInputDialog.getText(self, "Rename set", "Name:", text=old)
        new = (new or "").strip()
        if not ok or not new or new == old:
            return
        self._sets()[si]["name"] = new
        self.win._fs_save()
        self._reload(si)

    def _remove(self):
        si, fi = self._cur()
        if si is None:
            return
        s = self._sets()[si]
        if fi is not None:
            files = s.get("files", [])
            if 0 <= fi < len(files):
                del files[fi]
            self.win._fs_save()
            self._reload(si)
            return
        if QMessageBox.question(
                self, "Remove file set",
                "Remove “%s” from WhyBrowse?\n\nThe %d file(s) on the disk are not "
                "touched." % (s.get("name", "?"), len(s.get("files", [])))
        ) != QMessageBox.StandardButton.Yes:
            return
        del self._sets()[si]
        self.win._fs_save()
        self._reload()

    def _move(self, delta):
        si, _fi = self._cur()
        sets = self._sets()
        if si is None or not (0 <= si + delta < len(sets)):
            return
        sets[si], sets[si + delta] = sets[si + delta], sets[si]
        self.win._fs_save()
        self._reload(si + delta)

    def _use(self):
        si, _fi = self._cur()
        if si is None:
            return
        name = self._sets()[si].get("name", "")
        self.close()
        self.win._fs_use(name)

    def _drag(self):
        si, _fi = self._cur()
        if si is None:
            return
        name = self._sets()[si].get("name", "")
        self.close()
        self.win._fs_open_panel(name)

    def _copy(self):
        si, _fi = self._cur()
        if si is None:
            return
        self.win._fs_copy(self._sets()[si].get("name", ""))


# ============================================================================
#  DEL 40 - BUG REPORTER  (save current context + activity trail + a comment)
# ============================================================================
class BugReportDialog(QDialog):
    """Save a bug report: the current profile / tab / page, the recent activity
    trail and your own comment, written to a file in
    Helpfiles/WhyBrowse/bug_reports so the exact what / when / how can be
    reviewed later. Nothing is sent anywhere; no passwords are included."""
    def __init__(self, window):
        super().__init__(window)
        self.win = window
        self.setWindowTitle(APP_NAME + " - Report a bug")
        self.setModal(True)
        self.resize(740, 660)
        self.setStyleSheet(dialog_qss())
        apply_window_icon(self)
        QShortcut(QKeySequence("Esc"), self, self.reject)

        lay = QVBoxLayout(self)
        intro = QLabel(
            "Something wrong on this page — only a few items show, it won't "
            "scroll, something looks broken? Describe what you see below and "
            "press Save. The current profile, tab, page and the recent activity "
            "trail are written to a file. Nothing is sent anywhere, and no "
            "passwords are included.")
        intro.setWordWrap(True)
        lay.addWidget(intro)

        def _bold(txt):
            l = QLabel(txt)
            l.setStyleSheet("font-weight:bold; margin-top:6px;")
            lay.addWidget(l)

        _bold("Context (saved automatically)")
        cbox = QPlainTextEdit()
        cbox.setReadOnly(True)
        cbox.setPlainText(self.win._bug_context_text())
        cbox.setMaximumHeight(150)
        cbox.setStyleSheet(scrollbar_qss())
        lay.addWidget(cbox)

        _bold("What did you experience?  (what you did · what went wrong)")
        self.comment = QPlainTextEdit()
        self.comment.setPlaceholderText(
            "e.g. Switched to profile X → opened Tradera; only ~5 ads showed "
            "and the page would not scroll. A reload did / did not fix it.")
        self.comment.setStyleSheet(scrollbar_qss())
        lay.addWidget(self.comment, 1)

        _bold("Recent activity (included in the report)")
        trail = QPlainTextEdit()
        trail.setReadOnly(True)
        trail.setPlainText(self.win._activity_trail_text(80))
        trail.setMaximumHeight(160)
        trail.setStyleSheet(scrollbar_qss())
        lay.addWidget(trail)

        row = QHBoxLayout()
        row.addStretch(1)
        cancel = QPushButton("Cancel")            # normal colour: theme button
        cancel.clicked.connect(self.reject)
        save = QPushButton("💾  Save report")
        save.clicked.connect(lambda: self._save(False))
        save_open = QPushButton("💾  Save && open folder")
        save_open.clicked.connect(lambda: self._save(True))
        row.addWidget(cancel)
        row.addWidget(save)
        row.addWidget(save_open)
        lay.addLayout(row)
        self.comment.setFocus()

    def _save(self, open_folder):
        path = self.win._write_bug_report(self.comment.toPlainText())
        if not path:
            show_toast(self.win, "Could not save the report")
            return
        if open_folder:
            try:
                folder = os.path.dirname(path)
                if platform.system() == "Windows":
                    open_path(folder)          # noqa: (Windows only)
                elif platform.system() == "Darwin":
                    subprocess.Popen(["open", folder])
                else:
                    subprocess.Popen(["xdg-open", folder])
            except Exception:
                pass
        show_toast(self.win, "Bug report saved  ✔")
        self.accept()


# ============================================================================
#  DEL 41 - PROFILES OVERVIEW / STATS  (every profile's live tabs, quick-set
#           flags, and per-tab memory / CPU with a running total)
# ============================================================================
class ProfilesOverviewDialog(QDialog):
    """A dashboard across ALL live profiles: each profile's open tabs with
    one-click Pin / Auto-refresh / Lock / No-sleep checkboxes,
    plus per-tab memory and CPU (needs psutil) and a running total. Memory /
    CPU refresh on a timer while the window is open."""
    def __init__(self, window):
        super().__init__(window)
        self.win = window
        self.setWindowTitle(APP_NAME + " - Profiles overview")
        self.setModal(False)                      # let you watch it while browsing
        self.resize(940, 640)
        self.setStyleSheet(dialog_qss())
        apply_window_icon(self)
        QShortcut(QKeySequence("Esc"), self, self.close)

        self._ps_cache = {}                       # pid -> psutil.Process
        self._rows = []                           # [(view, ram_lbl, cpu_lbl)]

        outer = QVBoxLayout(self)
        head = QLabel("All your profiles are listed. A profile shows its tabs "
                      "once it has been opened this session (its tabs are then "
                      "kept alive in the background) — you do NOT need to switch "
                      "to a profile to manage it here, only to have opened it "
                      "once. Profiles you haven't opened yet appear greyed with "
                      "no tabs. Tick a box to set that tab's behaviour instantly.")
        head.setWordWrap(True)
        outer.addWidget(head)

        if psutil is None:
            warn = QFrame()
            warn.setStyleSheet("background:#3a2b18; border-radius:6px;")
            wl = QHBoxLayout(warn)
            msg = QLabel("Memory / CPU columns need the “psutil” package "
                         "(pip install psutil). They are hidden until it is "
                         "installed.")
            msg.setWordWrap(True)
            wl.addWidget(msg, 1)
            cpy = QPushButton("Copy pip command")
            cpy.clicked.connect(lambda: (
                QApplication.clipboard().setText("pip install psutil"),
                show_toast(self.win, "Copied: pip install psutil")))
            wl.addWidget(cpy)
            outer.addWidget(warn)

        # ---- Sticky column legend -----------------------------------------
        # Lives OUTSIDE the scroll area below, so it never scrolls out of
        # view: whichever profile you've scrolled down to, Pin / Refresh /
        # Lock / Sleep / Awake are always in this same spot at the top. The
        # per-profile header rows further down (inside the scroll area) are
        # the interactive ones — click a column name there to set/clear it
        # for that WHOLE profile at once.
        legend = self._row_frame()
        lg = QHBoxLayout(legend)
        lg.setContentsMargins(6, 4, 6, 4)
        lg.setSpacing(0)
        lg_nm = self._hlabel("Columns:")
        lg_nm.setFixedWidth(self.NAME_W)
        lg.addWidget(lg_nm)
        for key, label, w in self._columns():
            lg.addWidget(self._cell(self._hlabel(label, center=True), w))
        if psutil is not None:
            lg.addWidget(self._cell(self._hlabel("Memory", center=True), self.STAT_W))
            lg.addWidget(self._cell(self._hlabel("CPU", center=True), self.CPU_W))
        lg.addStretch(1)
        outer.addWidget(legend)
        # ---------------------------------------------------------------------

        # Scroll area holding the per-profile grid.
        self.scroll = QScrollArea()
        self.scroll.setWidgetResizable(True)
        self.scroll.setStyleSheet(scrollbar_qss())
        self.body = QWidget()
        self.grid = QVBoxLayout(self.body)
        self.grid.setContentsMargins(2, 2, 2, 2)
        self.scroll.setWidget(self.body)
        outer.addWidget(self.scroll, 1)

        self.total_lbl = QLabel("")
        self.total_lbl.setStyleSheet("font-weight:bold; padding:4px;")
        outer.addWidget(self.total_lbl)

        row = QHBoxLayout()
        note = QLabel("Tabs on the same site can share one process, so per-tab "
                      "memory may repeat; the total counts each process once.")
        note.setStyleSheet("color:%s; font-size:8pt;" % C_STATUS_FG)
        note.setWordWrap(True)
        row.addWidget(note, 1)
        rebuild = QPushButton("↻  Rebuild list")
        rebuild.clicked.connect(self._rebuild_clicked)
        close = QPushButton("Close")
        close.clicked.connect(self.close)
        row.addWidget(rebuild)
        row.addWidget(close)
        outer.addLayout(row)

        self._last_sig = None
        self._build()
        # Tick every 2 s: refresh memory / CPU, and auto-rebuild the list if the
        # set of profiles / tabs changed underneath (you opened a profile, closed
        # a tab, switched profile) - so it stays current without pressing Rebuild.
        self._timer = QTimer(self)
        self._timer.timeout.connect(self._tick)
        self._timer.start(2000)

    def _rebuild_clicked(self):
        self._build()
        show_toast(self.win, "Overview rebuilt")

    def _structure_sig(self):
        """A cheap signature of the current profiles/tabs, so the timer can tell
        when the list needs rebuilding (vs. only its numbers refreshing)."""
        try:
            # frozenset of ids => reordering tabs (e.g. pinning) does NOT count
            # as a structural change, so a checkbox toggle never yanks a rebuild.
            return tuple((g["pid"], frozenset(id(v) for v in g["views"]))
                         for g in self.win._all_profile_views())
        except Exception:
            return None

    def _tick(self):
        if self._structure_sig() != self._last_sig:
            self._build()          # structure changed -> rebuild (resets _last_sig)
        else:
            self._refresh_stats()  # same tabs -> just update memory / CPU

    # ---- build the profile groups + tab rows ----
    def _build(self):
        # Clear existing widgets.
        while self.grid.count():
            it = self.grid.takeAt(0)
            w = it.widget()
            if w:
                w.deleteLater()
        self._rows = []

        groups = self.win._all_profile_views()
        n_live = sum(1 for g in groups if g["views"])
        for g in groups:
            is_empty = not g["views"]
            title = QLabel("%s  %s%s   —   %s"
                           % (g.get("badge", "👤") or "👤",
                              g["name"], "  ★ active" if g["active"] else "",
                              "%d tab(s)" % len(g["views"]) if not is_empty
                              else "not opened this session"))
            title.setStyleSheet(
                "font-weight:bold; font-size:11pt; padding:8px 4px 2px 4px; "
                "color:%s;" % (C_STATUS_FG if is_empty else C_ACCENT))
            self.grid.addWidget(title)

            # A profile with no live tabs has nothing per-tab to show yet.
            if is_empty:
                note = QLabel("       Open this profile once (its tabs are then "
                              "kept alive) to see and manage them here.")
                note.setStyleSheet("color:%s; font-style:italic; padding-left:4px;"
                                   % C_STATUS_FG)
                self.grid.addWidget(note)
                continue

            # Column header row. Uses the SAME fixed-width cells as the tab
            # rows below (via _cell), so every header sits exactly over its
            # checkbox / figure instead of drifting. Each column name is a
            # clickable "select ALL" button for THIS profile: click "Sleep"
            # here to set (or clear) Sleep for every tab in this profile in
            # one go, instead of ticking each row by hand.
            hdr = self._row_frame()
            hg = QHBoxLayout(hdr)
            hg.setContentsMargins(6, 0, 6, 0)
            hg.setSpacing(0)
            nm = self._hlabel("Tab")
            nm.setFixedWidth(self.NAME_W)
            hg.addWidget(nm)
            for key, label, w in self._columns():
                hg.addWidget(self._cell(
                    self._header_all_btn(key, label, g["views"]), w))
            if psutil is not None:
                hg.addWidget(self._cell(self._hlabel("Memory", center=True),
                                        self.STAT_W))
                hg.addWidget(self._cell(self._hlabel("CPU", center=True),
                                        self.CPU_W))
            hg.addStretch(1)
            self.grid.addWidget(hdr)

            for v in g["views"]:
                self.grid.addWidget(self._tab_row(v))

        self.grid.addStretch(1)
        self._last_sig = self._structure_sig()      # for auto-rebuild detection
        self._refresh_stats()

    def _row_frame(self):
        f = QFrame()
        f.setStyleSheet("QFrame{background:%s; border-radius:5px;}"
                        % shade(C_ADDR_BG, 8))
        return f

    # ---- shared column geometry (header + rows use the SAME cells) ----
    NAME_W = 300
    STAT_W = 84
    CPU_W  = 60

    def _columns(self):
        # (flag key, header text, column width) — one per checkbox column.
        return [("pin", "Pin", 50), ("autorefresh", "Refresh", 64),
                ("lock", "Lock", 50), ("nosleep", "No sleep", 68)]

    def _hlabel(self, text, center=False):
        l = QLabel(text)
        l.setStyleSheet("color:%s; font-size:8pt;" % C_STATUS_FG)
        if center:
            l.setAlignment(Qt.AlignmentFlag.AlignCenter)
        return l

    def _header_all_btn(self, key, label, views):
        """A per-profile column header that doubles as a 'select ALL' button:
        click it to set that flag ON for every tab in THIS profile if not all
        of them already have it, otherwise click again to clear it from all of
        them (e.g. click 'Sleep' to put a whole profile's tabs to sleep, click
        it again to wake them all)."""
        btn = QPushButton(label)
        btn.setFlat(True)
        btn.setCursor(Qt.CursorShape.PointingHandCursor)
        btn.setStyleSheet(
            "QPushButton{color:%s; font-size:8pt; border:none; "
            "background:transparent; padding:0;}"
            "QPushButton:hover{color:%s; text-decoration:underline;}"
            % (C_STATUS_FG, C_ACCENT))
        btn.setToolTip("Click: turn %s ON for every tab in this profile\n"
                       "(click again to turn it OFF for all of them)" % label)
        btn.clicked.connect(
            lambda _=False, k=key, lb=label, vs=views: self._toggle_all(k, lb, vs))
        return btn

    def _toggle_all(self, key, label, views):
        """Set (or clear) one flag for every tab of one profile at once."""
        if not views:
            return
        turn_on = not all(self._flag_state(v, key) for v in views)
        for v in views:
            if key == "lock":
                self.win._dash_set_flag(v, "lock", 1 if turn_on else 0)
            else:
                self.win._dash_set_flag(v, key, turn_on)
        self._build()
        show_toast(self.win, "%s: turned %s for all %d tab(s)"
                   % (label, "ON" if turn_on else "OFF", len(views)))

    def _cell(self, widget, width):
        """A fixed-width cell with its content centred, so a header label and
        the checkbox/figure beneath it share one column and line up exactly."""
        w = QWidget()
        w.setFixedWidth(width)
        hl = QHBoxLayout(w)
        hl.setContentsMargins(0, 0, 0, 0)
        hl.setSpacing(0)
        hl.addStretch(1)
        hl.addWidget(widget)
        hl.addStretch(1)
        return w

    def _flag_state(self, view, key):
        if key == "lock":
            try:
                return self.win._lock(view) > 0
            except Exception:
                return False
        attr = {"pin": "_pinned", "autorefresh": "_auto_refresh",
                "nosleep": "_no_sleep"}.get(key, "")
        return bool(getattr(view, attr, False))

    def _tab_row(self, view):
        f = self._row_frame()
        h = QHBoxLayout(f)
        h.setContentsMargins(6, 3, 6, 3)
        h.setSpacing(0)

        try:
            title = view.title() or "New Tab"
        except Exception:
            title = "?"
        try:
            host = clean_host(view.url().host())
        except Exception:
            host = ""
        name = QLabel((title[:44] + ("  ·  " + host if host else "")))
        name.setFixedWidth(self.NAME_W)
        try:
            name.setToolTip(view.url().toString())
        except Exception:
            pass
        h.addWidget(name)

        tips = {"pin": "Pin: keep this page; links open in new tabs",
                "autorefresh": "Reload this tab each time you switch to it (kept "
                               "loaded; throttled by the auto-refresh delay). "
                               "Auto-sleep already reloads on return, so you "
                               "rarely need both.",
                "lock": "Lock (level 1). Finer levels are in the tab's right-click menu.",
                "nosleep": "Keep this tab loaded: it is left out of auto-sleep. "
                           "Every tab sleeps when idle unless you tick this — "
                           "sleeping frees the tab's memory and reloads it "
                           "FRESH when you come back."}
        for key, label, w in self._columns():
            cb = QCheckBox()
            cb.setChecked(bool(self._flag_state(view, key)))
            cb.setToolTip(tips.get(key, ""))
            cb.stateChanged.connect(
                lambda st, v=view, fl=key: self._toggle(v, fl, st))
            h.addWidget(self._cell(cb, w))

        if psutil is not None:
            ram = QLabel("–")
            ram.setStyleSheet("color:%s;" % C_STATUS_FG)
            cpu = QLabel("–")
            cpu.setStyleSheet("color:%s;" % C_STATUS_FG)
            h.addWidget(self._cell(ram, self.STAT_W))
            h.addWidget(self._cell(cpu, self.CPU_W))
            self._rows.append((view, ram, cpu))
        else:
            self._rows.append((view, None, None))
        h.addStretch(1)
        return f

    def _toggle(self, view, flag, state):
        value = (state == Qt.CheckState.Checked.value) if isinstance(state, int) \
            else (state == Qt.CheckState.Checked)
        # For the Lock checkbox, value True means level 1, False means 0.
        if flag == "lock":
            self.win._dash_set_flag(view, "lock", 1 if value else 0)
        else:
            self.win._dash_set_flag(view, flag, bool(value))

    def _proc(self, view):
        """(pid, rss_bytes, cpu_pct) for a view's render process, or Nones."""
        if psutil is None:
            return (None, None, None)
        pid = 0
        try:
            pid = int(view.page().renderProcessPid())
        except Exception:
            pid = 0
        if not pid or pid <= 0:
            return (None, None, None)
        try:
            p = self._ps_cache.get(pid)
            if p is None:
                p = psutil.Process(pid)
                self._ps_cache[pid] = p
                p.cpu_percent(None)               # prime (first call returns 0.0)
            return (pid, p.memory_info().rss, p.cpu_percent(None))
        except Exception:
            self._ps_cache.pop(pid, None)
            return (pid, None, None)

    def _refresh_stats(self):
        if psutil is None:
            self.total_lbl.setText("Live tabs: %d" % len(self._rows))
            return
        seen = {}                                  # pid -> (rss, cpu) counted once
        ncpu = psutil.cpu_count() or 1
        for view, ram, cpu in self._rows:
            try:
                pid, rss, cpupct = self._proc(view)
            except Exception:
                pid = rss = cpupct = None
            if rss is None:
                ram.setText("–")
                cpu.setText("–")
                continue
            ram.setText("%.0f MB" % (rss / (1024 * 1024)))
            # Normalise CPU to whole-machine percent (psutil can exceed 100 per core).
            cpu.setText("%.0f%%" % (cpupct / ncpu))
            if pid not in seen:
                seen[pid] = (rss, cpupct / ncpu)
        tot_ram = sum(r for r, _ in seen.values())
        tot_cpu = sum(c for _, c in seen.values())
        self.total_lbl.setText(
            "Total (unique processes): %.0f MB · %.0f%% CPU · %d live tab(s) · "
            "%d process(es)"
            % (tot_ram / (1024 * 1024), tot_cpu, len(self._rows), len(seen)))

    def closeEvent(self, e):
        try:
            self._timer.stop()
        except Exception:
            pass
        # Let the parent forget us so re-opening builds a fresh, ticking window.
        try:
            if getattr(self.win, "_profiles_dlg", None) is self:
                self.win._profiles_dlg = None
        except Exception:
            pass
        super().closeEvent(e)


# ----------------------------------------------------------------------------
#  Custom page sizes - a MANUAL, PERMANENT zoom override per active profile
#  + domain/page (see Browser._zoom_store / _set_zoom_override / _saved_zoom_for).
#  Independent from the normal Ctrl +/- / Ctrl+scroll zoom, which stays a
#  simple, temporary per-session convenience and is never auto-saved.
# ----------------------------------------------------------------------------
class ZoomSizeDialog(QDialog):
    """'Set custom size' popup: drag to preview, choose page or domain, Save.
    The size then always applies on every future visit until removed here
    or in ZoomSizeManagerDialog."""
    def __init__(self, window, view):
        super().__init__(window)
        self.win = window
        self.view = view
        self._orig_zoom = view.zoomFactor()          # restored if cancelled
        qurl = view.url()
        self.host = clean_host(qurl.host())
        self.url = qurl.toString()

        self.setWindowTitle(APP_NAME + " - Custom page size")
        self.setModal(True)
        self.setStyleSheet(dialog_qss())
        apply_window_icon(self)
        self.resize(460, 0)
        QShortcut(QKeySequence("Esc"), self, self.reject)

        lay = QVBoxLayout(self)

        prof_name = self.win._active_profile().get("name", "this profile")
        info = QLabel("Profile: <b>%s</b>" % prof_name)
        info.setStyleSheet("color:%s; font-size:9pt;" % C_STATUS_FG)
        lay.addWidget(info)

        hint = QLabel("Drag to preview, choose page or domain below, then Save. "
                      "The size sticks forever until you remove it here.")
        hint.setWordWrap(True)
        hint.setStyleSheet("color:%s; font-size:9pt;" % C_STATUS_FG)
        lay.addWidget(hint)

        row = QHBoxLayout()
        row.addWidget(QLabel("Size:"))
        start_pct = max(25, min(500, int(round(self._orig_zoom * 100))))
        self.slider = QSlider(Qt.Orientation.Horizontal)
        self.slider.setRange(25, 500)
        self.slider.setValue(start_pct)
        row.addWidget(self.slider, 1)
        self.spin = QSpinBox()
        self.spin.setRange(25, 500)
        self.spin.setSuffix("%")
        self.spin.setValue(start_pct)
        row.addWidget(self.spin)
        lay.addLayout(row)
        self.slider.valueChanged.connect(self._on_value)
        self.spin.valueChanged.connect(self._on_value)

        row2 = QHBoxLayout()
        row2.addWidget(QLabel("Apply to:"))
        self.scope = QComboBox()
        dom_label = self.host or "(no domain here)"
        page_label = self.url if len(self.url) <= 64 else self.url[:61] + "..."
        self.scope.addItem("Whole domain  -  %s" % dom_label, "domain")
        self.scope.addItem("This page only  -  %s" % page_label, "page")
        self.scope.setEnabled(bool(self.host))
        row2.addWidget(self.scope, 1)
        lay.addLayout(row2)

        bucket = self.win._zoom_bucket()
        page_z = bucket["by_url"].get(self.url)
        host_z = bucket["by_host"].get(self.host) if self.host else None
        if page_z is not None or host_z is not None:
            line = QFrame()
            line.setFrameShape(QFrame.Shape.HLine)
            line.setStyleSheet("color:%s;" % C_BORDER)
            lay.addWidget(line)
            if host_z is not None:
                lay.addLayout(self._saved_row(
                    "Saved for this domain: %d%%" % int(round(host_z * 100)),
                    lambda: self._remove("domain")))
            if page_z is not None:
                lay.addLayout(self._saved_row(
                    "Saved for this page: %d%%" % int(round(page_z * 100)),
                    lambda: self._remove("page")))

        btns = QHBoxLayout()
        manage = QPushButton("Manage all...")
        manage.clicked.connect(self._open_manager)
        btns.addWidget(manage)
        btns.addStretch(1)
        cancel = QPushButton("Cancel")
        cancel.clicked.connect(self.reject)
        btns.addWidget(cancel)
        save = QPushButton("Save")
        save.setDefault(True)
        save.clicked.connect(self._save)
        btns.addWidget(save)
        lay.addLayout(btns)

    def _saved_row(self, text, remove_fn):
        r = QHBoxLayout()
        r.addWidget(QLabel(text), 1)
        b = QPushButton("Remove")
        b.clicked.connect(remove_fn)
        r.addWidget(b)
        return r

    def _on_value(self, pct):
        self.slider.blockSignals(True)
        self.spin.blockSignals(True)
        self.slider.setValue(pct)
        self.spin.setValue(pct)
        self.slider.blockSignals(False)
        self.spin.blockSignals(False)
        try:
            self.view.setZoomFactor(pct / 100.0)      # live preview on the page
        except Exception:
            pass

    def _save(self):
        if not self.host:
            show_toast(self.win, "No page to save a size for here")
            return
        per_page = (self.scope.currentData() == "page")
        self.win._set_zoom_override(self.view, self.spin.value() / 100.0, per_page)
        self.accept()

    def _remove(self, which):
        if which == "page":
            self.win._clear_zoom_override(self.url, True)
        else:
            self.win._clear_zoom_override(self.host, False)
        self.win._apply_saved_zoom(self.view)
        show_toast(self.win, "Removed")
        self.accept()

    def _open_manager(self):
        self.reject()
        self.win.open_zoom_size_manager()

    def reject(self):
        try:
            self.view.setZoomFactor(self._orig_zoom)  # undo the live preview
        except Exception:
            pass
        super().reject()


class ZoomSizeManagerDialog(QDialog):
    """Every manually-saved page/domain size, across all profiles, in one
    place, so they can be reviewed or deleted without hunting through each
    site. See ZoomSizeDialog for how a size gets saved in the first place."""
    def __init__(self, window):
        super().__init__(window)
        self.win = window
        self.setWindowTitle(APP_NAME + " - Manage custom page sizes")
        self.setModal(True)
        self.resize(560, 480)
        self.setStyleSheet(dialog_qss())
        apply_window_icon(self)
        QShortcut(QKeySequence("Esc"), self, self.close)

        lay = QVBoxLayout(self)
        hint = QLabel("Sizes saved by hand. They always override the normal zoom "
                      "on that page or domain. Select one and Remove, or clear "
                      "everything below.")
        hint.setWordWrap(True)
        hint.setStyleSheet("color:%s; font-size:9pt;" % C_STATUS_FG)
        lay.addWidget(hint)

        self.tree = QTreeWidget()
        self.tree.setHeaderHidden(True)
        lay.addWidget(self.tree, 1)
        self._reload_tree()

        row = QHBoxLayout()

        def btn(txt, fn):
            b = QPushButton(txt)
            b.clicked.connect(fn)
            return b
        row.addWidget(btn("🗑  Remove selected", self._remove))
        row.addWidget(btn("🗑  Remove ALL...", self._remove_all))
        row.addStretch(1)
        row.addWidget(btn("Close", self.close))
        lay.addLayout(row)

    def _reload_tree(self):
        self.tree.clear()
        store = self.win._zoom_store()
        for pid, bucket in store.items():
            prof = self.win._profile_by_id(pid)
            pname = (prof.get("name", pid) if prof else pid) or pid
            hosts = bucket.get("by_host") or {}
            urls = bucket.get("by_url") or {}
            if not hosts and not urls:
                continue
            top = QTreeWidgetItem(["👤  Profile: %s" % pname])
            top._scope = None
            self.tree.addTopLevelItem(top)
            for host, z in sorted(hosts.items()):
                it = QTreeWidgetItem(["🌐  %s  -  %d%%" % (host, int(round(z * 100)))])
                it._scope, it._pid, it._key = "domain", pid, host
                top.addChild(it)
            for url, z in sorted(urls.items()):
                short = url if len(url) <= 60 else url[:57] + "..."
                it = QTreeWidgetItem(["📄  %s  -  %d%%" % (short, int(round(z * 100)))])
                it._scope, it._pid, it._key = "page", pid, url
                top.addChild(it)
            top.setExpanded(True)
        if self.tree.topLevelItemCount() == 0:
            na = QTreeWidgetItem(["(no custom sizes saved yet)"])
            na._scope = None
            self.tree.addTopLevelItem(na)

    def _remove(self):
        it = self.tree.currentItem()
        if not it or getattr(it, "_scope", None) is None:
            return
        self.win._clear_zoom_override(it._key, it._scope == "page", pid=it._pid)
        self.win._apply_saved_zoom_all_tabs()
        self._reload_tree()

    def _remove_all(self):
        if QMessageBox.question(
                self, "Remove ALL custom sizes",
                "Remove every saved page/domain size, for every profile? "
                "This cannot be undone.",
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
                ) != QMessageBox.StandardButton.Yes:
            return
        self.win.settings["page_zoom_overrides"] = {}
        save_json(SETTINGS_FILE, self.win.settings)
        self.win._apply_saved_zoom_all_tabs()
        self._reload_tree()


# ============================================================================
#  DEL 13 - MAIN BROWSER WINDOW
# ============================================================================
class Browser(QMainWindow):
    def __init__(self, launch_url=None):
        super().__init__()
        # URL Windows passed us on the command line (see get_launch_url()),
        # e.g. because we're the default browser and the user just clicked
        # a link somewhere else. Opened as a tab further down in __init__.
        self._launch_url = launch_url
        # A magnet / .torrent handed to us on the command line is NOT a page:
        # it goes to the torrent handling (DEL 49) once the window exists, and
        # must not be opened as a tab (which is exactly the "clicking a magnet
        # link does nothing" every other browser gives you).
        self._launch_torrent = None
        if launch_url and is_torrent_link(launch_url):
            self._launch_torrent = launch_url
            self._launch_url = None
        self.settings = load_settings()
        self._userscripts = load_userscripts()      # user add-ons (.js/.css)
        self._kb_layouts = load_keyboard_layouts()  # on-screen-keyboard layouts
        self._osk = None                            # the on-screen keyboard window
        self._media_dlg = None                      # the media-downloader window
        self._media_q = None                        # its job queue (made on demand)
        self.bookmarks = load_json(BOOKMARKS_FILE, [])
        # Favourites = ONE global list shared by every profile (see FAVOURITES_FILE).
        # Each item is {"title": ..., "url": ...}. Loaded once for the window.
        self.favourites = load_json(FAVOURITES_FILE, [])
        if not isinstance(self.favourites, list):
            self.favourites = []
        # The "99 Favourites" profile is created here, BEFORE the profile menu,
        # badge or engines are built, so it is just another profile to them.
        self._ensure_favourites_profile()
        # ---- Bulk upload queue (DEL 21J): never persisted, always starts empty
        self._upload_queue = []
        self._bulk_total = 0
        self._bulk_sent = 0
        self._bulk_host = ""
        self.history = load_json(HISTORY_FILE, [])
        # Low-vision runtime size = user's saved default (resets here every start).
        self._lv_zoom = float(self.settings.get("low_vision_zoom", 1.3))
        self._lv_minfont = int(self.settings.get("low_vision_minfont", 18))
        # Password vault state (locked at start; unlocked in memory only).
        self._vault = None
        self._vault_unlocked = False
        self._vault_pin = None

        # ---- Apply the saved theme BEFORE any stylesheet is built ----
        apply_theme_dict(self.settings.get("theme", {}))

        self.setWindowTitle(APP_NAME)
        apply_window_icon(self)

        # ---- Profiles: one Chromium engine per profile (separate cookies/logins) ----
        self.adblock = AdblockInterceptor()
        self.engines = {}              # pid -> QWebEngineProfile (built lazily)
        self.runtime_tabs = {}         # pid -> [urls] kept while switching this session
        self.runtime_tab_index = {}    # pid -> which tab index was active when we last left it
        self.live_views = {}           # pid -> [live view widgets] kept alive across switches
                                       # (so a profile's tabs keep scroll/state, no reload)
        self._activity = []            # rolling event trail for the bug reporter (DEL 40)
        self._activity_max = 400       # keep the last N events in memory
        self._has_identity_tab = False # cache: is any Google/MS tab open? (cookie filter)
        self._closed_tabs = []         # URLs of recently closed tabs (Ctrl+Shift+T reopens)
        self._chal_helped = set()      # hosts whose "verify you are human" wall we already relaxed
        self._ensure_profiles()
        self._scrub_dead_saved_tabs()   # one-shot cleanup of stale error pages (all profiles)
        self.active_id = self._valid_active_id()
        self.engine = self._get_engine(self.active_id)   # active profile's engine
        self.profile = self.engine     # back-compat alias
        self._load_profile_data()      # bookmarks + history for the active profile

        self._apply_privacy()          # adblock domains + scripts on every engine
        write_new_tab_page(self.settings.get("search_engine", SEARCH_URL))

        self._build_ui()
        self._build_shortcuts()
        self._restore_geometry()
        self._update_profile_badge()

        # ---- Startup: restore previous session, open home, or a blank tab ----
        mode = self.settings.get("startup_mode", "restore")
        items = []
        if mode == "restore":
            items = [x for x in (self._active_profile().get("last_tabs") or []) if x]
        elif mode == "home":
            items = [self.settings.get("home_url", DEFAULT_HOME)]
        if self._launch_url:
            # Came from Windows ("open with WhyBrowse" / default-browser click)
            # - always open it, on top of whatever the normal startup mode gives.
            items.append(self._launch_url)
        # Drop dead session-expired error pages (e.g. Inera IdP /_error?status=412
        # "No HTTP session") so they never reopen on start. See is_dead_restore_url.
        for it in items:
            if is_dead_restore_url(_saved_tab_url(it)):
                continue
            self._add_saved_tab(it)
        if self.tabs.count() == 0:
            self.new_tab(switch=False)          # blank start page
        # If we were launched with a URL, jump straight to that tab (it's the
        # last one added); otherwise land on the first tab as before.
        self.tabs.setCurrentIndex(self.tabs.count() - 1 if self._launch_url else 0)
        self._open_autostart_bookmarks()
        self._start_crash_recovery()
        self._build_completer()

        # ---- Single-instance URL forwarding ----
        # Only the PRIMARY instance owns the pipe. Later launches (e.g. a link
        # clicked in Thunderbird while WhyBrowse is already open) send their URL
        # here instead of starting a second WhyBrowse (see main()).
        self._ipc_server = None
        if not IS_SECONDARY_INSTANCE:
            self._start_ipc_server()

        # ---- Update Scanner: poll watched pages for changes in the background ----
        self._watch_cache = load_json(WATCH_CACHE_FILE, {})    # url -> last seen text
        self._watcher = PageWatcher(self)
        self._watcher.result.connect(self._on_watch_result)
        self._watch_timer = QTimer(self)
        self._watch_timer.timeout.connect(self._watch_tick)
        self._watch_timer.start(60 * 1000)          # check what is due every minute
        QTimer.singleShot(8000, self._watch_tick)   # first sweep shortly after start

        # ---- Tab sleeping: discard idle background tabs to free memory ----
        self._sleep_timer = QTimer(self)
        self._sleep_timer.timeout.connect(self._sleep_tick)
        self._sleep_timer.start(60 * 1000)          # re-evaluate idle tabs every minute

        # ---- Scroll-position memory (for "go to last position" sites) ----
        self._scroll_pos = load_json(SCROLL_POS_FILE, {})  # url -> {x,y,gsel,gx,gy}
        self._scroll_timer = QTimer(self)
        self._scroll_timer.timeout.connect(self._scroll_capture_tick)
        self._scroll_timer.start(4000)              # snapshot the current tab every 4 s

        # ---- Live cookie snapshot: lets a SECOND, later-started instance
        # inherit THIS one's current logins even while both stay open at the
        # same time (see _snapshot_all_cookie_stores / _replay_cookie_snapshot).
        self._cookie_snapshot_timer = QTimer(self)
        self._cookie_snapshot_timer.timeout.connect(self._snapshot_all_cookie_stores)
        self._cookie_snapshot_timer.start(20000)     # refresh every 20 s
        QTimer.singleShot(3000, self._snapshot_all_cookie_stores)   # + one early on

        # (Cookie safety-net backup/restore happens at startup in _build_engine —
        #  the ONLY time the Cookies file isn't exclusively locked by Chromium.)

        # ---- Form-field memory (remember & refill non-password fields per host) ----
        self._form_mem = load_json(FORM_MEMORY_FILE, {})   # host -> {fieldkey: value}
        # Message drafts: list of {ts,host,url,title,field,text}; 7-day safety net.
        self._drafts = load_json(DRAFTS_FILE, [])
        if not isinstance(self._drafts, list):
            self._drafts = []
        self._purge_old_drafts()
        self._form_timer = QTimer(self)
        self._form_timer.timeout.connect(self._form_capture_tick)
        self._form_timer.start(5000)                # snapshot the current tab's fields

        # ---- Torrents & magnet links (DEL 49) ----
        # Nothing here starts a torrent session by itself; the watch is only a
        # signal connection, and the resume runs a few seconds in so it never
        # competes with startup.
        self._torrent_engine = None
        self._torrent_dlg = None
        self._start_torrent_clipboard_watch()
        QTimer.singleShot(9000, self._resume_torrents_on_start)
        self._phone_sync_boot()                      # DEL 57: phone sync state + quiet background sync
        if self._launch_torrent:
            QTimer.singleShot(700, lambda: self.handle_torrent_link(
                self._launch_torrent, source="opened from another program"))

    # ----------------------------------------------------- profiles: model ----
    def _ensure_profiles(self):
        if not self.settings.get("profiles"):
            self.settings["profiles"] = [
                {"id": "default", "name": "Default", "color": C_ACCENT,
                 "badge": "1", "enabled": True, "shared_bookmarks": False,
                 "last_tabs": []}]
        if not self.settings.get("active_profile"):
            self.settings["active_profile"] = self.settings["profiles"][0]["id"]

    def _scrub_dead_saved_tabs(self):
        """Strip session-expired error pages (e.g. Inera IdP /_error?status=412
        'No HTTP session') out of EVERY profile's saved last_tabs, once at start.
        Restore-time filtering only cleans a profile when you switch to it; this
        clears background profiles too, so a dead tab stops reappearing the very
        next launch instead of lingering until that profile is next opened."""
        try:
            changed = False
            for prof in self.settings.get("profiles", []):
                tabs = prof.get("last_tabs")
                if not isinstance(tabs, list):
                    continue
                kept = [t for t in tabs
                        if not is_dead_restore_url(_saved_tab_url(t))]
                if len(kept) != len(tabs):
                    prof["last_tabs"] = kept
                    changed = True
            if changed:
                save_json(SETTINGS_FILE, self.settings)
        except Exception as e:
            log_line("scrub_dead_saved_tabs: %s" % e)

    def _valid_active_id(self):
        enabled = [p for p in self.settings["profiles"] if p.get("enabled", True)]
        ids = [p["id"] for p in enabled]
        # Links from OUTSIDE (default-browser click in Thunderbird etc.) must
        # ALWAYS land in profile 1 ("default"), never in whatever profile was
        # active last time. So when we were launched with a URL, force it.
        if getattr(self, "_launch_url", None) and "default" in ids:
            return "default"
        # A pinned default profile always wins at startup (if still enabled),
        # regardless of which profile was active when the app last closed.
        dft = self.settings.get("default_profile")
        if dft in ids:
            return dft
        pid = self.settings.get("active_profile")
        if pid in ids:
            return pid
        return ids[0] if ids else self.settings["profiles"][0]["id"]

    def _profile_by_id(self, pid):
        for p in self.settings.get("profiles", []):
            if p.get("id") == pid:
                return p
        return self.settings["profiles"][0]

    def _active_profile(self):
        return self._profile_by_id(self.active_id)

    def _bookmarks_file(self, profile):
        if profile.get("shared_bookmarks"):
            return SHARED_BOOKMARKS
        return profile_paths(profile["id"])["bookmarks"]

    def _load_profile_data(self):
        prof = self._active_profile()
        # Profile 99's bookmarks are GENERATED from the starred list (DEL 21H),
        # never read from disk.
        if self._is_fav_profile(prof):
            self.bookmarks = self._favourites_bookmark_tree()
        else:
            self.bookmarks = normalize_bookmarks(load_json(self._bookmarks_file(prof), []))
        self.history = load_json(profile_paths(prof["id"])["history"], [])

    def _save_profile_data(self):
        prof = self._active_profile()
        # Never write the generated tree over anything (DEL 21H).
        if not self._is_fav_profile(prof):
            save_json(self._bookmarks_file(prof), self.bookmarks)
        save_json(profile_paths(prof["id"])["history"], self.history)

    def _save_bm(self):
        prof = self._active_profile()
        if self._is_fav_profile(prof):
            return                               # generated view - nothing to save
        save_json(self._bookmarks_file(prof), self.bookmarks)

    def _save_hist(self):
        save_json(profile_paths(self.active_id)["history"], self.history)

    # ----------------------------------------------------- profiles: engines ----
    def _get_engine(self, pid):
        if pid not in self.engines:
            self._build_engine(pid)
        return self.engines[pid]

    # ---- Cookie safety-net: keep a backup of each profile's Cookies DB so logins
    #      survive even if QtWebEngine loses them on an unclean shutdown. Backups
    #      are taken while running (cookies present) and restored on next launch
    #      only when the live file is gone/empty.
    def _cookie_pairs(self, storage):
        return [
            (os.path.join(storage, "Cookies"),
             os.path.join(storage, "Cookies.wbbak")),
            (os.path.join(storage, "Network", "Cookies"),
             os.path.join(storage, "Network", "Cookies.wbbak")),
        ]

    def _backup_storage_cookies(self, storage):
        # NOTE: only useful BEFORE Chromium opens the cookie DB (at startup, in
        # _build_engine). While the app runs the file is exclusively locked on
        # Windows, so a copy here would just fail (caught). We snapshot the live
        # Cookies into .wbbak so a future launch can restore it if the live file
        # ever goes missing on an unclean shutdown.
        for live, bak in self._cookie_pairs(storage):
            try:
                if not (os.path.isfile(live) and os.path.getsize(live) > 1024):
                    continue
                tmp = bak + ".tmp"
                shutil.copy2(live, tmp)
                os.replace(tmp, bak)               # atomic swap into place
            except Exception:
                pass

    def _restore_cookies(self, storage):
        for live, bak in self._cookie_pairs(storage):
            try:
                if os.path.isfile(bak) and os.path.getsize(bak) > 1024:
                    if (not os.path.isfile(live)) or os.path.getsize(live) <= 1024:
                        os.makedirs(os.path.dirname(live), exist_ok=True)
                        shutil.copy2(bak, live)
                        log_line("Restored cookies backup for %s" % storage)
            except Exception:
                pass

    def _backup_all_cookies(self):
        seen = set()
        try:
            ids = [self.active_id] + list(self.engines.keys())
        except Exception:
            ids = ["default"]
        for pid in ids:
            try:
                st = profile_paths(pid)["storage"]
            except Exception:
                continue
            if st in seen:
                continue
            seen.add(st)
            self._backup_storage_cookies(st)

    # ---- Live cookie hand-off between simultaneously-open instances ----
    # If a SECOND WhyBrowse window is opened while an older one is still
    # running (e.g. you keep a build open to browse/chat, then launch a new
    # test build), the two Chromium engines must never share one on-disk
    # cookie database - see IS_SECONDARY_INSTANCE / profile_paths(). Instead,
    # every running instance periodically re-enumerates its OWN live cookies
    # (via Chromium's in-memory cookieStore API, never the raw locked file)
    # and writes a small JSON snapshot into the PRIMARY profile's folder. A
    # (re)starting instance reads that snapshot and replays it into its own
    # fresh cookie store with setCookie(), so it starts already logged in.
    def _snapshot_all_cookie_stores(self):
        for pid, eng in list(self.engines.items()):
            try:
                self._snapshot_engine_cookies(pid, eng)
            except Exception as e:
                log_line("cookie snapshot error (%s): %s" % (pid, e))

    def _snapshot_engine_cookies(self, pid, eng):
        store = eng.cookieStore()
        buf = []

        def _on_cookie(c):
            # Pull every field out RIGHT HERE, the moment Qt hands us the
            # cookie - not 800ms later off a stored reference. Holding onto
            # the raw QNetworkCookie across that delay is what let a single
            # stale/malformed one blow up the ENTIRE snapshot later (see
            # _qba_to_str below): "SystemError: Negative size passed to
            # PyUnicode_New" from a PyQt6/sip QByteArray conversion glitch.
            # One bad cookie must never cost us every other login.
            try:
                exp = c.expirationDate()
                buf.append({
                    "name":     self._qba_to_str(c.name()),
                    "value":    self._qba_to_str(c.value()),
                    "domain":   c.domain(),
                    "path":     c.path(),
                    "secure":   c.isSecure(),
                    "httponly": c.isHttpOnly(),
                    "expiry":   exp.toString(Qt.DateFormat.ISODate) if exp.isValid() else "",
                })
            except Exception:
                pass    # skip just this one cookie, keep the rest
        conn = store.cookieAdded.connect(_on_cookie)

        def _finish():
            try:
                store.cookieAdded.disconnect(conn)
            except Exception:
                pass
            self._write_cookie_snapshot(pid, buf)
        store.loadAllCookies()
        QTimer.singleShot(800, _finish)   # give the async enumeration time to arrive

    def _qba_to_str(self, qba):
        """Convert a cookie's QByteArray (name/value) to str, defensively.
        Some PyQt6/sip builds can raise a low-level SystemError doing this
        conversion on certain QByteArrays ('Negative size passed to
        PyUnicode_New') - catch it here so it costs us one field, not the
        whole cookie snapshot / the cross-instance login hand-off."""
        try:
            return bytes(qba).decode("utf-8", "replace")
        except Exception:
            return ""

    def _write_cookie_snapshot(self, pid, data):
        try:
            storage = profile_paths(pid, force_primary=True)["storage"]
            os.makedirs(storage, exist_ok=True)
            path = os.path.join(storage, "live_cookies.json")
            tmp = path + ".tmp"
            with open(tmp, "w", encoding="utf-8") as f:
                json.dump(data, f)
            os.replace(tmp, path)              # atomic swap into place
        except Exception as e:
            log_line("cookie snapshot write error (%s): %s" % (pid, e))

    def _replay_cookie_snapshot(self, eng, pid):
        """Called for a SECONDARY instance's fresh engine: pull in whatever
        the other, already-open instance's live_cookies.json currently has,
        so this window starts already logged in despite using a separate,
        empty storage folder."""
        try:
            storage = profile_paths(pid, force_primary=True)["storage"]
            path = os.path.join(storage, "live_cookies.json")
            if not os.path.isfile(path):
                return
            with open(path, "r", encoding="utf-8") as f:
                data = json.load(f)
            store = eng.cookieStore()
            n = 0
            for item in data:
                try:
                    c = QNetworkCookie(item["name"].encode("utf-8"),
                                        item["value"].encode("utf-8"))
                    if item.get("domain"):
                        c.setDomain(item["domain"])
                    if item.get("path"):
                        c.setPath(item["path"])
                    c.setSecure(bool(item.get("secure")))
                    c.setHttpOnly(bool(item.get("httponly")))
                    if item.get("expiry"):
                        dt = QDateTime.fromString(item["expiry"], Qt.DateFormat.ISODate)
                        if dt.isValid():
                            c.setExpirationDate(dt)
                    store.setCookie(c)
                    n += 1
                except Exception:
                    continue
            log_line("Linked session: replayed %d cookie(s) from the other "
                      "open instance for profile '%s'" % (n, pid))
        except Exception as e:
            log_line("cookie snapshot replay error (%s): %s" % (pid, e))

    def _build_engine(self, pid):
        paths = profile_paths(pid)
        for d in (paths["storage"], paths["cache"]):
            try: os.makedirs(d, exist_ok=True)
            except Exception: pass
        # BEFORE Chromium opens (and exclusively LOCKS) the cookie DB:
        #   1. if the live Cookies went missing/empty (a lost flush on a previous
        #      shutdown), restore it from our backup so logins survive;
        #   2. then snapshot the current (healthy) live Cookies into the backup.
        # This is the only safe moment to touch the file — while running it's locked.
        self._restore_cookies(paths["storage"])
        self._backup_storage_cookies(paths["storage"])
        eng = QWebEngineProfile("whybrowse_" + pid, self)
        eng.setPersistentStoragePath(paths["storage"])
        eng.setCachePath(paths["cache"])
        # FORCE persistent cookies: AllowPersistentCookies drops SESSION cookies on
        # restart, and Google's sign-in relies on session cookies — that is why you
        # had to log in again (and re-do "Check your device" 2FA) every time. Force
        # keeps them so you stay logged in across restarts/profile switches.
        eng.setPersistentCookiesPolicy(
            QWebEngineProfile.PersistentCookiesPolicy.ForcePersistentCookies)
        # Present as a normal, up-to-date Chrome. QtWebEngine's default UA carries
        # a "QtWebEngine/..." token and an older Chrome version, which makes web
        # apps like WhatsApp Web refuse to run ("please update Chrome").
        try:
            eng.setHttpUserAgent(self._effective_user_agent(eng))
        except Exception:
            pass
        # ...and send an Accept-Language header at all (Qt sends none by default).
        try:
            eng.setHttpAcceptLanguage(
                (self.settings.get("accept_language") or "").strip() or ACCEPT_LANGUAGE)
        except Exception:
            pass
        self._apply_brand_headers()
        eng.setUrlRequestInterceptor(self.adblock)
        eng.cookieStore().setCookieFilter(self._cookie_filter)
        eng.downloadRequested.connect(self.on_download)
        if IS_SECONDARY_INSTANCE:
            # Fresh, empty storage folder (see profile_paths) - inherit the
            # other, already-open instance's current logins right away.
            self._replay_cookie_snapshot(eng, pid)
        self.engines[pid] = eng
        self._install_scripts(eng)
        return eng

    def _effective_user_agent(self, eng):
        """The user-agent to present. A custom one (Settings) wins; otherwise we
        clean QtWebEngine's default: drop the 'QtWebEngine/..' token and replace
        whatever Chrome version Chromium reports with the latest stable Chrome
        major (fetched from Google's API at most once per 30 days and cached in
        settings as 'cached_chrome_major').  This keeps the UA believable for
        sites that reject old or unknown Chrome versions (e.g. Google sign-in,
        WhatsApp Web)."""
        custom = (self.settings.get("user_agent") or "").strip()
        if custom:
            return custom
        # Always derive from the engine's PRISTINE user-agent, captured once,
        # never from whatever we last wrote onto it. Otherwise setting a custom
        # UA and then clearing it would leave the custom string as the base
        # forever (all engines share the same Qt default, so one copy is right).
        global _PRISTINE_UA
        if not _PRISTINE_UA:
            try:
                _PRISTINE_UA = eng.httpUserAgent()
            except Exception:
                pass
        ua = _PRISTINE_UA or (
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
            "(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36")
        ua = re.sub(r"\s*QtWebEngine/\S+", "", ua)
        target = self._ua_chrome_major()
        ua = re.sub(r"Chrome/\d+\.\d+\.\d+\.\d+", "Chrome/%d.0.0.0" % target, ua)
        ua = re.sub(r"Chrome/\d+", "Chrome/%d" % target, ua)
        return ua

    def _engine_chrome_major(self):
        """The Chrome major version this build of QtWebEngine REALLY is."""
        try:
            from PyQt6.QtWebEngineCore import qWebEngineChromiumVersion
            return int(str(qWebEngineChromiumVersion()).split(".")[0])
        except Exception:
            return 0

    def _ua_chrome_major(self):
        """Which Chrome major the user-agent should claim.

        NEVER claim a version BELOW the engine's real one. The old code always
        rewrote the version to `cached_chrome_major`, which is refreshed from
        Google's API at most once a month - so a stale cache (136) made a real
        Chromium 140 engine advertise itself as Chrome 136 while still exposing
        every Chrome 140 API. Bot checks (Cloudflare Turnstile, hCaptcha)
        feature-detect and compare against the claimed version; a UA that does
        not match the feature set is a hard fail, and you loop on "Verify you
        are human" forever no matter how many boxes you tick (reported on
        predb.me, engine was 140 claiming 136).

        Policy: report the engine's REAL version whenever we know it. Claiming a
        version ABOVE the real one is the same mismatch in the other direction,
        so we only do that when the engine is genuinely ancient (more than
        UA_BUMP_GAP majors behind latest stable) - which is the case the upward
        bump was added for in the first place (WhatsApp Web and Google sign-in
        refusing an old Chrome). The real cure for an old engine is Menu →
        Browser engine version → Update engine now."""
        real = self._engine_chrome_major()
        cached = 0
        try:
            cached = int(self.settings.get("cached_chrome_major") or 0)
        except Exception:
            cached = 0
        if not real:
            return cached or 136
        if cached and cached - real > UA_BUMP_GAP:
            return cached                  # genuinely old engine: claim current
        return real

    # -------------------------------------------------- UI construction ----
    # ---- Stylesheet builders (read the active theme; reused by apply_theme) ----
    def _css_navbtn(self):
        # [wbdim="true"] is the greyed-out look for a button that is still
        # CLICKABLE. Qt sends no mouse events at all to a disabled widget, so a
        # disabled Forward arrow could never answer a right-click - and its
        # right-click (open a copy of this page) is useful precisely when there
        # is nothing to go forward TO. So it stays enabled and is dimmed here.
        return ("QPushButton{background:%s; color:%s; border:none; padding:4px 10px; "
                "border-radius:6px; font-size:13pt;}QPushButton:hover{background:%s;}"
                "QPushButton[wbdim=\"true\"]{color:%s;}"
                % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV,
                   blend(C_BTN_FG, C_BTN_BG, 0.62)))

    def _css_accentbtn(self):
        return ("QPushButton{background:%s; color:%s; border:none; padding:3px 10px; "
                "border-radius:6px; font-weight:bold; font-size:10pt;}"
                "QPushButton:hover{background:%s;}"
                % (C_ACCENT, C_ACCENT_FG, C_ACCENT_HOV))

    def _css_quick(self):
        return ("QLineEdit{background:%s; color:%s; border:1px solid %s; border-radius:12px; "
                "padding:5px 10px; font-size:10pt;}QLineEdit:focus{border:1px solid %s;}"
                % (C_ADDR_BG, C_ADDR_FG, C_BORDER, C_ACCENT))

    def _css_address(self):
        return ("QLineEdit{background:%s; color:%s; border:1px solid %s; border-radius:14px; "
                "padding:6px 14px; font-size:11pt;}QLineEdit:focus{border:1px solid %s;}"
                % (C_ADDR_BG, C_ADDR_FG, C_BORDER, C_ACCENT))

    def _css_tabs(self):
        # The selected tab is painted in the ACCENT colour so it is unmistakable.
        # Layout adapts to Top (horizontal) vs Left (vertical) tab position.
        left = self.settings.get("tab_position", "top") == "left"
        sel = shade(C_ACCENT, -45)
        if left:
            # Width/height come from VerticalTabBar.tabSizeHint, not the QSS.
            base_edge = "border-left:3px solid transparent;"
            sel_edge = "border-left:3px solid %s;" % sel
            radius = "border-top-left-radius:8px; border-bottom-left-radius:8px;"
            size = "margin-bottom:2px;"
        else:
            base_edge = "border-top:3px solid transparent;"
            sel_edge = "border-top:3px solid %s;" % sel
            radius = "border-top-left-radius:8px; border-top-right-radius:8px;"
            size = "max-width:240px; margin-right:2px;"
        return ("QTabWidget::pane{border:none;}"
                "QTabBar::tab{background:%s; color:%s; padding:7px 14px; %s %s %s}"
                "QTabBar::tab:selected{background:%s; color:%s; %s font-weight:bold;}"
                "QTabBar::tab:hover{background:%s;}"
                % (C_TAB_BG, C_TAB_FG, base_edge, radius, size,
                   C_ACCENT, C_ACCENT_FG, sel_edge, C_BTN_BG_HOV))

    def _apply_tab_layout(self):
        """Place the tab strip on Top (horizontal) or Left (vertical). In Left
        mode tabs are fixed-size horizontal rectangles (see VerticalTabBar)."""
        left = self.settings.get("tab_position", "top") == "left"
        self.tabs.setTabPosition(QTabWidget.TabPosition.West if left
                                 else QTabWidget.TabPosition.North)
        # Vertical tabs draw no close 'x' (it would clutter the small rectangle);
        # middle-click closes instead. Horizontal tabs keep the close button.
        self.tabs.setTabsClosable(not left)
        if left:
            px = int(self.settings.get("tab_width_px", 0) or 0)
            if px > 0:
                w = px                                  # custom dragged width
            else:
                chars = int(self.settings.get("tab_chars", 15) or 15)
                fm = self.tabs.tabBar().fontMetrics()
                w = fm.averageCharWidth() * chars + 36  # + favicon + padding
            self._tabbar.set_fixed_size(w, 28)          # fixed height = rectangles
        else:
            # Remove any width constraints that were set in vertical mode so the
            # horizontal tab bar is free to size itself normally.
            self._tabbar.setMinimumWidth(0)
            self._tabbar.setMaximumWidth(16777215)  # QWIDGETSIZE_MAX
        try:
            self.tabs.tabBar().setElideMode(Qt.TextElideMode.ElideRight)
        except Exception:
            pass
        self.tabs.setStyleSheet(self._css_tabs())
        self.tabs.tabBar().update()

    def _set_tab_position(self, pos):
        self.settings["tab_position"] = pos
        save_json(SETTINGS_FILE, self.settings)
        self._apply_tab_layout()
        show_toast(self, "Tabs on the %s" % ("left (vertical)" if pos == "left" else "top"))

    def _set_tab_chars(self, chars):
        self.settings["tab_chars"] = int(chars)
        self.settings["tab_width_px"] = 0          # a preset clears any dragged width
        save_json(SETTINGS_FILE, self.settings)
        self._apply_tab_layout()
        show_toast(self, "Tab width: %d characters" % chars)

    def _set_tab_width_px_dialog(self):
        """Ask the user for an exact pixel width for the left tab column."""
        cur = int(self.settings.get("tab_width_px", 0) or 0)
        if cur <= 0:                                # derive from chars as starting point
            chars = int(self.settings.get("tab_chars", 15) or 15)
            fm = self._tabbar.fontMetrics()
            cur = fm.averageCharWidth() * chars + 36
        px, ok = QInputDialog.getInt(
            self, "Tab column width",
            "Width in pixels (70 – 600):",
            value=cur, min=70, max=600, step=5)
        if ok:
            self.settings["tab_width_px"] = px
            save_json(SETTINGS_FILE, self.settings)
            self._apply_tab_layout()
            show_toast(self, "Tab width: %d px" % px)

    def _toggle_first_word(self, value):
        self.settings["tab_first_word_only"] = bool(value)
        save_json(SETTINGS_FILE, self.settings)
        for i in range(self.tabs.count()):
            v = self.tabs.widget(i)
            if v:
                self._refresh_tab_label(v)
        show_toast(self, "Show only first word: %s" % ("ON" if value else "OFF"))

    def _save_tab_width(self, px):
        """Persist a custom (dragged) left-tab column width."""
        self.settings["tab_width_px"] = int(px)
        save_json(SETTINGS_FILE, self.settings)

    def _apply_bookmarks_position(self):
        """Place the bookmarks bar on top (horizontal row) or right (vertical
        panel where folder menus open inward/left). Applied once at startup;
        switching at runtime asks for a restart (toolbar reflow is finicky)."""
        if not hasattr(self, "bmbar"):
            return
        right = self.settings.get("bookmarks_position", "top") == "right"
        try:
            self.removeToolBar(self.bmbar)
        except Exception:
            pass
        if right:
            self.addToolBar(Qt.ToolBarArea.RightToolBarArea, self.bmbar)
        else:
            self.addToolBarBreak(Qt.ToolBarArea.TopToolBarArea)   # own row under the nav
            self.addToolBar(Qt.ToolBarArea.TopToolBarArea, self.bmbar)
        self.bmbar.setVisible(bool(self.settings.get("show_bookmarks_bar", True)))

    def _set_bookmarks_position(self, pos):
        self.settings["bookmarks_position"] = pos
        save_json(SETTINGS_FILE, self.settings)
        show_toast(self, "Bookmarks bar: %s — restart to apply"
                   % ("right side" if pos == "right" else "top"))

    def _css_bar(self):
        return "QToolBar{background:%s; border:none; padding:4px;}" % C_BAR_BG

    def _css_status(self):
        return "QStatusBar{background:%s; color:%s;}" % (C_BAR_BG, C_STATUS_FG)

    def _build_ui(self):
        # ---- Navigation toolbar ----
        self.nav = QToolBar()
        self.nav.setMovable(False)
        self.nav.setIconSize(QSize(20, 20))
        self.nav.setContextMenuPolicy(Qt.ContextMenuPolicy.PreventContextMenu)
        self.addToolBar(self.nav)
        self._chrome_btns = []          # normal nav buttons (for re-theming)
        self._accent_btns = []          # accent buttons (for re-theming)

        def tool_btn(text, tip, slot, accent=False):
            b = QPushButton(text)
            b.setToolTip(tip)
            b.setFixedHeight(30)
            b.setCursor(Qt.CursorShape.PointingHandCursor)
            b.clicked.connect(slot)
            self.nav.addWidget(b)
            (self._accent_btns if accent else self._chrome_btns).append(b)
            return b

        # Nav arrows: left-click = one step, right-click = the big version of
        # the same idea. Back -> all the way to the page this tab started on;
        # Forward -> a second copy of the page you are on, in its own tab.
        self.btn_back = tool_btn("◀", "Back (Alt+Left)\n"
                                 "Right-click: back to the FIRST page of this tab",
                                 lambda: self._nav_do("back"))
        self.btn_back.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        self.btn_back.customContextMenuRequested.connect(
            lambda _p: self._nav_first_page())
        self.btn_fwd  = tool_btn("▶", "Forward (Alt+Right)\n"
                                 "Right-click: open a COPY of this page in a new tab",
                                 lambda: self._nav_do("forward"))
        self.btn_fwd.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        self.btn_fwd.customContextMenuRequested.connect(
            lambda _p: self._nav_duplicate_here())
        self.btn_rel  = tool_btn("↻", "Reload (F5)", lambda: self._nav_do("reload"))
        self.btn_home = tool_btn("⌂", "Home", self.go_home)
        # New-tab button lives in the toolbar so it can never be clipped.
        self.btn_newtab = tool_btn("+", "New tab (Ctrl+T)", lambda: self.new_tab(), accent=True)
        self.btn_newtab.setFixedWidth(30)
        self.btn_refresh_all = tool_btn("⟳", "Reload every open tab", self.refresh_all_tabs)
        self.btn_refresh_all.setFixedWidth(34)
        # Tab arrows: left-click = step, right-click = jump to the far end.
        self.btn_tabprev = tool_btn("◁", "Previous tab (right-click: first tab)",
                                    lambda: self._cycle_tab(-1))
        self.btn_tabprev.setFixedWidth(28)
        self.btn_tabprev.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        self.btn_tabprev.customContextMenuRequested.connect(
            lambda _p: self.tabs.setCurrentIndex(0))
        self.btn_tabnext = tool_btn("▷", "Next tab (right-click: last tab)",
                                    lambda: self._cycle_tab(+1))
        self.btn_tabnext.setFixedWidth(28)
        self.btn_tabnext.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        self.btn_tabnext.customContextMenuRequested.connect(
            lambda _p: self.tabs.setCurrentIndex(self.tabs.count() - 1))
        # Quick audio: LEFT-click mutes/unmutes THIS tab, RIGHT-click opens a
        # volume slider (+ mute/unmute all).
        self.btn_mute = tool_btn("🔊", "Mute/unmute this tab  (right-click: volume)",
                                 self.toggle_mute_current)
        self.btn_mute.setFixedWidth(30)
        self.btn_mute.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        self.btn_mute.customContextMenuRequested.connect(lambda _p: self._show_volume_menu())
        # Plain/clean mode: one-click temporary "turn OFF everything" (adblock,
        # 3p-cookie block, all injected scripts). Turns accent when ON.
        self.btn_clean = tool_btn(
            "🧹", "Plain mode: temporarily turn OFF all features (ad block, cookie "
            "block, scripts). Click to toggle.", self._toggle_clean_toolbar)
        self.btn_clean.setFixedWidth(30)
        # Find/list every open tab (handy when there are too many to see at once).
        self.btn_tablist = tool_btn("🗂", "Search / list all open tabs (Ctrl+Shift+A)",
                                    self.show_tab_search)
        self.btn_tablist.setFixedWidth(34)

        # ---- Low-vision dial: click=on/off, scroll=zoom, Shift+scroll=font,
        #      right-click=save/factory default ----
        self.btn_lv = WheelButton(self._lv_wheel, "🔎")
        self.btn_lv.setToolTip("Low-vision: click = on/off · scroll = bigger/smaller · "
                               "Shift+scroll = font size · right-click = defaults")
        self.btn_lv.setFixedHeight(30)
        self.btn_lv.setCursor(Qt.CursorShape.PointingHandCursor)
        self.btn_lv.clicked.connect(self._lv_button_click)
        self.btn_lv.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        self.btn_lv.customContextMenuRequested.connect(self._lv_menu)
        self.nav.addWidget(self.btn_lv)
        self._chrome_btns.append(self.btn_lv)

        # ---- CP ("Copy/Paste" field memory): click into a field, then click
        # CP. First time (nothing saved yet) it asks you to type a value and
        # click CP again to save it; after that, click the field + CP fills
        # it back in. Works on stubborn custom fields (e.g. no name/id) since
        # it targets the FOCUSED field directly, incl. inside shadow DOM. ----
        # ---- 🚫 Popup marker (DEL 21I): hidden until this tab has a popup
        #      blocked, or the site is set to "no popups". Never let a block be
        #      silent - a page crippled without explanation looks like a bug. ----
        self.btn_popup = tool_btn("🚫", "Blocked popups on this page",
                                  self._popup_marker_menu)
        self.btn_popup.setFixedWidth(46)
        self.btn_popup.setVisible(False)

        # ---- ❓ Help mode (DEL 21K): hover anything and it explains itself ----
        self.btn_help = tool_btn("❓", "Help mode: hover anything and it explains "
                                 "itself\n(F1 · Esc leaves it)",
                                 lambda: self.toggle_help_mode())
        self.btn_help.setFixedWidth(34)

        # ---- 📝 Saved words / snippets: quick access straight from the toolbar.
        #      Its menu shows the words saved for the ACTIVE PAGE and for ALL SITES
        #      at the top (click one to drop it into the focused field), then
        #      "Save a new word…" and "Manage saved words…". Same store as the page
        #      right-click menu's "Saved words / snippets". ----
        self.btn_snippets = tool_btn(
            "📝", "Saved words / snippets — this page's words, all-site words, "
            "save a new word, or manage the list",
            self._snippets_button_menu)
        self.btn_snippets.setFixedWidth(34)

        # ---- 📎 File sets (DEL 52): like snippets, but for FILES. A drop-down of
        #      named groups of files (e.g. "Instruction - Paperdoll" = three .md
        #      files); pick one and the next upload dialog on any site is answered
        #      with them, so you never switch to the file manager again. ----
        self.btn_filesets = tool_btn(
            "📎", "File sets — named groups of files to attach with one click, "
            "plus save a new set or manage the list",
            self._filesets_button_menu)
        self.btn_filesets.setFixedWidth(34)

        # ---- 📤 Bulk-upload progress (DEL 21J): hidden unless a run is on. Kept
        #      narrow - it only ever shows a short "📤 3/8" count while a run is
        #      live, so it no longer needs the old double-width slot. ----
        self.btn_upload = tool_btn("📤", "Bulk upload in progress",
                                   self._upload_marker_menu)
        self.btn_upload.setFixedWidth(46)
        self.btn_upload.setVisible(False)

        self.btn_cp = tool_btn("CP", "Copy/Paste field memory:\n"
                               "1) Click into a field, then click CP.\n"
                               "2) Nothing saved yet? Type a value, click CP again to save it.\n"
                               "3) Next time: click the field, then CP - it fills itself in.",
                               self._cp_click)
        self.btn_cp.setFixedWidth(42)

        # ---- "New tab" box: ALWAYS empty. Type an address + Enter and it opens
        #      in a NEW tab (you skip the "+" then type step). ----
        self.opentab = QLineEdit()
        self.opentab.setPlaceholderText("New tab ↗")
        self.opentab.setFixedWidth(150)
        self.opentab.setToolTip("Type an address here, press Enter to open it in a NEW tab\n"
                                "↑ / ↓ walks back through what you have typed (both boxes)\n"
                                "Right-click for the last 20")
        self.opentab.returnPressed.connect(self.navigate_newtab)
        self.opentab.textEdited.connect(
            lambda t, e=self.opentab: self._small_box_edited(e, t))
        self._wire_typed_history(self.opentab)
        self.nav.addWidget(self.opentab)

        # ---- Quick-entry box: ALWAYS empty. Type an address here and press
        #      Enter (or Go) - it loads in the CURRENT tab's big bar and clears
        #      itself, so you never have to select the old address first. ----
        self.quick = QLineEdit()
        self.quick.setPlaceholderText("This tab →")
        self.quick.setFixedWidth(150)
        self.quick.setToolTip("Type a new address here, press Enter (loads in THIS tab)\n"
                              "↑ / ↓ walks back through what you have typed (both boxes)\n"
                              "Right-click for the last 20")
        self.quick.returnPressed.connect(self.navigate_quick)
        self.quick.textEdited.connect(
            lambda t, e=self.quick: self._small_box_edited(e, t))
        self._wire_typed_history(self.quick)
        self.nav.addWidget(self.quick)

        self.btn_translate = tool_btn("🌍", "Translate this page (Google Translate)\n"
                                      "Right-click: translate selected text / change language",
                                      self._translate_page)
        self.btn_translate.setFixedWidth(34)
        self.btn_translate.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        self.btn_translate.customContextMenuRequested.connect(
            lambda _p: self._show_translate_menu())

        # ---- Profile badge (the letter/number shows which profile is active);
        #      sits right before the address bar. Click it for the profile menu. ----
        self.btn_profile = QPushButton("1")
        self.btn_profile.setToolTip("Profiles - click to switch or manage")
        self.btn_profile.setFixedSize(32, 30)
        self.btn_profile.setCursor(Qt.CursorShape.PointingHandCursor)
        # Badge CIRCLE: hover = the full profile menu (everything, incl. the
        # profile list); left-click = a quick switch to another profile.
        self.btn_profile.clicked.connect(self._click_profile_circle)
        self.btn_profile.installEventFilter(self)
        self._profile_hover = QTimer(self)
        self._profile_hover.setSingleShot(True)
        self._profile_hover.setInterval(400)
        self._profile_hover.timeout.connect(self._hover_full_menu)
        self._hover_watch = QTimer(self)                 # auto-close when mouse leaves
        self._hover_watch.setInterval(250)
        self._hover_watch.timeout.connect(self._check_hover_menu)
        self.nav.addWidget(self.btn_profile)

        # ---- Profile tag (the login/name text) sits between the badge circle and
        #      the address bar. Click it to type your login into the last-clicked
        #      web field. The badge NUMBER is omitted here (the circle shows it). ----
        self.btn_profiletag = QPushButton("")
        self.btn_profiletag.setCursor(Qt.CursorShape.PointingHandCursor)
        self.btn_profiletag.clicked.connect(self._insert_profile_login)
        self.nav.addWidget(self.btn_profiletag)

        # ---- Main address bar: shows the current page; click to place cursor ----
        self.address = QLineEdit()
        self.address.setPlaceholderText("Current address (click to edit)")
        self.address.setClearButtonEnabled(True)
        self.address.returnPressed.connect(self.navigate_from_address)
        self.address.textEdited.connect(
            lambda t, e=self.address: self._address_edited(e, t))
        # Leading icon: one click selects ALL the text in the bar (ready to copy).
        self._act_selectall = self.address.addAction(
            make_glyph_icon("🅰"),
            QLineEdit.ActionPosition.LeadingPosition)
        self._act_selectall.setToolTip("Select all text (ready to copy)")
        self._act_selectall.triggered.connect(self._address_select_all)
        # Second leading icon: select all AND copy to the clipboard in one click.
        self._act_copyall = self.address.addAction(
            make_glyph_icon("🅲"),
            QLineEdit.ActionPosition.LeadingPosition)
        self._act_copyall.setToolTip("Select all + copy to clipboard")
        self._act_copyall.triggered.connect(self._address_copy_all)
        # Right-click: Qt's own edit menu PLUS "bookmarks open, by default…"
        # and the two temp-tab shortcuts (DEL 44).
        self.address.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        self.address.customContextMenuRequested.connect(self._address_context_menu)
        self.nav.addWidget(self.address)

        # ---- Close-tab button: right next to the address bar so the mouse
#      never has to travel to the tab strip. Same as Ctrl+W / tab ✕.
        self.btn_closetab = QPushButton("✕")
        self.btn_closetab.setToolTip("Close this tab  (Ctrl+W)")
        self.btn_closetab.setFixedSize(28, 28)
        self.btn_closetab.setCursor(Qt.CursorShape.PointingHandCursor)
        self.btn_closetab.clicked.connect(
            lambda: self.close_tab(self.tabs.currentIndex()))
        self.nav.addWidget(self.btn_closetab)
        self._chrome_btns.append(self.btn_closetab)

        # ONE button for what used to be ☆ + 🔖 + 🕘 (the toolbar row was full):
        # its menu holds "Bookmark this page", Bookmarks ▸ and History ▸.
        self.btn_bm   = tool_btn("🔖", "Bookmark this page · Bookmarks · History",
                                 self.show_bookmarks_menu)
        self.btn_bm.setFixedWidth(34)
        self.btn_vault = tool_btn("🔒", "Passwords: click to unlock the vault",
                                  self.toggle_vault)
        self.btn_kbd = tool_btn("⌨", "On-screen keyboard - type login/password with the "
                                "mouse to defeat keyloggers (Ctrl+Shift+K)",
                                self.toggle_keyboard)
        self.btn_menu = tool_btn("☰", "Menu", self.show_main_menu)

        # ---- Bookmarks bar (Firefox-style row, toggle in the menu) ----
        self.bmbar = QToolBar("Bookmarks bar")
        self.bmbar.setMovable(False)
        self.bmbar.setIconSize(QSize(16, 16))
        self.bmbar.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        self.bmbar.customContextMenuRequested.connect(self._bmbar_context_menu)
        self._apply_bookmarks_position()        # places it: top (horizontal) or right (vertical)

        # ---- Tabs ----
        self.tabs = QTabWidget()
        self._tabbar = VerticalTabBar(self)         # horizontal-text side tabs option
        self.tabs.setTabBar(self._tabbar)
        self.tabs.setDocumentMode(True)
        self.tabs.setMovable(True)
        self.tabs.setTabsClosable(True)
        self.tabs.tabCloseRequested.connect(self.close_tab)
        self.tabs.currentChanged.connect(self.on_tab_changed)
        self.tabs.tabBar().setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        self.tabs.tabBar().customContextMenuRequested.connect(self._tab_context_menu)
        self._apply_tab_layout()        # Top vs Left (vertical) + elide

        # ---- Central layout: tabs + find bar ----
        central = QWidget()
        v = QVBoxLayout(central)
        v.setContentsMargins(0, 0, 0, 0)
        v.setSpacing(0)
        # Tabs on the left of a splitter; an optional SECOND page pane on the right.
        self.split = QSplitter(Qt.Orientation.Horizontal)
        self.split.addWidget(self.tabs)
        self.second_pane = QWidget()
        sp = QVBoxLayout(self.second_pane)
        sp.setContentsMargins(0, 0, 0, 0)
        sp.setSpacing(0)
        sp_bar = QHBoxLayout()
        sp_bar.setContentsMargins(4, 2, 4, 2)
        self.second_addr = QLineEdit()
        self.second_addr.setPlaceholderText("Second page address (Enter)")
        self.second_addr.returnPressed.connect(self._second_navigate)
        self.second_sync = QCheckBox("Sync scroll")
        self.second_sync.toggled.connect(self._toggle_sync_scroll)
        sp_close = QPushButton("✕")
        sp_close.setFixedWidth(28)
        sp_close.clicked.connect(self.toggle_split_view)
        for w in (self.second_addr, self.second_sync, sp_close):
            sp_bar.addWidget(w if w is self.second_addr else w, 1 if w is self.second_addr else 0)
        sp.addLayout(sp_bar)
        self._second_lay = sp
        self.second_view = None
        self.split.addWidget(self.second_pane)
        self.second_pane.hide()
        v.addWidget(self.split, 1)
        self.find_bar = FindBar(self)
        v.addWidget(self.find_bar)
        self.setCentralWidget(central)

        # ---- Status bar with a small progress hint ----
        self.status = QStatusBar()
        self.setStatusBar(self.status)

        self.apply_theme()              # paint everything from the active theme

    def apply_theme(self):
        """(Re)apply the active theme to every chrome widget, live."""
        self.nav.setStyleSheet(self._css_bar())
        for b in self._chrome_btns:
            b.setStyleSheet(self._css_navbtn())
        for b in self._accent_btns:
            b.setStyleSheet(self._css_accentbtn())
        self.btn_newtab.setStyleSheet(self._css_accentbtn() +
                                      "QPushButton{font-size:13pt; font-weight:bold;}")
        self.address.setStyleSheet(self._css_address())
        self.quick.setStyleSheet(self._css_quick())
        self.opentab.setStyleSheet(self._css_quick())
        self.tabs.setStyleSheet(self._css_tabs())
        self.status.setStyleSheet(self._css_status())
        # Bookmarks bar: clearly darker + a divider line so it stands apart
        # from the tab strip directly below it. Colour can be overridden globally
        # (right-click the bar) or per profile (Edit profile).
        bmbg = self._bar_colors()[0]
        self.bmbar.setStyleSheet(
            "QToolBar{background:%s; border:none; border-bottom:2px solid %s; "
            "padding:2px 4px;}" % (bmbg, shade(C_BAR_BG, 28)))
        try:
            self.find_bar.setStyleSheet("background:%s;" % C_BAR_BG)
        except Exception:
            pass
        self.build_bookmarks_bar()
        if hasattr(self, "btn_profile"):
            self._update_profile_badge()
        self._paint_lv_button()
        self._paint_vault_button()
        if hasattr(self, "btn_clean"):
            self._update_clean_button()
        # Refresh the blank page so it picks up new colors too.
        write_new_tab_page(self.settings.get("search_engine", SEARCH_URL))
        for i in range(self.tabs.count()):
            v = self.tabs.widget(i)
            if v and is_blank_page(v.url().toString()):
                v.reload()

    def _folder_menu(self, nodes, depth=1):
        """Build a (possibly nested) bookmark menu. Each level gets a lighter
        shade. Link items support middle/Ctrl-click = new tab and right-click =
        a small context menu (see BookmarkMenu)."""
        m = BookmarkMenu(self)
        m.nodes = nodes                 # DEL 55: right-click finds its node by index
        m.setStyleSheet(self._menu_style(depth))
        if not nodes:
            a = m.addAction("(empty)")
            a.setEnabled(False)
            return m
        links = [n["url"] for n in nodes if n.get("url")]
        if len(links) > 1:
            a = m.addAction("📑  Open all %d in tabs" % len(links))
            a.triggered.connect(lambda _=False, us=list(links): self._open_all_tabs(us))
            m.addSeparator()
        for i_node, n in enumerate(nodes[:400]):
            if "folder" in n:
                sub = self._folder_menu(n.get("folder", []), depth + 1)
                sub.setTitle("📁  " + (n.get("title") or "Folder")[:40])
                a_sub = m.addMenu(sub)
                a_sub.setProperty("wb_idx", i_node)
            elif n.get("url"):
                a = m.addAction((n.get("title") or n["url"])[:60])
                a.setData(n["url"])          # picked up by BookmarkMenu
                a.setProperty("wb_idx", i_node)
                if "fav_src" in n:
                    # Profile 99: keep the favourite's own login (DEL 21H).
                    a.setToolTip("%s\nopens as: %s"
                                 % (n["url"], n.get("fav_src_name") or "its own login"))
                    a.triggered.connect(
                        lambda _=False, nn=n: self._open_favourite_node(nn))
                else:
                    a.setToolTip(n["url"] + "    (middle-click = new tab)")
                    a.triggered.connect(lambda _=False, u=n["url"]: self._open_in_current(u))
        return m

    def _open_all_tabs(self, urls):
        opened = 0
        for u in urls[:25]:
            self.add_tab(u, switch=False)
            opened += 1
        show_toast(self, "Opened %d tab%s" % (opened, "" if opened == 1 else "s"))

    def build_bookmarks_bar(self):
        """Fill the Firefox-style bookmarks row: links as buttons, folders as
        dropdown menus."""
        if not hasattr(self, "bmbar"):
            return
        # Profile 99: regenerate from the starred list every time, so adding or
        # removing a favourite shows up here at once (DEL 21H).
        if self._is_fav_profile():
            self.bookmarks = self._favourites_bookmark_tree()
        self.bmbar.clear()
        self.bmbar.setVisible(bool(self.settings.get("show_bookmarks_bar", True)))
        bar_nodes = self.bookmarks.get("bar", []) if isinstance(self.bookmarks, dict) else []
        bmbg, bar_fg = self._bar_colors()            # profile override > global > default
        # Left-align labels (a straight line, not centred). Indent + link colour
        # are PER PROFILE (a folder-less profile can keep indent 0).
        prof = self._active_profile()
        align = "text-align:left;"
        indent = " " * int(prof.get("bookmark_indent", 0) or 0)
        link_col = prof.get("link_color")
        css = ("QPushButton{background:transparent; color:%s; border:none; %s "
               "padding:3px 9px; border-radius:5px; font-size:9pt;}"
               "QPushButton:hover{background:%s;}"
               "QPushButton::menu-indicator{width:0px;}" % (bar_fg, align, C_BTN_BG_HOV))
        # Plain links can use a distinct text colour (folders keep the bar colour).
        link_css = css
        if link_col:
            link_css = ("QPushButton{background:transparent; color:%s; border:none; %s "
                        "padding:3px 9px; border-radius:5px; font-size:9pt;}"
                        "QPushButton:hover{background:%s;}"
                        "QPushButton::menu-indicator{width:0px;}" % (link_col, align, C_BTN_BG_HOV))

        # (The profile tag now lives in the nav toolbar, between the profile
        #  badge and the address bar - see _update_profile_tag.)
        def item_css(node):
            c = node.get("color")
            if c:
                return ("QPushButton{background:%s; color:%s; border:none; %s padding:3px 9px;"
                        " border-radius:5px; font-size:9pt;}QPushButton:hover{background:%s;}"
                        "QPushButton::menu-indicator{width:0px;}"
                        % (c, node.get("textcolor") or contrast_fg(c), align, shade(c, 22)))
            return css

        # A "Bookmarks" folder at the start of the bar = everything in the
        # Bookmarks MENU (i.e. NOT the bar itself, so there's no infinite loop).
        # ⭐ FAVOURITES sits FIRST on the bar, before the bookmark folders. The
        # starred list used to live only in  ☰ menu -> ⭐ Favourites, which made
        # people star a page and then have no idea where it went. It is one
        # global list (every profile sees it), so it belongs in plain sight.
        # Turn it off in the bar's right-click menu if you want the space back.
        if self.settings.get("show_fav_bar_button", True):
            fbtn = QPushButton("⭐ Favourites%s ▾"
                               % ("  (%d)" % len(self.favourites) if self.favourites else ""))
            fbtn.setStyleSheet(css)
            fbtn.setCursor(Qt.CursorShape.PointingHandCursor)
            fbtn.setToolTip("Your starred links — one global list shared by every "
                            "profile.\nEach favourite opens with the login it was "
                            "saved under.\nCtrl+Shift+B opens the full window.")
            # Rebuilt on every click so it always shows the current list.
            fmenu = QMenu(fbtn)
            fmenu.setStyleSheet(self._menu_style(0))
            fmenu.aboutToShow.connect(
                lambda m=fmenu: (m.clear(), self._fill_favourites_menu(m, depth=0)))
            fbtn.setMenu(fmenu)
            self.bmbar.addWidget(fbtn)

        menu_nodes = self.bookmarks.get("menu", []) if isinstance(self.bookmarks, dict) else []
        if menu_nodes:
            bbtn = QPushButton("📚 Bookmarks ▾")
            bbtn.setStyleSheet(css)
            bbtn.setCursor(Qt.CursorShape.PointingHandCursor)
            bbtn.setMenu(self._folder_menu(menu_nodes))
            # DEL 55: right-click = drop a picked-up bookmark into this menu.
            bbtn.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
            bbtn.customContextMenuRequested.connect(
                lambda pos, b=bbtn: self._bm_bookmarks_btn_menu(b, pos))
            self.bmbar.addWidget(bbtn)

        # Tookmarks: an OPT-IN live folder of ONE chosen other profile's bookmarks,
        # sitting next to your own 📚 Bookmarks folder. Read-only, nothing copied.
        # PER PROFILE - pick / change which profile in Menu -> Tookmarks (or Settings).
        if self._active_profile().get("tookmarks_enabled"):
            tnodes = self._tookmarks_nodes()
            if tnodes:
                src = self._tookmarks_source_profile()
                tbtn = QPushButton("👻 Tookmarks ▾")
                tbtn.setStyleSheet(css)
                tbtn.setToolTip("Live view of %s's bookmarks — change the profile in "
                                "Menu → Tookmarks" % (src.get("name", "?") if src else "?"))
                tbtn.setCursor(Qt.CursorShape.PointingHandCursor)
                tbtn.setMenu(self._folder_menu(tnodes))
                self.bmbar.addWidget(tbtn)

        for node in bar_nodes[:60]:
            if node.get("section") is not None:
                # A coloured, non-clickable SECTION chip — groups the items after it
                # (use different colours instead of separators). Right-click to edit.
                col = node.get("color") or C_ACCENT
                lab = QPushButton(" " + (node.get("section") or "Section")[:20] + " ")
                lab.setStyleSheet(
                    "QPushButton{background:%s; color:%s; border:none; padding:3px 10px;"
                    " border-radius:8px; font-size:8pt; font-weight:bold;}"
                    "QPushButton::menu-indicator{width:0px;}"
                    % (col, node.get("textcolor") or contrast_fg(col)))
                lab.setCursor(Qt.CursorShape.ArrowCursor)
                lab.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
                lab.customContextMenuRequested.connect(
                    lambda pos, n=node, b=lab: self._bm_section_menu(n, b, pos))
                self.bmbar.addWidget(lab)
                continue
            if "folder" in node:
                # Folders sit flush at the left edge (no indent).
                btn = QPushButton("📁 " + (node.get("title") or "Folder")[:20] + " ▾")
                btn.setStyleSheet(item_css(node))
                btn.setCursor(Qt.CursorShape.PointingHandCursor)
                btn.setMenu(self._folder_menu(node.get("folder", [])))
            elif node.get("url"):
                # Plain LINKS get the indent (start N spaces in from the folder edge)
                # and the optional link colour (unless the item has its own colour).
                btn = QPushButton(indent + (node.get("title") or node["url"])[:22])
                # Profile 99: name the account, since the label may be cut short.
                if "fav_src" in node:
                    btn.setToolTip("%s\nopens as: %s"
                                   % (node["url"],
                                      node.get("fav_src_name") or "its own login"))
                else:
                    btn.setToolTip(node["url"])
                btn.setCursor(Qt.CursorShape.PointingHandCursor)
                btn.setStyleSheet(item_css(node) if node.get("color") else link_css)
                btn.clicked.connect(
                    lambda _=False, u=node["url"], n=node: self._open_bar_link(u, n))
            else:
                continue
            if node is getattr(self, "_bm_cut", None):      # DEL 55: the picked-up one
                btn.setStyleSheet(btn.styleSheet() +
                                  "QPushButton{border:1px dashed %s;}" % C_ACCENT)
            btn.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
            btn.customContextMenuRequested.connect(
                lambda pos, n=node, b=btn: self._bm_bar_menu(n, b, pos))
            self.bmbar.addWidget(btn)

    def _open_bar_link(self, url, node):
        """Open a bookmark-bar link in the way THIS bookmark asks for - its own
        'open by default' (same / new / temp tab) if it has one, otherwise the
        global default from Settings (or the address bar's right-click menu)."""
        # Profile 99: a generated favourite opens with ITS OWN login (DEL 21H).
        if "fav_src" in node:
            self._open_favourite_node(node)
            return
        self.open_url_in_mode(url, self._bm_open_mode(node))

    # ----------------------------------------------------- bookmark right-click ----
    def _bm_bar_menu(self, node, btn, pos):
        m = QMenu(self)
        m.setStyleSheet(self._menu_style())
        # Profile 99: these items are a generated view of the starred list, so
        # the usual bookmark edits would be thrown away on the next rebuild.
        # Offer the FAVOURITE's own actions instead (DEL 21H).
        if "fav_src" in node:
            m.addAction("🔗  Open  (as %s)" % (node.get("fav_src_name") or "its own login"),
                        lambda n=node: self._open_favourite_node(n))
            m.addSeparator()
            m.addAction("🗂  Favourites window...   (Ctrl+Shift+B)",
                        self.show_favourites_manager)
            m.addAction("🗑  Remove from Favourites",
                        lambda n=node: self._fav_remove(n.get("url"),
                                                        n.get("fav_src") or ""))
            m.exec(btn.mapToGlobal(pos))
            return
        is_link = "url" in node
        # DEL 55: while a bookmark is picked up, the drop-here entries come first.
        if self._bm_move_target_items(m, node,
                                      horizontal=self.settings.get("bookmarks_position") != "right"):
            m.addSeparator()
        if is_link:
            m.addAction("Open", lambda: self._open_bar_link(node["url"], node))
            # One-off opens, whatever this bookmark's default is
            m.addAction("↩  Open in the same tab",
                        lambda u=node["url"]: self.open_url_in_mode(u, "same"))
            m.addAction("🆕  Open in a new tab",
                        lambda u=node["url"]: self.open_url_in_mode(u, "new"))
            m.addAction("🕒  Open in the temp tab",
                        lambda u=node["url"]: self.open_url_in_mode(u, "temp"))
            # …and what a plain click on it should do from now on
            own = (node.get("open_mode") or
                   ("same" if node.get("same_tab") else "")).strip().lower()
            dm = m.addMenu("⚙  A plain click on this one opens…")
            dm.setStyleSheet(self._menu_style(1))
            a = dm.addAction(("●  " if not own else "     ")
                             + "Default for all bookmarks  (%s)"
                             % {"same": "same tab", "new": "new tab",
                                "temp": "temp tab"}[self._bookmark_open_default()])
            a.triggered.connect(lambda _=False, n=node: self._bm_set_open_mode(n, ""))
            dm.addSeparator()
            for mode, label in self.OPEN_MODES:
                a = dm.addAction(("●  " if mode == own else "     ") + label)
                a.triggered.connect(
                    lambda _=False, n=node, md=mode: self._bm_set_open_mode(n, md))
            m.addSeparator()
        m.addAction("✎  Rename...", lambda: self._bm_rename(node))
        if is_link:
            m.addAction("🔗  Edit address...", lambda: self._bm_edit_url(node))
        m.addAction("🎨  Set colour...", lambda: self._bm_color(node, False))
        m.addAction("🅰  Set text colour...", lambda: self._bm_color(node, True))
        if node.get("color") or node.get("textcolor"):
            m.addAction("⨯  Clear colour", lambda: self._bm_clear_color(node))
        if is_link:
            a_as = m.addAction("🚀  Open on startup")
            a_as.setCheckable(True)
            a_as.setChecked(bool(node.get("autostart")))
            a_as.triggered.connect(lambda v, n=node: self._bm_set_autostart(n, v))
        # Reorder within the bar (the bar shows the top-level 'bar' list).
        bar = self.bookmarks.get("bar", []) if isinstance(self.bookmarks, dict) else []
        idx = next((k for k, n in enumerate(bar) if n is node), -1)
        if idx >= 0 and len(bar) > 1:
            vert = self.settings.get("bookmarks_position") == "right"
            up_lbl = "🔼  Move up" if vert else "◀  Move left"
            dn_lbl = "🔽  Move down" if vert else "Move right  ▶"
            m.addSeparator()
            if idx > 0:
                m.addAction(up_lbl, lambda: self._bm_move(node, -1))
            if idx < len(bar) - 1:
                m.addAction(dn_lbl, lambda: self._bm_move(node, +1))
        # DEL 55: pick it up and put it anywhere (another folder, another place)
        if self._bm_can_move():
            m.addSeparator()
            self._bm_move_start_item(m, node)
        if is_link:
            m.addSeparator()
            prof = self._active_profile()
            if self._fav_has(node.get("url", ""), prof.get("id") or ""):
                a = m.addAction("⭐  Already in Favourites (this login)")
                a.setEnabled(False)
            else:
                m.addAction("⭐  Add to Favourites  (login: %s)"
                            % (prof.get("name") or "current"),
                            lambda n=node: self._fav_add(n.get("title"), n.get("url")))
            self._fav_login_menu(m, node.get("title"), node.get("url", ""),
                                 "⭐  Add to Favourites using login…")
        m.addSeparator()
        m.addAction("🗑  Delete", lambda: self._bm_delete(node))
        m.exec(btn.mapToGlobal(pos))

    def _bm_section_menu(self, node, btn, pos):
        """Right-click menu for a bookmark-bar SECTION chip."""
        m = QMenu(self)
        m.setStyleSheet(self._menu_style())
        # DEL 55: a section chip is a valid place to drop a picked-up bookmark.
        if self._bm_move_target_items(m, node,
                                      horizontal=self.settings.get("bookmarks_position") != "right"):
            m.addSeparator()
        m.addAction("✎  Rename section...", lambda: self._bm_rename_section(node))
        m.addAction("🎨  Set colour...", lambda: self._bm_color(node, False))
        m.addAction("🅰  Set text colour...", lambda: self._bm_color(node, True))
        bar = self.bookmarks.get("bar", []) if isinstance(self.bookmarks, dict) else []
        idx = next((k for k, n in enumerate(bar) if n is node), -1)
        if idx >= 0 and len(bar) > 1:
            m.addSeparator()
            if idx > 0:
                m.addAction("◀  Move left", lambda: self._bm_move(node, -1))
            if idx < len(bar) - 1:
                m.addAction("Move right  ▶", lambda: self._bm_move(node, +1))
        m.addSeparator()
        m.addAction("🗑  Delete section", lambda: self._bm_delete(node))
        m.exec(btn.mapToGlobal(pos))

    def _bm_bookmarks_btn_menu(self, btn, pos):
        """Right-click the 📚 Bookmarks button (DEL 55)."""
        m = QMenu(self)
        m.setStyleSheet(self._menu_style())
        menu_list = self.bookmarks.get("menu") if isinstance(self.bookmarks, dict) else None
        if not self._bm_move_end_item(m, menu_list, "the 📚 Bookmarks menu"):
            m.addAction("Nothing picked up — right-click a bookmark ▸ Move... first"
                        ).setEnabled(False)
        m.exec(btn.mapToGlobal(pos))

    def _bm_rename_section(self, node):
        name, ok = QInputDialog.getText(self, "Rename section", "Section name:",
                                        text=node.get("section", ""))
        if ok:
            node["section"] = name.strip()
            self._save_bm()
            self.build_bookmarks_bar()

    def _bm_add_section(self):
        """Add a new coloured section chip to the END of the bookmarks bar."""
        name, ok = QInputDialog.getText(self, "New section",
                                        "Section name (a coloured label on the bar):")
        if not ok or not name.strip():
            return
        col = QColorDialog.getColor(QColor(C_ACCENT), self, "Section colour")
        node = {"section": name.strip()}
        if col.isValid():
            node["color"] = col.name()
        self.bookmarks.setdefault("bar", []).append(node)
        self._save_bm()
        self.build_bookmarks_bar()
        show_toast(self, "Section added")

    def _bm_move(self, node, delta):
        """Swap a top-level bar bookmark with its neighbour (reorder the bar)."""
        bar = self.bookmarks.get("bar", [])
        i = next((k for k, n in enumerate(bar) if n is node), -1)
        if i < 0:
            return
        j = i + delta
        if 0 <= j < len(bar):
            bar[i], bar[j] = bar[j], bar[i]
            self._save_bm()
            self.build_bookmarks_bar()

    # *************** DEL 55 - MOVE A BOOKMARK WITH THE RIGHT-CLICK MENU *****************
    # Two clicks instead of opening the bookmark manager: right-click a bookmark
    # (or folder) -> "Move..." picks it up (it gets a dashed outline on the bar),
    # then right-click any other bookmark -> "Move here (above/below this one)",
    # a folder -> "Move into this folder", the bar's empty space -> "Move to the
    # end of the bar". Works in the bar AND in the folder dropdowns. No dragging.
    # ToDo (2026-11-05): Tookmarks / the generated 99 Favourites are read-only, so
    # they offer no move; sections can be a target but not be picked up (they
    # already have Move left/right).
    def _bm_can_move(self):
        return isinstance(self.bookmarks, dict) and not self._is_fav_profile()

    def _bm_parent_list(self, node):
        """The list (bar, menu or a folder's contents) that holds `node`, by
        identity - or None when the node is not in this profile's own tree."""
        def walk(lst):
            for n in lst:
                if n is node:
                    return lst
                if isinstance(n.get("folder"), list):
                    hit = walk(n["folder"])
                    if hit is not None:
                        return hit
            return None
        if not isinstance(self.bookmarks, dict):
            return None
        for key in ("bar", "menu"):
            hit = walk(self.bookmarks.get(key, []))
            if hit is not None:
                return hit
        return None

    def _bm_inside(self, node, lst):
        """True when `lst` is node's own folder list, or sits somewhere below it."""
        sub = node.get("folder")
        if not isinstance(sub, list):
            return False
        if sub is lst:
            return True
        return any(self._bm_inside(n, lst) for n in sub)

    @staticmethod
    def _bm_title(node, n=28):
        return (node.get("section") or node.get("title") or node.get("url") or "bookmark")[:n]

    def _bm_start_move(self, node):
        self._bm_cut = node
        QTimer.singleShot(0, self.build_bookmarks_bar)       # dashed outline
        show_toast(self, "✂  Moving “%s” — right-click where it should go, then "
                   "choose “Move here”" % self._bm_title(node), 5000)

    def _bm_cancel_move(self):
        self._bm_cut = None
        QTimer.singleShot(0, self.build_bookmarks_bar)
        show_toast(self, "Move cancelled")

    def _bm_move_to(self, target_list, ref=None, after=False):
        """Put the picked-up bookmark into `target_list`: before `ref` (or after
        it), or at the end when `ref` is None."""
        node = getattr(self, "_bm_cut", None)
        if node is None:
            return
        src = self._bm_parent_list(node) if self._bm_can_move() else None
        if src is None:
            self._bm_cut = None
            show_toast(self, "That bookmark is no longer in this profile — move cancelled")
            QTimer.singleShot(0, self.build_bookmarks_bar)
            return
        if ref is node:
            self._bm_cancel_move()
            return
        if self._bm_inside(node, target_list):
            show_toast(self, "A folder cannot be moved into itself — pick another place")
            return                                    # still picked up
        for i, n in enumerate(src):
            if n is node:
                del src[i]
                break
        idx = next((i for i, n in enumerate(target_list) if n is ref), None)
        if idx is None:
            target_list.append(node)
        else:
            target_list.insert(idx + 1 if after else idx, node)
        self._bm_cut = None
        self._save_bm()
        # Deferred like _bm_delete: an open menu must be gone before the bar's
        # buttons are rebuilt.
        QTimer.singleShot(0, self.build_bookmarks_bar)
        QTimer.singleShot(0, lambda t=self._bm_title(node): show_toast(self, "Moved “%s”" % t))

    def _bm_move_start_item(self, m, node, after=None):
        """Menu entry that picks `node` up (or cancels, if it is the picked one)."""
        if not self._bm_can_move() or "section" in node \
                or self._bm_parent_list(node) is None:
            return False
        if getattr(self, "_bm_cut", None) is node:
            m.addAction("✖  Cancel the move",
                        lambda: ((after() if after else None), self._bm_cancel_move()))
        else:
            m.addAction("✂  Move...   (then right-click where it should go)",
                        lambda n=node: ((after() if after else None), self._bm_start_move(n)))
        return True

    def _bm_move_target_items(self, m, ref, after=None, horizontal=False):
        """While a bookmark is picked up: entries that drop it next to / into
        `ref`. Returns True if anything was added."""
        cut = getattr(self, "_bm_cut", None)
        if cut is None or ref is cut or not self._bm_can_move():
            return False
        parent = self._bm_parent_list(ref)
        if parent is None:
            return False
        name = self._bm_title(cut)
        before_t, after_t = (("to the left of this one", "to the right of this one")
                             if horizontal else ("above this one", "below this one"))

        def go(fn):
            return lambda: ((after() if after else None), fn())
        m.addAction("📥  Move “%s” here — %s" % (name, before_t),
                    go(lambda: self._bm_move_to(parent, ref, False)))
        m.addAction("📥  Move “%s” here — %s" % (name, after_t),
                    go(lambda: self._bm_move_to(parent, ref, True)))
        if isinstance(ref.get("folder"), list):
            m.addAction("📁  Move “%s” into this folder" % name,
                        go(lambda: self._bm_move_to(ref["folder"])))
        m.addAction("✖  Cancel the move", go(self._bm_cancel_move))
        return True

    def _bm_move_end_item(self, m, target_list, where):
        """While a bookmark is picked up: 'move it to the end of <where>'."""
        cut = getattr(self, "_bm_cut", None)
        if cut is None or not self._bm_can_move() or target_list is None:
            return False
        m.addAction("📥  Move “%s” to the end of %s" % (self._bm_title(cut), where),
                    lambda: self._bm_move_to(target_list))
        m.addAction("✖  Cancel the move", self._bm_cancel_move)
        return True

    def _bm_rename(self, node):
        text, ok = QInputDialog.getText(self, "Rename bookmark", "Name:",
                                        text=node.get("title", ""))
        if ok and text.strip():
            node["title"] = text.strip()
            self._save_bm(); self.build_bookmarks_bar()

    def _bm_edit_url(self, node):
        text, ok = QInputDialog.getText(self, "Edit address", "URL:",
                                        text=node.get("url", ""))
        if ok and text.strip():
            node["url"] = text.strip()
            self._save_bm(); self.build_bookmarks_bar()

    def _bm_color(self, node, is_text):
        col = QColorDialog.getColor(parent=self,
                                    title="Text colour" if is_text else "Background colour")
        if col.isValid():
            node["textcolor" if is_text else "color"] = col.name()
            self._save_bm(); self.build_bookmarks_bar()

    def _bm_clear_color(self, node):
        node.pop("color", None); node.pop("textcolor", None)
        self._save_bm(); self.build_bookmarks_bar()

    def _bm_set_autostart(self, node, value):
        node["autostart"] = bool(value)
        if not value:
            node.pop("autostart", None)
        self._save_bm()
        self.build_bookmarks_bar()
        show_toast(self, "Open on startup: %s" % ("ON" if value else "OFF"))

    def _open_autostart_bookmarks(self):
        """Open bookmarks flagged 'autostart' that aren't already open."""
        open_urls = set()
        for i in range(self.tabs.count()):
            v = self.tabs.widget(i)
            if v:
                open_urls.add(v.url().toString())

        def collect(nodes, out):
            for n in nodes or []:
                if "folder" in n:
                    collect(n["folder"], out)
                elif n.get("autostart") and n.get("url"):
                    out.append(n["url"])
        wanted = []
        collect(self.bookmarks.get("bar", []), wanted)
        collect(self.bookmarks.get("menu", []), wanted)
        for u in wanted:
            if u not in open_urls:
                self.add_tab(u, switch=False)
                open_urls.add(u)

    def _bm_delete(self, node):
        for lst in (self.bookmarks.get("bar", []), self.bookmarks.get("menu", [])):
            if self._remove_node(lst, node):
                break
        self._save_bm()
        # Defer the bar rebuild by one event-loop tick so any open context menu
        # (and the QPushButton it popped from) can be fully closed/destroyed
        # before bmbar.clear() runs.  Without this, the button underlying the
        # menu is destroyed while the menu is still alive, which causes the
        # next folder button in the bar to lose its left-click open-menu
        # behaviour until the next full rebuild.
        QTimer.singleShot(0, self.build_bookmarks_bar)
        QTimer.singleShot(0, lambda: show_toast(self, "Bookmark deleted"))

    def _remove_node(self, lst, node):
        for i, n in enumerate(lst):
            if n is node:
                del lst[i]
                return True
            if "folder" in n and self._remove_node(n["folder"], node):
                return True
        return False

    def _find_node_by_url(self, lst, url):
        for n in lst:
            if n.get("url") == url:
                return n
            if "folder" in n:
                hit = self._find_node_by_url(n.get("folder", []), url)
                if hit:
                    return hit
        return None

    def _bm_rename_url(self, url):
        n = (self._find_node_by_url(self.bookmarks.get("bar", []), url)
             or self._find_node_by_url(self.bookmarks.get("menu", []), url))
        if n:
            self._bm_rename(n)

    def _bm_delete_url(self, url):
        n = (self._find_node_by_url(self.bookmarks.get("bar", []), url)
             or self._find_node_by_url(self.bookmarks.get("menu", []), url))
        if n:
            self._bm_delete(n)

    # ---- Favourites: one global collection shared by every profile ----------
    #  This is NOT a login profile: it is a single starred list (FAVOURITES_FILE)
    #  that every profile can see. "Add to Favourites" drops a copy here so your
    #  hand-picked links are reachable from any profile you switch to.
    def _save_favs(self):
        try:
            save_json(FAVOURITES_FILE, self.favourites)
        except Exception as e:
            log_line("favourites save error: %s" % e)

    # -- Each favourite remembers WHICH LOGIN it opens with (its "source") so the
    #    one shared list can hold, say, two Gmail accounts that share the same URL
    #    but belong to different profiles. source = an engine id: a profile id
    #    ("default"/pid), a container id ("ctr_…"), or "" (whatever profile is
    #    active when you open it). Opening a favourite binds its tab to that
    #    engine's cookie store WITHOUT switching your active profile, so several
    #    accounts of the same site can sit side by side in ONE window.
    def _engine_id_exists(self, eid):
        """True if `eid` names a login engine we can bind a tab to."""
        if not eid:
            return False
        if eid == "default":
            return True
        if self._container_by_id(eid):
            return True
        return any(p.get("id") == eid for p in self.settings.get("profiles", []))

    def _engine_label(self, eid):
        """Human name for a login engine id (container OR profile); None if gone."""
        c = self._container_by_id(eid)
        if c:
            return c.get("name") or "Container"
        for p in self.settings.get("profiles", []):
            if p.get("id") == eid:
                return p.get("name") or "Profile"
        return None

    def _fav_has(self, url, source="__any__"):
        """True if `url` is already a favourite. With `source` given, only counts
        an entry saved under that same login (so the same URL can be starred once
        per login)."""
        for f in self.favourites:
            if f.get("url") == url and (source == "__any__"
                                        or (f.get("source") or "") == (source or "")):
                return True
        return False

    def _fav_add(self, title, url, source=None, source_name=None):
        """Add a copy of a link to the global Favourites. If `source` is None the
        favourite is bound to the CURRENTLY active profile's login, so a link you
        star while signed in as one account reopens as that same account."""
        url = (url or "").strip()
        if not url:
            return
        if source is None:                          # default: bind to current login
            prof = self._active_profile()
            source = prof.get("id") or ""
            source_name = prof.get("name") or "Profile"
        if source_name is None:
            source_name = self._engine_label(source) or ""
        if self._fav_has(url, source):
            show_toast(self, "Already in Favourites for that login")
            return
        self.favourites.append({"title": (title or url).strip()[:120], "url": url,
                                "source": source or "",
                                "source_name": (source_name or "")[:24]})
        self._save_favs()
        # Say WHERE it went - the ⭐ button on the bookmarks bar - so a starred
        # page never feels like it vanished into a menu you have to hunt for.
        #
        # DEFERRED on purpose: this is usually called FROM the ⭐ menu, and
        # rebuilding the bar right now would destroy the button that owns the
        # still-open menu. Same trap (and same fix) as _bm_delete above.
        QTimer.singleShot(0, self.build_bookmarks_bar)   # refresh the ⭐ (n) counter
        show_toast(self, "⭐  Added to Favourites (login: %s) — see the ⭐ "
                         "Favourites button on the bookmarks bar, or Ctrl+Shift+B"
                   % (source_name or "current"), 2600)

    def _fav_remove(self, url, source="__any__"):
        before = len(self.favourites)
        self.favourites = [
            f for f in self.favourites
            if not (f.get("url") == url
                    and (source == "__any__"
                         or (f.get("source") or "") == (source or "")))]
        if len(self.favourites) != before:
            self._save_favs()
            # Deferred: this runs from inside the ⭐ menu (see _fav_add).
            QTimer.singleShot(0, self.build_bookmarks_bar)
            show_toast(self, "Removed from Favourites")

    def _fav_open(self, fav):
        """Open a favourite in a new tab, using the login it was saved under."""
        url = (fav.get("url") or "").strip()
        if not url:
            return
        src = fav.get("source") or ""
        # A favourite saved as "whichever profile is active" would land in
        # profile 99's OWN empty cookie jar - i.e. signed out - which is never
        # what was meant. In profile 99 such a link falls back to the startup
        # profile instead (DEL 21H).
        if not src and self._is_fav_profile():
            src = (self.settings.get("default_profile")
                   or (self.settings["profiles"][0].get("id") if
                       self.settings.get("profiles") else "") or "")
            if src == FAV_PROFILE_ID:
                src = "default"
        # Bind to the saved engine only when it's a DIFFERENT login than the one
        # we're already on (same login = a plain tab; no need to relabel it).
        if src and src != self.active_id and self._engine_id_exists(src):
            self.add_tab(url, switch=True, container=src)
        else:
            if src and src != self.active_id and not self._engine_id_exists(src):
                show_toast(self, "That login is gone — opening in the current one")
            self.add_tab(url, switch=True)

    def _fav_login_menu(self, parent_menu, title, url, label_prefix):
        """A slide-out that stars `url` under a login you pick (current profile,
        any other profile, or a container). Lets you gather every profile's
        favourites into the one list without switching profile first."""
        sub = parent_menu.addMenu(label_prefix)
        sub.setStyleSheet(self._menu_style(2))
        prof = self._active_profile()
        sub.addAction("👤  %s  (current)" % (prof.get("name") or "This profile"),
                      lambda _=False, t=title, u=url, s=prof.get("id"),
                      n=prof.get("name"): self._fav_add(t, u, s, n))
        others = [p for p in self.settings.get("profiles", [])
                  if p.get("id") != self.active_id]
        if others:
            sub.addSeparator()
            for p in others:
                sub.addAction("👤  %s" % (p.get("name") or "?"),
                              lambda _=False, t=title, u=url, s=p.get("id"),
                              n=p.get("name"): self._fav_add(t, u, s, n))
        cont = self._containers()
        if cont:
            sub.addSeparator()
            for c in cont:
                sub.addAction("🫙  %s" % (c.get("name") or "?"),
                              lambda _=False, t=title, u=url, s=c.get("id"),
                              n=c.get("name"): self._fav_add(t, u, s, n))
        return sub

    def _build_favourites_menu(self, parent_menu):
        """A '⭐ Favourites' slide-out for the ☰ menu. The menu itself is built by
        _fill_favourites_menu so the SAME menu can also hang off the ⭐ button on
        the bookmarks bar (see build_bookmarks_bar / DEL 21F)."""
        fm = parent_menu.addMenu("⭐  Favourites")
        fm.setStyleSheet(self._menu_style(1))
        self._fill_favourites_menu(fm, depth=1)
        return fm

    def _favourites_menu(self, depth=0):
        """A standalone ⭐ Favourites QMenu (for the bookmarks-bar button)."""
        fm = QMenu(self)
        fm.setStyleSheet(self._menu_style(depth))
        self._fill_favourites_menu(fm, depth=depth)
        return fm

    def _fill_favourites_menu(self, fm, depth=1):
        """Fill a ⭐ Favourites menu: open any favourite in a new tab (using its
        own saved login), manage the whole list, or remove one. Entries are
        grouped by login so two accounts of the same site are easy to tell
        apart."""
        cur = self.current_view()
        cur_url = cur.url().toString() if cur else ""
        if cur_url.startswith("http"):
            cur_title = (cur.title() if cur else "") or cur_url
            prof = self._active_profile()
            if self._fav_has(cur_url, prof.get("id") or ""):
                a = fm.addAction("✓  This page is a favourite (this login)")
                a.setEnabled(False)
            else:
                fm.addAction("⭐  Add THIS page to Favourites  (login: %s)"
                             % (prof.get("name") or "current"),
                             lambda _=False, t=cur_title, u=cur_url: self._fav_add(t, u))
            self._fav_login_menu(fm, cur_title, cur_url,
                                 "⭐  Add THIS page using login…")
            fm.addSeparator()
        if not self.favourites:
            a = fm.addAction("(no favourites yet — right-click a bookmark or a "
                             "page → ⭐ Add to Favourites)")
            a.setEnabled(False)
            fm.addSeparator()
            fm.addAction("🗂  Open the Favourites window...", self.show_favourites_manager)
            return
        # Group by login so each account's links sit together.
        groups = {}
        for f in self.favourites[:400]:
            key = f.get("source") or ""
            groups.setdefault(key, []).append(f)
        multi = len(groups) > 1
        for key, items in groups.items():
            name = (items[0].get("source_name")
                    or self._engine_label(key) or "Current login")
            if multi:
                grp = fm.addMenu("👤  %s  (%d)" % (name, len(items)))
                grp.setStyleSheet(self._menu_style(depth + 1))
            else:
                grp = fm
            for f in items:
                a = grp.addAction((f.get("title") or f.get("url") or "?")[:60])
                a.setToolTip(f.get("url") or "")
                a.triggered.connect(lambda _=False, ff=f: self._fav_open(ff))
        fm.addSeparator()
        # ONE window that shows every favourite at once (what the ⭐ list really
        # is: a single starred collection, not a per-profile thing).
        fm.addAction("🗂  Open the Favourites window...   (Ctrl+Shift+B)",
                     self.show_favourites_manager)
        rm = fm.addMenu("🗑  Remove a favourite...")
        rm.setStyleSheet(self._menu_style(depth + 1))
        for f in self.favourites[:400]:
            lbl = (f.get("title") or f.get("url") or "?")[:44]
            sn = f.get("source_name") or self._engine_label(f.get("source") or "")
            if sn:
                lbl += "  · %s" % sn[:14]
            a = rm.addAction(lbl)
            a.triggered.connect(
                lambda _=False, u=f.get("url"), s=f.get("source") or "":
                self._fav_remove(u, s))

# ****************************************************************************
#  DEL 21F - FAVOURITES WINDOW  (see every starred link in ONE place)
#
#  Favourites were only reachable through  ☰ menu -> ⭐ Favourites, so starring
#  a page felt like it went nowhere. Two things fix that:
#    1) a ⭐ Favourites button at the LEFT END OF THE BOOKMARKS BAR
#       (build_bookmarks_bar), and
#    2) this window - the whole starred collection at once, grouped by the
#       login each link opens with, with rename / re-assign / remove / reorder.
#  Open it with Ctrl+Shift+F, from the ⭐ menu, or by right-clicking the bar.
# ****************************************************************************

# ****************************************************************************
#  DEL 21H - THE "99  FAVOURITES" PROFILE
#
#  Switch to profile 99 and your whole starred list IS the bookmarks bar. Every
#  link still opens with the account it was saved under, so the Tradera link
#  saved as "BGGgeekmarket" opens logged in as BGGgeekmarket even though you
#  are "in" profile 99.
#
#  WHY IT IS A VIEW AND NOT A COPY  (this is the part worth understanding)
#  A profile IS a cookie jar. Logins and passwords are not files that can be
#  gathered up and moved - they are cookies inside ONE Chromium storage, and
#  two accounts on the same site cannot live in the same jar (tradera.com can
#  only hold one "logged in as" cookie at a time). So a profile that physically
#  held every account's logins is not possible - not a limitation of this
#  program, but of how logins work.
#
#  What IS possible is what profile 99 does: it holds no logins of its own and
#  lends each link the jar it came from. Opening a favourite here binds that
#  TAB to its original engine (_fav_open), exactly as the ⭐ menu already did.
#  The result is what you actually wanted - one place with everything, each
#  item still signed in as the right account, several accounts of the same site
#  open side by side in one window.
#
#  Consequences to know:
#   * the bookmarks in profile 99 are GENERATED from favourites.json on every
#     rebuild and are never written to disk - editing them edits the favourite;
#   * a NEW address you type while in profile 99 uses profile 99's own empty
#     jar, i.e. signed out. That is the honest behaviour: there is no account
#     to guess. Star it from a real profile first, or switch to that profile.
# ****************************************************************************

    def _ensure_favourites_profile(self):
        """Create the 99 Favourites profile once, unless it was turned off."""
        if not self.settings.get("fav_profile_enabled", True):
            return
        profs = self.settings.setdefault("profiles", [])
        for p in profs:
            if p.get("id") == FAV_PROFILE_ID:
                p["is_favourites"] = True        # keep the marker if hand-edited
                return
        profs.append({
            "id": FAV_PROFILE_ID,
            "name": "Favourites",
            "badge": "99",
            "color": "#f5b301",                  # gold - stands out from the rest
            "enabled": True,
            "is_favourites": True,
        })
        save_json(SETTINGS_FILE, self.settings)
        log_line("created the 99 Favourites profile")

    def _is_fav_profile(self, prof=None):
        prof = prof if prof is not None else self._active_profile()
        return bool(prof.get("is_favourites")) or prof.get("id") == FAV_PROFILE_ID

    def _engine_colour(self, eid):
        """The colour of a login engine (profile or container), or None. Note
        this is a STRICT lookup - _profile_by_id falls back to the first profile,
        which would quietly paint an unknown login in someone else's colour."""
        if not eid:
            return None
        for p in self.settings.get("profiles", []):
            if p.get("id") == eid:
                return p.get("color")
        c = self._container_by_id(eid)
        return c.get("color") if c else None

    def _favourites_bookmark_tree(self):
        """Build profile 99's bookmarks FROM the starred list. Each link carries
        'fav_src' = the engine it must open with, and is painted in that login's
        colour so the accounts are told apart at a glance.

        A login with SEVERAL favourites becomes a folder; a login with just one
        goes straight on the bar. Folding a single link into a folder would mean
        two clicks to reach one page, which is what the ⭐ menu already made you
        do and the whole point here is to stop that."""
        groups = {}
        for f in self.favourites:
            groups.setdefault(f.get("source") or "", []).append(f)

        # The bookmarks bar cuts labels at 22 characters, so gluing the login
        # onto the title ("Tradera | Köp & sälj b…") loses the very part that
        # tells two accounts apart. The duplicates that matter share the same
        # ADDRESS, not the same title - the whole point of favourites is that
        # one URL can be starred once per login. When an address appears more
        # than once the login IS the only difference, so it becomes the label.
        seen = {}
        for f in self.favourites:
            key = (f.get("url") or "").strip().lower().rstrip("/")
            seen[key] = seen.get(key, 0) + 1

        def link(f, with_login=False):
            src = f.get("source") or ""
            name = f.get("source_name") or self._engine_label(src) or ""
            title = (f.get("title") or f.get("url") or "?")[:60]
            ambiguous = seen.get((f.get("url") or "").strip().lower().rstrip("/"), 0) > 1
            if with_login and name and ambiguous:
                title = name[:40]
            node = {"title": title,
                    "url": f.get("url") or "",
                    "fav_src": src,
                    "fav_src_name": name}
            col = self._engine_colour(src)
            if col:
                node["color"] = col
            return node

        bar = []
        for key, items in groups.items():
            if len(items) == 1:
                bar.append(link(items[0], with_login=True))
                continue
            name = (items[0].get("source_name")
                    or self._engine_label(key) or "Current login")
            folder = {"title": "👤 %s" % name[:22],
                      "folder": [link(f) for f in items]}
            col = self._engine_colour(key)
            if col:
                folder["color"] = col
            bar.append(folder)
        return {"bar": bar, "menu": []}

    def _open_favourite_node(self, node):
        """Open a generated profile-99 bookmark with ITS OWN login."""
        self._fav_open({"url": node.get("url"),
                        "source": node.get("fav_src") or "",
                        "source_name": node.get("fav_src_name") or ""})

    def _toggle_fav_profile(self, on):
        """Turn the 99 Favourites profile on or off."""
        self.settings["fav_profile_enabled"] = bool(on)
        if on:
            self._ensure_favourites_profile()
            show_toast(self, "Profile 99 “Favourites” is back")
        else:
            if self.active_id == FAV_PROFILE_ID:
                for p in self.settings.get("profiles", []):
                    if p["id"] != FAV_PROFILE_ID and p.get("enabled", True):
                        self.switch_profile(p["id"])
                        break
            self.settings["profiles"] = [p for p in self.settings.get("profiles", [])
                                         if p.get("id") != FAV_PROFILE_ID]
            show_toast(self, "Profile 99 “Favourites” removed (your favourites are kept)")
        save_json(SETTINGS_FILE, self.settings)
        self._update_profile_badge()

    # ------------------------------------------- in-page pop-up killer (DEL 21L) ----
    def enter_popupkill_mode(self, view=None):
        """Point at the advert box and choose what should happen to it."""
        view = view or self.current_view()
        if not view:
            return
        try:
            view.page().runJavaScript(POPUP_KILL_PICK_SCRIPT)
            # Two ways to reach Esc: give the web content focus so the page's own
            # keydown fires, AND install an app-level filter so Esc cancels even
            # when focus is still on the window chrome after the right-click menu.
            try:
                view.setFocus(Qt.FocusReason.OtherFocusReason)
            except Exception:
                pass
            self._popupkill_view = view
            self._popupkill_mode = True
            QApplication.instance().installEventFilter(self)
            show_toast(self, "Click the pop-up you want rid of · Esc cancels", 2600)
        except Exception as e:
            log_line("popup kill pick: %s" % e)

    def _end_popupkill_mode(self):
        """Leave the pop-up picker: drop the app filter and tear down the page
        overlay. Safe to call more than once."""
        if not getattr(self, "_popupkill_mode", False):
            return
        self._popupkill_mode = False
        # Only relinquish the app filter if help mode isn't also using it.
        if not getattr(self, "_help_mode", False):
            try:
                QApplication.instance().removeEventFilter(self)
            except Exception:
                pass
        v = getattr(self, "_popupkill_view", None)
        self._popupkill_view = None
        if v:
            try:
                # Cancel whichever picker is up (killer OR "remember a choice").
                v.page().runJavaScript(
                    "try{if(window.__wbKillCancel)window.__wbKillCancel();}catch(e){}"
                    "try{if(window.__wbClickCancel)window.__wbClickCancel();}catch(e){}")
            except Exception:
                pass

    # ---- "Remember a choice": auto-click one button for me (DEL 21L-b) ----
    def enter_autoclick_mode(self, view=None):
        """Point at a button (e.g. your region) and WhyBrowse clicks it for you
        whenever it reappears - the clean fix for a MANDATORY box that blinks
        back after remove/close."""
        view = view or self.current_view()
        if not view:
            return
        try:
            view.page().runJavaScript(AUTOCLICK_PICK_SCRIPT)
            try:
                view.setFocus(Qt.FocusReason.OtherFocusReason)
            except Exception:
                pass
            self._popupkill_view = view
            self._popupkill_mode = True
            QApplication.instance().installEventFilter(self)
            show_toast(self, "Click the button to remember (e.g. your region) · "
                       "Esc cancels", 3000)
        except Exception as e:
            log_line("autoclick pick: %s" % e)

    def _autoclick_picked(self, view, payload):
        """The picker reported the button to remember. Save it and start clicking
        it for this site."""
        self._end_popupkill_mode()
        try:
            view.page().runJavaScript(
                "try{if(window.__wbOrigTitle)document.title=window.__wbOrigTitle;}catch(e){}")
        except Exception:
            pass
        try:
            info = json.loads(payload)
        except Exception as e:
            log_line("autoclick payload: %s" % e)
            return
        host = clean_host(view.url().host())
        if not host:
            return
        sel = (info.get("sel") or "").strip()
        if not sel:
            return
        matches = int(info.get("matches") or 0)
        label = (info.get("label") or "").strip()
        # Auto-clicking several elements at once is never wanted - refuse it.
        if matches != 1:
            show_toast(self, "Couldn't pin that to one button (it matches %d). "
                       "Try clicking the button's own text." % matches, 4000)
            return
        rules = self.settings.setdefault("popup_killers", {}).setdefault(host, [])
        # Replace any existing autoclick rule for the same target, don't stack them.
        rules[:] = [r for r in rules
                    if not (r.get("mode") == "autoclick" and r.get("sel") == sel)]
        rules.append({"sel": sel, "mode": "autoclick", "close_sel": "",
                      "label": (label[:40] or sel[:40])})
        save_json(SETTINGS_FILE, self.settings)
        self._apply_popupkill(view)
        show_toast(self, "Will click “%s” for you on %s every time — undo it in "
                   "the page's right-click menu" % (label[:30] or sel[:20], host), 3600)

    def _popupkill_rules(self, host):
        return (self.settings.get("popup_killers") or {}).get(
            clean_host(host) or "", [])

    def _popupkill_picked(self, view, payload):
        """The picker reported a box. Offer the two ways of dealing with it."""
        # The pick is done: drop the app-level Esc filter before the modal opens
        # (the dialog has its own Esc = Cancel).
        self._end_popupkill_mode()
        # Put the page's own title back (the picker borrowed it to report).
        try:
            view.page().runJavaScript(
                "try{if(window.__wbOrigTitle)document.title=window.__wbOrigTitle;}catch(e){}")
        except Exception:
            pass
        try:
            info = json.loads(payload)
        except Exception as e:
            log_line("popup kill payload: %s" % e)
            return
        host = clean_host(view.url().host())
        if not host:
            return
        sel = (info.get("sel") or "").strip()
        if not sel:
            return
        matches = int(info.get("matches") or 0)
        close_sel = (info.get("close_sel") or "").strip()
        close_label = (info.get("close_label") or "").strip()
        preview = (info.get("text") or "").strip()

        dlg = QDialog(self)
        dlg.setWindowTitle("Pop-up killer")
        dlg.setStyleSheet(dialog_qss())
        apply_window_icon(dlg)
        dlg.setModal(True)
        dlg.resize(560, 100)
        lay = QVBoxLayout(dlg)
        lay.addWidget(QLabel(
            "<b style='color:%s;'>What should happen to this pop-up on %s?</b>"
            % (C_ACCENT, host)))
        if preview:
            pv = QLabel("“%s…”" % preview[:80])
            pv.setStyleSheet("color:%s;font-size:8pt;" % dim_fg())
            pv.setWordWrap(True)
            lay.addWidget(pv)

        # A selector matching several elements is how a QR code gets hidden by
        # accident. Refuse it rather than let that happen quietly.
        if matches > 1:
            warn = QLabel(
                "⚠  This description matches <b>%d</b> things on the page, not just "
                "this one. Removing it could take something you need with it (a QR "
                "code, for example). Only “click its X” is offered." % matches)
            warn.setStyleSheet("color:#fbbf24;")
            warn.setWordWrap(True)
            lay.addWidget(warn)

        choice = {"v": None}

        def pick(v):
            choice["v"] = v
            dlg.accept()

        if matches <= 1:
            b_rm = QPushButton("🚫  Remove it — never show this box again")
            b_rm.setStyleSheet("QPushButton{background:%s;color:%s;border:none;"
                               "padding:9px 14px;border-radius:6px;}"
                               "QPushButton:hover{background:%s;}"
                               % (C_ACCENT, C_ACCENT_FG, C_ACCENT_HOV))
            b_rm.clicked.connect(lambda: pick("remove"))
            lay.addWidget(b_rm)

        if close_sel:
            b_cl = QPushButton("✖  Click its own X for me%s"
                               % ("  (“%s”)" % close_label if close_label else ""))
            b_cl.setStyleSheet("QPushButton{background:%s;color:%s;border:none;"
                               "padding:9px 14px;border-radius:6px;}"
                               "QPushButton:hover{background:%s;}"
                               % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
            b_cl.clicked.connect(lambda: pick("close"))
            lay.addWidget(b_cl)
            hint = QLabel("Clicking its X is the safer one: the box still appears "
                          "for a blink, but the page runs its own tidy-up, so "
                          "anything that depends on it closing properly still works.")
        else:
            hint = QLabel("This box has no close button that could be found, so "
                          "only removing it is offered.")
        hint.setStyleSheet("color:%s;font-size:8pt;" % dim_fg())
        hint.setWordWrap(True)
        lay.addWidget(hint)

        b_cancel = QPushButton("Cancel")          # normal colour
        b_cancel.clicked.connect(dlg.reject)
        lay.addWidget(b_cancel)
        QShortcut(QKeySequence("Escape"), dlg, activated=dlg.reject)
        dlg.exec()

        if not choice["v"]:
            return
        rules = self.settings.setdefault("popup_killers", {}).setdefault(host, [])
        rules.append({"sel": sel, "mode": choice["v"], "close_sel": close_sel,
                      "label": (preview[:40] or sel[:40])})
        save_json(SETTINGS_FILE, self.settings)
        self._apply_popupkill(view)
        show_toast(self, "Pop-up rule saved for %s (%s) — undo it in the page's "
                   "right-click menu" % (host, choice["v"]), 3000)

    def _apply_popupkill(self, view):
        """Push this site's rules into the page (re-applied there on any change)."""
        if not view:
            return
        # Plain mode = a plain browser: no injected scripts do anything at
        # all, including saved pop-up/element-hide rules. _content_cfg()
        # already zeroes elementHide/adblock/cosmetic for clean mode, but
        # this popup-kill path is separate and was never checked - so a
        # saved rule (e.g. one written for a harmless cookie box) kept
        # running unconditionally on every load, even in Plain mode, and
        # could end up matching something else entirely on a site whose
        # class names are generic/reused (autoclicking or removing the
        # wrong element). Bail out here so Plain mode really means nothing
        # runs.
        if self._clean_active():
            return
        try:
            host = clean_host(view.url().host())
            if self._crash_has(host, "popup", "postload"):      # DEL 56
                return
            rules = self._popupkill_rules(host)
            if not rules:
                return
            js = POPUP_KILL_APPLY_SCRIPT.replace("__RULES__", json.dumps(rules))
            view.page().runJavaScript(js)
        except Exception as e:
            log_line("popup kill apply: %s" % e)

    def _popupkill_clear(self, host):
        host = clean_host(host) or ""
        (self.settings.get("popup_killers") or {}).pop(host, None)
        save_json(SETTINGS_FILE, self.settings)
        show_toast(self, "Pop-up rules cleared for %s — reloading" % host)
        v = self.current_view()
        if v:
            v.reload()

    def _popupkill_remove_one(self, host, sel):
        host = clean_host(host) or ""
        rules = (self.settings.get("popup_killers") or {}).get(host, [])
        (self.settings.get("popup_killers") or {})[host] = [
            r for r in rules if r.get("sel") != sel]
        save_json(SETTINGS_FILE, self.settings)
        show_toast(self, "Rule removed — reloading")
        v = self.current_view()
        if v:
            v.reload()

    # ------------------------------------------------ "?" hover help (DEL 21K) ----
    def toggle_help_mode(self, on=None):
        """? mode: hover anything and it explains itself."""
        want = (not getattr(self, "_help_mode", False)) if on is None else bool(on)
        self._help_mode = want
        if want:
            if getattr(self, "_help_panel", None) is None:
                self._help_panel = HelpHoverPanel(self)
            QApplication.instance().installEventFilter(self)
            show_toast(self, "❓  Help mode ON — hover anything. Esc to leave.", 2600)
        else:
            try:
                QApplication.instance().removeEventFilter(self)
            except Exception:
                pass
            p = getattr(self, "_help_panel", None)
            if p:
                p.hide()
            show_toast(self, "Help mode off")
        btn = getattr(self, "btn_help", None)
        if btn is not None:
            btn.setStyleSheet(
                ("QPushButton{background:%s;color:%s;border:none;border-radius:6px;}"
                 % (C_ACCENT, C_ACCENT_FG)) if want else "")

    def eventFilter(self, obj, event):
        """While ? mode is on, watch what the mouse moves over. Everything here
        is defensive: help must never be able to break browsing."""
        try:
            if getattr(self, "_popupkill_mode", False):
                if (event.type() == QEvent.Type.KeyPress
                        and event.key() == Qt.Key.Key_Escape):
                    self._end_popupkill_mode()
                    show_toast(self, "Pop-up picker cancelled")
                    return True                      # swallow, don't leak Esc onward
            if getattr(self, "_help_mode", False):
                et = event.type()
                if et == QEvent.Type.KeyPress and event.key() == Qt.Key.Key_Escape:
                    self.toggle_help_mode(False)
                    return False
                if et in (QEvent.Type.Enter, QEvent.Type.ToolTip):
                    self._help_describe(obj)
                elif et == QEvent.Type.MouseMove and isinstance(obj, QMenu):
                    # Menus don't send Enter per entry - read the active one.
                    act = obj.activeAction()
                    if act is not None and act is not getattr(self, "_help_last_act", None):
                        self._help_last_act = act
                        self._help_describe_text(
                            act.text(), act.toolTip() if act.toolTip() != act.text() else "")
        except Exception:
            pass
        return super().eventFilter(obj, event)

    # Toolbar controls named EXACTLY, because guessing from their wording is
    # unreliable where two of them are near-identical: the only difference
    # between the two address boxes is "THIS tab" versus "NEW tab", and the
    # word that separates them is exactly the kind of filler the fuzzy lookup
    # has to ignore to work at all. Fuzzy matching stays for everything else
    # (menu entries, bookmarks, dialogs), where there is nothing to map.
    _HELP_WIDGET_FEATURES = {
        "btn_popup":   "Junk sites & popup guard",
        "btn_upload":  "Bulk upload",
        "btn_help":    "Keyboard shortcuts",
        "opentab":     "New-tab field",
        "quick":       "Quick-navigate",
        "address":     "Address bar",
        "btn_bm":      "Bookmarks",
        "btn_filesets": "File sets",
        "btn_dl":      "Downloads",
        "btn_vault":   "Password vault",
        "btn_kbd":     "Virtual keyboard",
        "btn_lv":      "Low-vision",
        "btn_cp":      "CP — Copy-Paste",
        "btn_snippets": "Snippets",
        "btn_translate": "Translate",
        "btn_tablist": "Tab list",
        "btn_clean":   "Clean / plain mode",
        "btn_mute":    "Mute / volume",
        "btn_pin":     "Pin a tab",
        "btn_pip":     "Pop out",
        "btn_profile": "Profile badge",
        "btn_settings": "Feature toggles",
    }

    def _help_feature_for_widget(self, obj):
        """The feature entry a known toolbar control belongs to, or None."""
        cache = getattr(self, "_help_widget_cache", None)
        if cache is None:
            cache = {}
            for attr, needle in self._HELP_WIDGET_FEATURES.items():
                w = getattr(self, attr, None)
                if w is not None:
                    cache[id(w)] = needle
            self._help_widget_cache = cache
        needle = cache.get(id(obj))
        if not needle:
            return None
        for name, where, desc, _keys in FEATURE_INDEX:
            if needle.lower() in name.lower():
                return (name, where, desc)
        return None

    def _help_describe(self, obj):
        """Explain a hovered widget: its own tooltip, plus the matching entry
        from the feature index underneath."""
        if not isinstance(obj, QWidget):
            return
        known = self._help_feature_for_widget(obj)
        if known:
            panel = getattr(self, "_help_panel", None)
            if panel is not None:
                name, where, desc = known
                try:
                    tip = (obj.toolTip() or "").strip()
                except Exception:
                    tip = ""
                panel.show_for(name, where, tip or desc[:150],
                               desc if tip else "", QCursor.pos())
            return
        if getattr(self, "_help_panel", None) is not None and \
                self._help_panel.isAncestorOf(obj):
            return                                  # don't explain the panel itself
        label = ""
        for getter in ("text", "placeholderText", "windowTitle"):
            try:
                v = getattr(obj, getter, None)
                if callable(v):
                    label = (v() or "").strip()
                    if label:
                        break
            except Exception:
                pass
        try:
            tip = (obj.toolTip() or "").strip()
        except Exception:
            tip = ""
        if not label and not tip:
            return
        self._help_describe_text(label, tip)

    def _help_describe_text(self, label, tip):
        panel = getattr(self, "_help_panel", None)
        if panel is None:
            return
        hits = help_lookup((label + " " + tip).strip(), 1)
        if hits:
            name, where, desc = hits[0]
        elif tip:
            name, where, desc = (label or "This control"), "", ""
        else:
            return
        # The tooltip is the immediate answer; the index entry is the depth.
        short = tip or (desc[:150] + "…" if len(desc) > 150 else desc)
        full = desc if (tip and desc) else ""
        panel.show_for(name if hits else (label or "This control"),
                       where if hits else "", short, full, QCursor.pos())

    # ------------------------------------------- bulk upload queue (DEL 21J) ----
    def start_bulk_upload(self):
        """Pick every picture ONCE; from here on the site's file dialog is
        answered from the queue instead of opening."""
        v = self.current_view()
        if not v:
            return
        host = clean_host(v.url().host())
        start = ((self.settings.get("upload_dirs") or {}).get(host)
                 or self.settings.get("upload_last") or "")
        if not start or not os.path.isdir(start):
            start = os.path.expanduser("~")
        files, _ = QFileDialog.getOpenFileNames(
            self, "Pick every file to upload (they are sent one after another)",
            start, "Images (*.jpg *.jpeg *.png *.gif *.webp *.bmp);;All files (*.*)")
        if not files:
            return
        self._upload_queue = list(files)
        self._bulk_total = len(files)
        self._bulk_sent = 0
        self._bulk_host = host
        base = os.path.dirname(files[0])
        if base:
            self.settings["upload_last"] = base
            save_json(SETTINGS_FILE, self.settings)
        self._update_upload_marker()
        QMessageBox.information(
            self, "Bulk upload — %d file%s queued" % (len(files),
                                                      "" if len(files) == 1 else "s"),
            "%d files are queued for %s.\n\n"
            "From now on the file dialog will NOT appear: each time the page asks "
            "for a file, the next one in the queue is handed over automatically.\n\n"
            "Just use the site's own \"add image\" button as usual — WhyBrowse will "
            "also try to press it for you between files. If it can't (browsers "
            "restrict opening a file dialog on their own), click it yourself; you "
            "still never have to find the folder or the file again.\n\n"
            "The 📤 button in the toolbar shows the progress and can stop the run."
            % (len(files), host or "this site"))
        self._bulk_advance()

    def _bulk_advance(self):
        """Press the site's own "add image" control so the next file goes without
        you touching anything. The press has to be a REAL mouse event posted to
        the render widget - a scripted click is ignored by the picker (measured;
        see the note above BULK_UPLOAD_TARGET_JS) - so JavaScript only reports
        where the control is and the click itself happens here."""
        if not getattr(self, "_upload_queue", None):
            return
        if not self.settings.get("bulk_autoadvance", True):
            return
        v = self.current_view()
        if not v or getattr(v, "_asleep", False):
            return

        def done(res):
            if not res or res == "noinput":
                log_line("bulk upload: no file control found on the page")
                show_toast(self, "📤  %d left — click the site's “add image” once"
                           % len(getattr(self, "_upload_queue", []) or []), 2800)
                return
            try:
                spot = json.loads(res)
            except Exception:
                return
            self._click_page_point(v, float(spot["x"]), float(spot["y"]))
        try:
            v.page().runJavaScript(BULK_UPLOAD_TARGET_JS, done)
        except Exception as e:
            log_line("bulk advance: %s" % e)

    def _click_page_point(self, view, css_x, css_y):
        """A genuine left-click at a point given in the page's own CSS pixels.

        Two things matter and are easy to get wrong:
          * the event must go to view.focusProxy() - the actual render widget.
            Sent to the view itself it is swallowed (the same trap the find-bar
            hit with synthetic key events);
          * CSS pixels are not widget pixels once the page is zoomed, so the
            point is scaled by the tab's zoom factor."""
        try:
            target = view.focusProxy() or view
            zoom = float(view.zoomFactor() or 1.0)
            pt = QPointF(css_x * zoom, css_y * zoom)
            glob = view.mapToGlobal(pt.toPoint()).toPointF()
            for typ in (QEvent.Type.MouseButtonPress, QEvent.Type.MouseButtonRelease):
                ev = QMouseEvent(typ, pt, glob,
                                 Qt.MouseButton.LeftButton, Qt.MouseButton.LeftButton,
                                 Qt.KeyboardModifier.NoModifier)
                QApplication.sendEvent(target, ev)
        except Exception as e:
            log_line("bulk click: %s" % e)

    def _bulk_done(self, n, all_at_once=False):
        self._upload_queue = []
        self._update_upload_marker()
        if all_at_once:
            show_toast(self, "📤  This upload takes several files — sent all %d at once"
                       % n, 2600)
        else:
            show_toast(self, "📤  Bulk upload finished — %d file%s sent"
                       % (n, "" if n == 1 else "s"), 2600)

    def _bulk_stop(self):
        n = len(getattr(self, "_upload_queue", []) or [])
        self._upload_queue = []
        self._update_upload_marker()
        show_toast(self, "📤  Bulk upload stopped (%d not sent)" % n)

    def _bulk_skip(self):
        q = getattr(self, "_upload_queue", None)
        if not q:
            return
        skipped = q.pop(0)
        self._update_upload_marker()
        show_toast(self, "Skipped %s" % os.path.basename(skipped))
        if not q:
            self._bulk_done(self._bulk_sent)

    def _update_upload_marker(self):
        btn = getattr(self, "btn_upload", None)
        if btn is None:
            return
        q = getattr(self, "_upload_queue", None) or []
        total = getattr(self, "_bulk_total", 0)
        sent = getattr(self, "_bulk_sent", 0)
        btn.setVisible(bool(q))
        if q:
            btn.setText("📤 %d/%d" % (sent, total))
            btn.setToolTip(
                "Bulk upload on %s: %d of %d sent, %d waiting.\nNext: %s\n"
                "Click to stop, skip or see the list."
                % (getattr(self, "_bulk_host", "") or "this site", sent, total,
                   len(q), os.path.basename(q[0])))

    def _upload_marker_menu(self):
        q = getattr(self, "_upload_queue", None) or []
        m = QMenu(self)
        m.setStyleSheet(self._menu_style())
        a = m.addAction("📤  %d of %d sent — %d waiting"
                        % (getattr(self, "_bulk_sent", 0),
                           getattr(self, "_bulk_total", 0), len(q)))
        a.setEnabled(False)
        m.addSeparator()
        for f in q[:12]:
            m.addAction("   %s" % os.path.basename(f)[:50]).setEnabled(False)
        if len(q) > 12:
            m.addAction("   ...and %d more" % (len(q) - 12)).setEnabled(False)
        m.addSeparator()
        m.addAction("▶  Send the next one now", self._bulk_advance)
        m.addAction("⏭  Skip “%s”" % (os.path.basename(q[0])[:30] if q else ""),
                    self._bulk_skip)
        m.addSeparator()
        a_auto = m.addAction("🤖  Try to press “add image” by itself")
        a_auto.setCheckable(True)
        a_auto.setChecked(bool(self.settings.get("bulk_autoadvance", True)))
        a_auto.triggered.connect(self._toggle_bulk_autoadvance)
        m.addAction("⏱  Wait between files: %d ms (change...)"
                    % int(self.settings.get("bulk_advance_delay", 2500) or 2500),
                    self._set_bulk_delay)
        m.addSeparator()
        m.addAction("🛑  Stop this bulk upload", self._bulk_stop)
        m.exec(QCursor.pos())

    def _toggle_bulk_autoadvance(self, on):
        self.settings["bulk_autoadvance"] = bool(on)
        save_json(SETTINGS_FILE, self.settings)
        show_toast(self, "Auto-press “add image”: %s" % ("ON" if on else "OFF"))

    def _set_bulk_delay(self):
        cur = int(self.settings.get("bulk_advance_delay", 2500) or 2500)
        val, ok = QInputDialog.getInt(
            self, "Bulk upload",
            "How long to let each upload finish before sending the next\n"
            "(milliseconds). Raise it if pictures arrive half-uploaded.",
            cur, 200, 60000, 250)
        if ok:
            self.settings["bulk_advance_delay"] = int(val)
            save_json(SETTINGS_FILE, self.settings)
            show_toast(self, "Wait between files: %d ms" % val)

    # ---------------------------------------- popup guard + junk (DEL 21I) ----
    def _view_for_page(self, page):
        """The tab widget showing `page`, or None (a page can outlive its tab)."""
        for i in range(self.tabs.count()):
            v = self.tabs.widget(i)
            try:
                if v is not None and v.page() is page:
                    return v
            except Exception:
                pass
        return None

    @staticmethod
    def _host_matches(host, pattern):
        """Host-or-subdomain match: 'ads.togglevpn.org' matches 'togglevpn.org'."""
        h = (host or "").lower().strip().replace("www.", "")
        d = (pattern or "").lower().strip().replace("www.", "").lstrip(".")
        return bool(d) and (h == d or h.endswith("." + d))

    # ---- Junk domains ----
    def _is_junk_host(self, host):
        if not self.settings.get("junk_autoclose", True):
            return False
        return any(self._host_matches(host, d)
                   for d in (self.settings.get("junk_domains") or []))

    def _junk_blocked(self, page, url):
        """A junk site was refused. If the tab exists only because of it, close
        the tab too - that is the "autostangs omedelbart" the list is for. A tab
        that already had a real page keeps it; only the navigation is refused."""
        view = self._view_for_page(page)
        host = clean_host(QUrl(url).host()) or url
        if view is None:
            return
        cur = view.url().toString()
        fresh = (not cur) or cur.startswith("about:") or is_blank_page(cur)
        if fresh and self.tabs.count() > 1:
            QTimer.singleShot(0, lambda v=view: self._close_view(v))
            show_toast(self, "🚫  Junk site closed: %s" % host, 1600)
        else:
            show_toast(self, "🚫  Blocked junk site: %s" % host, 1600)

    def _close_view(self, view):
        try:
            i = self.tabs.indexOf(view)
            if i >= 0:
                self.close_tab(i)
        except Exception as e:
            log_line("close junk tab: %s" % e)

    def _sync_junk_block(self):
        """Hand the junk list to the network interceptor as well.

        The list has always stopped a blocked site from LOADING AS A PAGE
        (WebPage.acceptNavigationRequest). That left the other way in open: the
        same site riding along INSIDE a page you do want - an iframe, a script,
        a beacon - which is how a "blocked" pop-up farm still gets to run code
        at you. Handing the list to the interceptor closes that too. Called at
        start-up, on every change to the list, and from _apply_privacy()."""
        try:
            if self.settings.get("junk_autoclose", True):
                self.adblock.junk_domains = set(
                    d for d in (clean_host(x)
                                for x in (self.settings.get("junk_domains") or []))
                    if d)
            else:
                self.adblock.junk_domains = set()
        except Exception as e:
            log_line("junk sync: %s" % e)

    def _junk_add(self, host):
        host = (host or "").lower().strip().replace("www.", "")
        if not host:
            return False
        lst = self.settings.setdefault("junk_domains", [])
        if any(self._host_matches(host, d) for d in lst):
            show_toast(self, "Already on the junk list")
            return False
        lst.append(host)
        save_json(SETTINGS_FILE, self.settings)
        self._sync_junk_block()
        show_toast(self, "🚫  %s added to the junk list" % host, 2200)
        return True

    def _views_for_host(self, host):
        """Every tab in this window currently showing `host` (sub-domains too)."""
        out = []
        for i in range(self.tabs.count()):
            v = self.tabs.widget(i)
            try:
                if v is not None and self._host_matches(v.url().host(), host):
                    out.append(v)
            except Exception:
                pass
        return out

    def block_site(self, host, why=""):
        """BLOCK a whole site for good - one right-click, one question.

        The front door to the junk list, which could always do this but sat
        three sub-menus deep under "Troubleshoot this page", where nobody
        reaching for it in anger was ever going to find it. What it is FOR: a
        site that forces pages on you - a tab you never asked for, a pop-up
        window, a redirect on to somewhere else. Once a site is on the list it
        may not open here again by ANY route: not as a page, not as a forced
        new tab, not as a clicked link, and (see _sync_junk_block) not as an
        iframe or a script inside a page you do want. Sub-domains count.

        Asked before it happens, because it is permanent and per-site - and the
        question names the way back out, since a site you blocked and forgot is
        indistinguishable from a site that is broken, three weeks later."""
        host = clean_host(host)
        if not host:
            show_toast(self, "No site to block here")
            return
        if any(self._host_matches(host, d)
               for d in (self.settings.get("junk_domains") or [])):
            show_toast(self, "⛔  %s is already blocked" % host, 2000)
            return
        # The QUESTION is deferred by one event-loop tick, for the same reason
        # open_page_menu_layout() does it: a modal dialog opened straight out of
        # a menu that was exec()'d over the web view can have its show/activate
        # swallowed by the native surface on Windows - and a question you cannot
        # see is a browser that has locked up.
        QTimer.singleShot(0, lambda h=host, w=why: self._block_site_ask(h, w))

    def _block_site_ask(self, host, why=""):
        """The question, and the blocking itself. Always reached through
        block_site(), never called straight from a menu - see the note there."""
        # ---- The question (rev95): WHICH part of the address, and whether the
        #      suggestions should forget it too. Asked for after hiding
        #      adress.hk-r.se, allaproffs.hk-r.se and hittat.hk-r.se one at a
        #      time: the sub-domain is the only thing a link shows you, but the
        #      thing you mean is usually the domain it hangs off. So the box
        #      offers every level down to the registered domain, with the
        #      address you right-clicked as the (safe, narrowest) default.
        scopes = domain_scopes(host) or [host]
        # Every line is broken HERE rather than left to the dialog. That is
        # rev81's lesson: a QLabel with no word-wrap asks the layout for the
        # width of its longest line and gets it, which is how the About box
        # once opened wider than the monitor. Short lines cannot do that.
        box = QDialog(self)
        box.setWindowTitle("%s - Block a site" % APP_NAME)
        try:
            box.setStyleSheet(dialog_qss())
            apply_window_icon(box)
        except Exception:
            pass
        lay = QVBoxLayout(box)
        head = QLabel("Block this for good?")
        try:
            f = head.font()
            f.setBold(True)
            head.setFont(f)
        except Exception:
            pass
        lay.addWidget(head)
        cb = QComboBox()
        if len(scopes) > 1:
            lay.addWidget(QLabel("Block which part of the address?"))
            for i, sc in enumerate(scopes):
                if i == 0:
                    cb.addItem("only  %s" % sc, sc)
                elif i == len(scopes) - 1:
                    cb.addItem("the whole domain  %s  (every sub-address)" % sc, sc)
                else:
                    cb.addItem("everything under  %s" % sc, sc)
            lay.addWidget(cb)
        else:
            cb.addItem(scopes[0], scopes[0])
        body = QLabel("")
        body.setWordWrap(True)
        lay.addWidget(body)

        def _describe(_i=0):
            sc = cb.currentData() or host
            n = len(self._views_for_host(sc))
            t = ("Nothing from  %s  may open in %s again:\n"
                 "no tab, no forced pop-up window, no clicked link,\n"
                 "and nothing of its own inside a page you DO want.\n"
                 "\n"
                 "Sub-domains count too, so ads.%s is blocked as well."
                 % (sc, APP_NAME, sc))
            if n:
                t += ("\n\n%d open tab%s on this site %s closed now."
                      % (n, "" if n == 1 else "s", "is" if n == 1 else "are"))
            body.setText(t)
        cb.currentIndexChanged.connect(_describe)
        _describe()
        also_hist = QCheckBox("Also keep it out of history && suggestions")
        also_hist.setToolTip(
            "Nothing from it is written to history or offered in the address "
            "boxes, and what is already stored is removed now.")
        also_hist.setChecked(False)
        lay.addWidget(also_hist)
        way_out = QLabel("You can let it back in whenever you like:\n"
                         "right-click a page  →  🔧 Troubleshoot this page\n"
                         "      →  🚫 Popups & junk sites\n"
                         "      →  🗂 Junk sites and popup rules…")
        lay.addWidget(way_out)
        row = QHBoxLayout()
        row.addStretch(1)
        # Own button texts on purpose: Qt's own Yes/No follow WINDOWS' language,
        # so a standard box answers a question asked in English with Ja/Nej.
        b_yes = QPushButton("⛔  Block it")
        b_no = QPushButton("Cancel")
        b_no.setDefault(True)
        b_yes.clicked.connect(box.accept)
        b_no.clicked.connect(box.reject)
        row.addWidget(b_yes)
        row.addWidget(b_no)
        lay.addLayout(row)
        fit_to_screen(box)                 # belt and braces, see rev81
        if box.exec() != QDialog.DialogCode.Accepted:
            return False
        host = cb.currentData() or host     # the part of the address chosen
        forget = also_hist.isChecked()
        # The master switch. With it off the whole list is ignored, so blocking
        # would report success and change nothing - the one failure mode this
        # feature must not have. Turn it back on, and SAY that it did.
        switched_on = not self.settings.get("junk_autoclose", True)
        if switched_on:
            self.settings["junk_autoclose"] = True
        jl = self.settings.setdefault("junk_domains", [])
        _chg, swallowed = absorb_domain(jl, host)     # whole domain folds in its parts
        save_json(SETTINGS_FILE, self.settings)
        self._sync_junk_block()
        log_line("blocked site: %s%s%s" % (host, (" [%s]" % why) if why else "",
                 ("  (folded in %d narrower)" % swallowed) if swallowed else ""))
        if forget:
            self._set_history_excluded(host, True)
        views = self._views_for_host(host)
        if views:
            QTimer.singleShot(0, lambda vs=list(views):
                              [self._close_view(v) for v in vs])
        show_toast(self, "⛔  %s is blocked - it cannot open here any more%s%s%s"
                   % (host,
                      "   ·  %d narrower line%s folded in"
                      % (swallowed, "" if swallowed == 1 else "s")
                      if swallowed else "",
                      "   ·  out of history and suggestions too" if forget else "",
                      "   (the junk list was switched back on)"
                      if switched_on else ""), 3200)
        self._update_popup_marker()
        return True

    def _junk_add_current(self):
        """Right-click while standing ON the junk page: block it and close it."""
        v = self.current_view()
        if not v:
            return
        self.block_site(clean_host(v.url().host()), why="troubleshoot menu")

    # ---- Popup policy (per opener site) ----
    def _popup_policy(self, host):
        """'allow' or 'block' for this site: per-site setting wins, else default."""
        h = (host or "").lower().replace("www.", "")
        pol = self.settings.get("popup_policy") or {}
        for d, v in pol.items():
            if self._host_matches(h, d):
                return v
        return self.settings.get("popup_default", "allow")

    def _popups_allowed_for_page(self, page):
        try:
            return self._popup_policy(page.url().host()) != "block"
        except Exception:
            return True

    def _set_popup_policy(self, host, policy):
        host = (host or "").lower().strip().replace("www.", "")
        if not host:
            return
        pol = self.settings.setdefault("popup_policy", {})
        if policy is None:
            pol.pop(host, None)
        else:
            pol[host] = policy
        save_json(SETTINGS_FILE, self.settings)
        show_toast(self, "Popups from %s: %s"
                   % (host, {"block": "BLOCKED", "allow": "allowed"}.get(policy, "default")))
        self._update_popup_marker()

    def _toggle_popups_here(self):
        v = self.current_view()
        if not v:
            return
        host = clean_host(v.url().host())
        if not host:
            return
        now = self._popup_policy(host)
        self._set_popup_policy(host, "allow" if now == "block" else "block")

    # ---- The 🚫 marker: a blocked popup must never be silent ----
    def _record_blocked_popup(self, view, url):
        if view is None:
            view = self.current_view()
        if view is None:
            return
        lst = getattr(view, "_blocked_popups", None)
        if lst is None:
            lst = view._blocked_popups = []
        if url and url not in lst:
            lst.append(url)
            del lst[:-20]                      # keep the last 20
        log_line("popup blocked: %s" % url)
        self._update_popup_marker()

    def _update_popup_marker(self):
        """Show the 🚫 button only when THIS tab had a popup blocked."""
        btn = getattr(self, "btn_popup", None)
        if btn is None:
            return
        v = self.current_view()
        n = len(getattr(v, "_blocked_popups", []) or []) if v else 0
        host = clean_host(v.url().host()) if v else ""
        blocked_site = bool(host) and self._popup_policy(host) == "block"
        btn.setVisible(n > 0 or blocked_site)
        btn.setText("🚫 %d" % n if n else "🚫")
        btn.setToolTip(
            "Popups from %s are BLOCKED.\n%s\nClick for the list, to allow this "
            "site, or to junk the address it wanted."
            % (host or "this site",
               "%d blocked in this tab." % n if n else "Nothing blocked yet."))

    def _popup_marker_menu(self):
        v = self.current_view()
        host = clean_host(v.url().host()) if v else ""
        blocked = getattr(v, "_blocked_popups", []) if v else []
        m = QMenu(self)
        m.setStyleSheet(self._menu_style())
        a = m.addAction("🚫  Popups blocked on %s" % (host or "this site"))
        a.setEnabled(False)
        m.addSeparator()
        if blocked:
            m.addAction("These wanted to open:").setEnabled(False)
            for u in blocked[-10:][::-1]:
                sub = m.addMenu("   %s" % u[:70])
                sub.setStyleSheet(self._menu_style(1))
                sub.addAction("↗  Open it anyway (this once)",
                              lambda _=False, uu=u: self.add_tab(uu, switch=True))
                jh = clean_host(QUrl(u).host())
                if jh:
                    sub.addAction("🚫  Never again: junk %s" % jh,
                                  lambda _=False, hh=jh: self._junk_add(hh))
                sub.addAction("📋  Copy address",
                              lambda _=False, uu=u: QApplication.clipboard().setText(uu))
            m.addAction("🧹  Clear this list",
                        lambda: (setattr(v, "_blocked_popups", []),
                                 self._update_popup_marker()))
            m.addSeparator()
        cur = self._popup_policy(host)
        a_allow = m.addAction("✅  Allow popups on %s  (page seems broken without them?)"
                              % (host or "this site"))
        a_allow.setCheckable(True)
        a_allow.setChecked(cur != "block")
        a_allow.triggered.connect(lambda: self._set_popup_policy(host, "allow"))
        a_block = m.addAction("🚫  Block popups on %s" % (host or "this site"))
        a_block.setCheckable(True)
        a_block.setChecked(cur == "block")
        a_block.triggered.connect(lambda: self._set_popup_policy(host, "block"))
        m.addSeparator()
        m.addAction("🗂  Junk sites and popup rules...", self.show_junk_manager)
        m.exec(QCursor.pos())

    def show_junk_manager(self):
        """One window for both lists: sites closed on sight, and sites that may
        not open new tabs."""
        dlg = QDialog(self)
        dlg.setWindowTitle(APP_NAME + " - 🚫 Junk sites & popup rules")
        dlg.setModal(False)
        dlg.setStyleSheet(dialog_qss())
        apply_window_icon(dlg)
        geo = self.settings.get("junk_dlg_size") or [700, 520]
        try:
            dlg.resize(int(geo[0]), int(geo[1]))
        except Exception:
            dlg.resize(700, 520)
        lay = QVBoxLayout(dlg)

        # ---- junk domains ----
        lay.addWidget(QLabel(
            "<b style='color:%s;'>🚫 Junk sites</b> &nbsp; refused everywhere, and the "
            "tab closes itself if it was opened just for them. Subdomains count "
            "(<i>togglevpn.org</i> also blocks <i>ads.togglevpn.org</i>)." % C_ACCENT))
        jl = QListWidget()
        lay.addWidget(jl, 1)

        def fill_junk():
            jl.clear()
            for d in (self.settings.get("junk_domains") or []):
                jl.addItem(QListWidgetItem("🚫   %s" % d))
            if not (self.settings.get("junk_domains") or []):
                it = QListWidgetItem(
                    "(empty — right-click the page you want rid of → "
                    "⛔ BLOCK this site)")
                it.setFlags(Qt.ItemFlag.NoItemFlags)
                jl.addItem(it)

        jrow = QHBoxLayout()
        je = QLineEdit()
        je.setPlaceholderText("add a domain, e.g.  togglevpn.org   (Enter)")
        jrow.addWidget(je, 1)

        def add_junk():
            if self._junk_add(je.text()):
                je.clear()
                fill_junk()
        b_ja = QPushButton("➕  Add")                       # normal colour
        b_ja.clicked.connect(add_junk)
        je.returnPressed.connect(add_junk)                  # ENTER works too
        jrow.addWidget(b_ja)

        def del_junk():
            it = jl.currentItem()
            if not it or not (it.flags() & Qt.ItemFlag.ItemIsEnabled):
                return
            d = it.text().replace("🚫", "").strip()
            self.settings["junk_domains"] = [
                x for x in (self.settings.get("junk_domains") or []) if x != d]
            save_json(SETTINGS_FILE, self.settings)
            self._sync_junk_block()
            fill_junk()
            show_toast(self, "Removed: %s" % d)
        b_jd = QPushButton("🗑  Remove")
        b_jd.setStyleSheet("QPushButton{background:#8a3030;color:#ffffff;border:none;"
                           "padding:6px 14px;border-radius:6px;}"
                           "QPushButton:hover{background:#a03a3a;}")   # red
        b_jd.clicked.connect(del_junk)
        jrow.addWidget(b_jd)
        lay.addLayout(jrow)

        # ---- popup policy ----
        lay.addWidget(QLabel(
            "<br><b style='color:%s;'>⛔ Sites that may not open new tabs</b> &nbsp; set "
            "this on the site you are READING (e.g. <i>subdl.com</i>), so the junk "
            "tab is never created whatever address it would have used. The 🚫 button "
            "in the toolbar then shows what was stopped." % C_ACCENT))
        pl = QListWidget()
        lay.addWidget(pl, 1)

        def fill_pol():
            pl.clear()
            pol = self.settings.get("popup_policy") or {}
            for h, v in pol.items():
                pl.addItem(QListWidgetItem(
                    "%s   %s" % ("⛔" if v == "block" else "✅", h)))
            if not pol:
                it = QListWidgetItem("(empty — every site may open new tabs)")
                it.setFlags(Qt.ItemFlag.NoItemFlags)
                pl.addItem(it)

        prow = QHBoxLayout()
        pe = QLineEdit()
        pe.setPlaceholderText("block popups from this site, e.g.  subdl.com   (Enter)")
        prow.addWidget(pe, 1)

        def add_pol():
            h = (pe.text() or "").strip()
            if h:
                self._set_popup_policy(h, "block")
                pe.clear()
                fill_pol()
        b_pa = QPushButton("⛔  Block")                     # normal colour
        b_pa.clicked.connect(add_pol)
        pe.returnPressed.connect(add_pol)
        prow.addWidget(b_pa)

        def del_pol():
            it = pl.currentItem()
            if not it or not (it.flags() & Qt.ItemFlag.ItemIsEnabled):
                return
            h = it.text().replace("⛔", "").replace("✅", "").strip()
            self._set_popup_policy(h, None)
            fill_pol()
        b_pd = QPushButton("🗑  Remove rule")
        b_pd.clicked.connect(del_pol)
        prow.addWidget(b_pd)
        lay.addLayout(prow)

        brow = QHBoxLayout()
        brow.addStretch(1)
        b_close = QPushButton("Close")                      # normal colour
        b_close.clicked.connect(dlg.close)
        brow.addWidget(b_close)
        lay.addLayout(brow)

        fill_junk()
        fill_pol()

        def _closed(ev):
            self.settings["junk_dlg_size"] = [dlg.width(), dlg.height()]
            save_json(SETTINGS_FILE, self.settings)
            ev.accept()
        dlg.closeEvent = _closed
        QShortcut(QKeySequence("Escape"), dlg, activated=dlg.close)
        dlg.show()
        dlg.raise_()
        dlg.activateWindow()
        je.setFocus()

    def _toggle_fav_bar_button(self, on):
        self.settings["show_fav_bar_button"] = bool(on)
        save_json(SETTINGS_FILE, self.settings)
        self.build_bookmarks_bar()
        show_toast(self, "Favourites button: %s" % ("ON" if on else "OFF"))

    def show_favourites_manager(self):
        """One window listing EVERY favourite, grouped by the login it opens
        with. Non-modal, so you can keep opening links from it while you browse."""
        dlg = getattr(self, "_fav_dlg", None)
        if dlg is not None:
            try:
                dlg.close()
            except Exception:
                pass
        dlg = QDialog(self)
        self._fav_dlg = dlg
        dlg.setWindowTitle(APP_NAME + " - ⭐ Favourites")
        dlg.setModal(False)
        dlg.setStyleSheet(dialog_qss())
        apply_window_icon(dlg)
        # Remember the window size between sessions, like every other window here.
        geo = self.settings.get("fav_dlg_size") or [760, 520]
        try:
            dlg.resize(int(geo[0]), int(geo[1]))
        except Exception:
            dlg.resize(760, 520)

        lay = QVBoxLayout(dlg)
        lay.addWidget(QLabel(
            "<b style='color:%s;'>⭐ Favourites</b> &nbsp; one global list — every "
            "profile sees all of it. Each link remembers <i>which login</i> it "
            "opens with, so two accounts on the same site stay apart."
            % C_ACCENT))

        # ---- search field (fixed caret, never blinking) ----
        row = QHBoxLayout()
        row.addWidget(QLabel("Search:"))
        search = QLineEdit()
        search.setPlaceholderText("type to filter by name or address...")
        row.addWidget(search, 1)
        lay.addLayout(row)

        tree = QTreeWidget()
        tree.setColumnCount(2)
        tree.setHeaderLabels(["Name", "Address"])
        tree.setRootIsDecorated(True)
        tree.setAlternatingRowColors(False)
        tree.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection)
        lay.addWidget(tree, 1)

        count_lbl = QLabel("")
        count_lbl.setStyleSheet("color:%s;" % dim_fg())
        lay.addWidget(count_lbl)

        def selected_fav():
            it = tree.currentItem()
            if it is None:
                return None
            return it.data(0, Qt.ItemDataRole.UserRole)

        def repopulate():
            needle = (search.text() or "").strip().lower()
            tree.clear()
            groups = {}
            for f in self.favourites:
                if needle and needle not in ((f.get("title") or "") + " "
                                             + (f.get("url") or "")).lower():
                    continue
                groups.setdefault(f.get("source") or "", []).append(f)
            shown = 0
            for key, items in groups.items():
                name = (items[0].get("source_name")
                        or self._engine_label(key) or "Current login")
                gone = key and not self._engine_id_exists(key)
                head = QTreeWidgetItem(tree, ["👤  %s  (%d)%s"
                                              % (name, len(items),
                                                 "   ⚠ login no longer exists" if gone else ""),
                                              ""])
                head.setFirstColumnSpanned(True)
                head.setExpanded(True)
                for f in items:
                    child = QTreeWidgetItem(head, [(f.get("title") or f.get("url") or "?"),
                                                   f.get("url") or ""])
                    child.setData(0, Qt.ItemDataRole.UserRole, f)
                    child.setToolTip(1, f.get("url") or "")
                    shown += 1
            tree.expandAll()
            tree.resizeColumnToContents(0)
            count_lbl.setText(
                "%d favourite(s) shown of %d   ·   stored in  %s"
                % (shown, len(self.favourites), FAVOURITES_FILE))
            if not self.favourites:
                count_lbl.setText(
                    "No favourites yet. Right-click a page (or a bookmark) → "
                    "⭐ Add to Favourites.   ·   File: %s" % FAVOURITES_FILE)

        # ---- actions ----
        def do_open():
            f = selected_fav()
            if f:
                self._fav_open(f)

        def do_open_all():
            it = tree.currentItem()
            if it is None:
                return
            head = it if it.parent() is None else it.parent()
            for i in range(head.childCount()):
                ff = head.child(i).data(0, Qt.ItemDataRole.UserRole)
                if ff:
                    self._fav_open(ff)

        def do_rename():
            f = selected_fav()
            if not f:
                return
            new, ok = QInputDialog.getText(dlg, "Rename favourite", "Name:",
                                           QLineEdit.EchoMode.Normal,
                                           f.get("title") or "")
            if ok and new.strip():
                f["title"] = new.strip()[:120]
                self._save_favs()
                repopulate()
                self.build_bookmarks_bar()

        def do_copy():
            f = selected_fav()
            if f:
                QApplication.clipboard().setText(f.get("url") or "")
                show_toast(self, "Address copied")

        def do_login():
            """Re-assign which login this favourite opens with."""
            f = selected_fav()
            if not f:
                return
            choices, ids = [], []
            for p in self.settings.get("profiles", []):
                choices.append("👤  %s" % (p.get("name") or "?"))
                ids.append((p.get("id") or "", p.get("name") or ""))
            for c in self._containers():
                choices.append("🫙  %s" % (c.get("name") or "?"))
                ids.append((c.get("id") or "", c.get("name") or ""))
            choices.append("(whichever profile is active)")
            ids.append(("", ""))
            if not choices:
                return
            pick, ok = QInputDialog.getItem(dlg, "Open this favourite as",
                                            "Login:", choices, 0, False)
            if not ok:
                return
            sid, sname = ids[choices.index(pick)]
            f["source"], f["source_name"] = sid, sname[:24]
            self._save_favs()
            repopulate()
            show_toast(self, "Login changed")

        def do_remove():
            f = selected_fav()
            if not f:
                return
            if QMessageBox.question(
                    dlg, "Remove favourite",
                    "Remove “%s” from Favourites?" % (f.get("title") or f.get("url"))
                    ) != QMessageBox.StandardButton.Yes:
                return
            self.favourites = [x for x in self.favourites if x is not f]
            self._save_favs()
            repopulate()
            self.build_bookmarks_bar()

        def do_move(step):
            f = selected_fav()
            if not f:
                return
            try:
                i = next(n for n, x in enumerate(self.favourites) if x is f)
            except StopIteration:
                return
            j = i + step
            if 0 <= j < len(self.favourites):
                self.favourites[i], self.favourites[j] = self.favourites[j], self.favourites[i]
                self._save_favs()
                repopulate()
                self.build_bookmarks_bar()

        # ---- buttons (colours written out so they are easy to change) ----
        brow = QHBoxLayout()
        for text, fn, col in (
                ("🔗  Open",            do_open,     C_ACCENT),
                ("📂  Open all in group", do_open_all, C_BTN_BG),
                ("✏  Rename...",        do_rename,   C_BTN_BG),
                ("👤  Change login...", do_login,    C_BTN_BG),
                ("📋  Copy address",    do_copy,     C_BTN_BG),
                ("▲",                   lambda: do_move(-1), C_BTN_BG),
                ("▼",                   lambda: do_move(1),  C_BTN_BG),
                ("🗑  Remove",          do_remove,   "#8a3030"),   # red
        ):
            b = QPushButton(text)
            b.setStyleSheet("QPushButton{background:%s;color:%s;border:none;"
                            "padding:6px 12px;border-radius:6px;}"
                            "QPushButton:hover{background:%s;}"
                            % (col, contrast_fg(col), shade(col, 22)))
            b.clicked.connect(fn)
            brow.addWidget(b)
        brow.addStretch(1)
        b_close = QPushButton("Close")          # normal colour
        b_close.clicked.connect(dlg.close)
        brow.addWidget(b_close)
        lay.addLayout(brow)

        search.textChanged.connect(repopulate)
        search.returnPressed.connect(do_open)     # ENTER works, not just the button
        tree.itemDoubleClicked.connect(lambda *_: do_open())
        repopulate()

        # Remember the size; close on Escape.
        def _closed(ev):
            self.settings["fav_dlg_size"] = [dlg.width(), dlg.height()]
            save_json(SETTINGS_FILE, self.settings)
            ev.accept()
        dlg.closeEvent = _closed
        QShortcut(QKeySequence("Escape"), dlg, activated=dlg.close)

        dlg.show()
        dlg.raise_()
        dlg.activateWindow()
        search.setFocus()

    # ---- Single-instance URL forwarding (server side) -----------------------
    #  Only the PRIMARY instance listens. A later launch (default-browser link
    #  click) hands us the URL over the pipe instead of opening a 2nd WhyBrowse.
    def _start_ipc_server(self):
        try:
            self._ipc_server = QLocalServer(self)
            # Without this the pipe's DACL gives other processes READ only, and
            # an ELEVATED WhyBrowse (Tower's Admin flag) is then unwritable for
            # every normal program: "Access denied", the hand-off fails and the
            # caller starts a stray second browser.  UserAccessOption = this
            # account may read AND write, whichever integrity level it is at.
            try:
                self._ipc_server.setSocketOptions(
                    QLocalServer.SocketOption.UserAccessOption)
            except Exception as e:
                log_line("IPC socket options not set: %s" % e)
            # A crash can leave a stale pipe; clear it so listen() succeeds.
            QLocalServer.removeServer(ipc_pipe_name())
            if not self._ipc_server.listen(ipc_pipe_name()):
                log_line("IPC listen failed: %s" % self._ipc_server.errorString())
                # Not the owner of the pipe, so not the one to take ipc.json
                # down when we close (_remove_ipc_file looks at this).
                self._ipc_server = None
                return
            self._ipc_server.newConnection.connect(self._on_ipc_connection)
            log_line("IPC server listening on %s" % ipc_pipe_name())
            self._publish_ipc_file()
        except Exception as e:
            log_line("IPC server error: %s" % e)

    def _publish_ipc_file(self):
        """Write down WHERE we are listening, so no caller has to work it out.

        The pipe name is an md5 of this folder, and a program that wants to
        hand us a link would have to reproduce that hash byte for byte -
        including whatever capitalisation Windows happened to report the folder
        with. Writing the real name into Helpfiles/WhyBrowse/ipc.json removes
        the guesswork entirely: read the file, push the URL in, done in a
        millisecond, with no second browser started (Issu 2026-08-08)."""
        try:
            os.makedirs(DATA_DIR, exist_ok=True)
            save_json(IPC_FILE, {
                "pipe": ipc_pipe_name(),
                "pipe_path": r"\\.\pipe\%s" % ipc_pipe_name(),
                "pid": os.getpid(),
                "base_dir": BASE_DIR,
                "program": (sys.executable if getattr(sys, "frozen", False)
                            else os.path.abspath(__file__)),
                "wire_format": "utf-8 bytes: either \"url\" or "
                               "\"profile<TAB>url\" - no newline needed",
                "profile_flag": "--profile={profile}",
                "started": time.strftime("%Y-%m-%d %H:%M:%S"),
                "note": "Written by the running WhyBrowse and removed when it "
                        "closes. Any program may write a link into this pipe "
                        "instead of launching a second browser.",
            })
        except Exception as e:
            log_line("Could not write ipc.json: %s" % e)

    def _remove_ipc_file(self):
        """Once we are gone the pipe is gone with us, so take the note down -
        a stale file would only make callers wait for a dead pipe."""
        try:
            if self._ipc_server is not None and os.path.isfile(IPC_FILE):
                os.remove(IPC_FILE)
        except Exception:
            pass

    def _on_ipc_connection(self):
        try:
            conn = self._ipc_server.nextPendingConnection()
            if conn is None:
                return

            done = {"v": False}

            def _read():
                if done["v"]:
                    return
                try:
                    data = bytes(conn.readAll()).decode("utf-8", "replace").strip()
                except Exception:
                    data = ""
                if not data:
                    return                      # wait for more / for disconnect
                done["v"] = True
                try:
                    conn.disconnectFromServer()
                except Exception:
                    pass
                self._handle_forwarded_url(data)

            conn.readyRead.connect(_read)
            # If the client already sent its URL and closed, readyRead may never
            # fire again — read whatever is buffered on disconnect too.
            conn.disconnected.connect(_read)
            if conn.bytesAvailable():
                _read()
        except Exception as e:
            log_line("IPC read error: %s" % e)

    def _resolve_profile_id(self, wanted):
        """Turn "gotanetreserv" (an id OR a display name, any case) into a
        real, enabled profile id — or None if there is no such profile."""
        if not wanted:
            return None
        want = str(wanted).strip().lower()
        for p in self.settings.get("profiles", []):
            if not p.get("enabled", True):
                continue
            if str(p.get("id", "")).lower() == want:
                return p["id"]
        for p in self.settings.get("profiles", []):
            if not p.get("enabled", True):
                continue
            if str(p.get("name", "")).lower() == want:
                return p["id"]
        return None

    def _handle_forwarded_url(self, url):
        """Open a URL another launch handed us, as a new tab, then bring THIS
        already-running window to the front.

        The sender may name a PROFILE ("profile<TAB>url"), which is how
        F(re)email opens a link with the login belonging to the account the
        mail arrived at. Without one — the old format — it lands in profile 1
        exactly as before."""
        try:
            url = (url or "").strip()
            if not url:
                return
            wanted_profile = None
            if "\t" in url:
                wanted_profile, _sep, url = url.partition("\t")
                url = url.strip()
                if not url:
                    return
            # A magnet / .torrent link from another program is not a page:
            # hand it to the torrent handling and stop (DEL 49).
            if is_torrent_link(url):
                self.handle_torrent_link(url, source="from another program")
                if self.isMinimized():
                    self.showNormal()
                self.raise_()
                self.activateWindow()
                return
            enabled_ids = [p["id"] for p in self.settings.get("profiles", [])
                           if p.get("enabled", True)]
            target = self._resolve_profile_id(wanted_profile)
            if target:
                if self.active_id != target:
                    self.switch_profile(target)
            else:
                if wanted_profile:
                    log_line("Requested profile %r not found; using profile 1"
                             % wanted_profile)
                if "default" in enabled_ids and self.active_id != "default":
                    self.switch_profile("default")
            self.add_tab(url, switch=True)
            if self.isMinimized():
                self.showNormal()
            self.show()
            self.raise_()
            self.activateWindow()
            show_toast(self, "Opened a link from another app (profile 1)")
        except Exception as e:
            log_line("handle forwarded url error: %s" % e)

    def _bmbar_context_menu(self, pos):
        """Right-click the bookmarks bar (empty area)."""
        m = QMenu(self)
        m.setStyleSheet(self._menu_style())
        # DEL 55: a picked-up bookmark can be dropped at the end of the bar.
        if self._bm_move_end_item(m, self.bookmarks.setdefault("bar", [])
                                  if isinstance(self.bookmarks, dict) else None,
                                  "the bar"):
            m.addSeparator()
        m.addAction("📁➕  New folder here...", self._bm_new_folder_in_bar)
        m.addAction("🏷➕  New section here... (coloured label)", self._bm_add_section)
        m.addAction("☆  Bookmark this page to the bar", self.add_bookmark)
        m.addAction("📁  Bookmark this page in a folder...", self._bookmark_page_to_folder)
        m.addSeparator()
        m.addAction("🗂  Favourites window...   (Ctrl+Shift+B)",
                    self.show_favourites_manager)
        a_fav = m.addAction("⭐  Show the Favourites button on this bar")
        a_fav.setCheckable(True)
        a_fav.setChecked(bool(self.settings.get("show_fav_bar_button", True)))
        a_fav.triggered.connect(self._toggle_fav_bar_button)
        m.addSeparator()
        m.addAction("🎨  Bar background colour...", lambda: self._set_bmbar_color("bmbar_bg"))
        m.addAction("🅰  Bar text colour...", lambda: self._set_bmbar_color("bmbar_fg"))
        prof = self._active_profile()
        if (self.settings.get("bmbar_bg") or self.settings.get("bmbar_fg")
                or prof.get("bar_bg") or prof.get("bar_fg")):
            m.addAction("⨯  Reset bar colours to default", self._reset_bmbar_color)
        m.addSeparator()
        a_bb = m.addAction("🔖  Show bookmarks bar")
        a_bb.setCheckable(True)
        a_bb.setChecked(bool(self.settings.get("show_bookmarks_bar", True)))
        a_bb.triggered.connect(lambda v: self.toggle_bookmarks_bar(v))
        # Position: top row vs vertical panel on the right (needs a restart).
        bpos = self.settings.get("bookmarks_position", "top")
        psub = m.addMenu("↔  Position  (%s)" % ("right side" if bpos == "right" else "top"))
        psub.setStyleSheet(self._menu_style(1))
        a_t = psub.addAction(("● " if bpos != "right" else "    ") + "Top (horizontal row)")
        a_t.triggered.connect(lambda: self._set_bookmarks_position("top"))
        a_r = psub.addAction(("● " if bpos == "right" else "    ") + "Right side (vertical)")
        a_r.triggered.connect(lambda: self._set_bookmarks_position("right"))
        # Per-profile: link indent + link text colour.
        cur_ind = int(prof.get("bookmark_indent", 0) or 0)
        isub = m.addMenu("⇥  Link indent for this profile  (%d spaces)" % cur_ind)
        isub.setStyleSheet(self._menu_style(1))
        for n in (0, 5, 10, 15, 20):
            a = isub.addAction(("● " if n == cur_ind else "    ") + "%d spaces" % n)
            a.triggered.connect(lambda _=False, c=n: self._set_bookmark_indent(c))
        m.addAction("🅰  Link text colour (this profile)...", self._set_link_color)
        if prof.get("link_color"):
            m.addAction("⨯  Reset link colour", lambda: self._set_link_color(reset=True))
        m.addSeparator()
        sm = m.addMenu("↕  Sort bookmarks")
        sm.setStyleSheet(self._menu_style(1))
        sm.addAction("📁  Folders first (A–Z)", lambda: self._sort_bookmarks("folders_first"))
        sm.addAction("🔤  Alphabetical (A–Z)", lambda: self._sort_bookmarks("alpha"))
        sm.addAction("⭐  Most used first", lambda: self._sort_bookmarks("most_used"))
        m.exec(self.bmbar.mapToGlobal(pos))

    def _set_bookmark_indent(self, n):
        self._active_profile()["bookmark_indent"] = int(n)
        save_json(SETTINGS_FILE, self.settings)
        self.build_bookmarks_bar()
        show_toast(self, "Link indent (this profile): %d spaces" % n)

    def _set_link_color(self, reset=False):
        prof = self._active_profile()
        if reset:
            prof.pop("link_color", None)
        else:
            col = QColorDialog.getColor(parent=self, title="Link text colour")
            if not col.isValid():
                return
            prof["link_color"] = col.name()
        save_json(SETTINGS_FILE, self.settings)
        self.build_bookmarks_bar()
        show_toast(self, "Link colour reset" if reset else "Link colour set")

    def _bar_colors(self):
        """Resolve bookmarks-bar (background, text) colours:
        profile override > global setting > theme default."""
        prof = self._active_profile()
        bg = prof.get("bar_bg") or self.settings.get("bmbar_bg") or shade(C_BAR_BG, -34)
        fg = prof.get("bar_fg") or self.settings.get("bmbar_fg") or contrast_fg(bg)
        return bg, fg

    def _set_bmbar_color(self, key):
        """Pick a global bar colour with LIVE preview (the bar recolours while
        you move the picker, so you can test before clicking OK)."""
        old = self.settings.get(key)
        dlg = QColorDialog(self)
        dlg.setWindowTitle("Bookmarks bar colour")
        if old:
            dlg.setCurrentColor(QColor(old))

        def live(c):
            if c.isValid():
                self.settings[key] = c.name()
                self.apply_theme()
        dlg.currentColorChanged.connect(live)
        if dlg.exec():
            self.settings[key] = dlg.selectedColor().name()
        else:                                  # cancelled -> revert
            if old is None:
                self.settings.pop(key, None)
            else:
                self.settings[key] = old
        save_json(SETTINGS_FILE, self.settings)
        self.apply_theme()

    def _reset_bmbar_color(self):
        self.settings.pop("bmbar_bg", None)
        self.settings.pop("bmbar_fg", None)
        prof = self._active_profile()                # also clear this profile's override
        prof.pop("bar_bg", None)
        prof.pop("bar_fg", None)
        save_json(SETTINGS_FILE, self.settings)
        self.apply_theme()
        show_toast(self, "Bar colours reset to default")

    def _type_into_focused(self, view, text, fallback=False):
        """Insert `text` into the focused web field WITHOUT real keystrokes.

        Uses the native value setter so React/Vue-controlled inputs actually
        register the change (otherwise the site ignores it and you'd have to type
        a real space before Enter would submit - the old Blocket bug). When
        `fallback` is True and nothing editable is focused, it targets a likely
        search/text box (used by snippets, where the right-click may not have
        focused a field; NOT used for passwords)."""
        if not text:
            return
        js = ("(function(v,fb){"
              "function setVal(e,val){try{"
              "var proto=e.tagName==='TEXTAREA'?window.HTMLTextAreaElement.prototype"
              ":window.HTMLInputElement.prototype;"
              "var d=Object.getOwnPropertyDescriptor(proto,'value');"
              "if(d&&d.set){d.set.call(e,val);}else{e.value=val;}"
              "}catch(_){e.value=val;}}"
              "function ed(el){return el&&(el.isContentEditable||((el.tagName==='INPUT'"
              "||el.tagName==='TEXTAREA')&&!el.disabled&&!el.readOnly));}"
              "var e=document.activeElement;"
              "if(!ed(e)&&fb){"
              "e=document.querySelector('input[type=search]:not([disabled]),"
              "input[name=q]:not([disabled]),input[name*=quer i]:not([disabled]),"
              "input[type=text]:not([disabled]),textarea:not([disabled])');"
              "if(e){try{e.focus();}catch(_){}}}"
              "if(!ed(e))return false;"
              "if(e.isContentEditable){try{e.focus();}catch(_){}"
              "document.execCommand('insertText',false,v);return true;}"
              "var s=e.selectionStart,en=e.selectionEnd,val=e.value||'';"
              "if(s===null||s===undefined){s=en=val.length;}"
              "setVal(e,val.slice(0,s)+v+val.slice(en));"
              "try{e.selectionStart=e.selectionEnd=s+v.length;}catch(_){}"
              "e.dispatchEvent(new Event('input',{bubbles:true}));"
              "e.dispatchEvent(new Event('change',{bubbles:true}));"
              "return true;})(%s,%s);"
              % (json.dumps(text), "true" if fallback else "false"))
        view.page().runJavaScript(js)

    def _insert_profile_login(self):
        """Click the profile tag to type into the last-focused web field:
        plain = login/e-mail, Shift = saved password, Ctrl = autofill address."""
        view = self.current_view()
        if not view:
            return
        prof = self._active_profile()
        mods = QApplication.keyboardModifiers()
        host = view.url().host().replace("www.", "")
        login = self._vault_login_for(host) if self._vault_unlocked else None

        if mods & Qt.KeyboardModifier.ShiftModifier:        # password
            if not self._require_vault():
                return
            if login and login.get("pass"):
                self._type_into_focused(view, login["pass"])
            else:
                show_toast(self, "No saved password for %s" % (host or "this site"))
        elif mods & Qt.KeyboardModifier.ControlModifier:    # address
            addr = (self._vault.get("autofill", {}) if self._vault else {}).get("address", "")
            self._type_into_focused(view, addr or "")
            if not addr:
                show_toast(self, "No address saved (set it in the vault)")
        else:                                                # login / e-mail
            user = (login or {}).get("user") if login else None
            if not user:
                af = (self._vault.get("autofill", {}) if self._vault else {})
                user = af.get("email") or prof.get("login") or prof.get("name", "")
            self._type_into_focused(view, user)

    # ------------------------------------------ on-screen keyboard (anti-keylogger) ----
    def toggle_keyboard(self):
        """Show / hide the virtual keyboard. Keys are injected into the focused
        web field via JavaScript, so a keylogger that hooks the real keyboard
        never sees the username/password you click in."""
        if self._osk is None:
            self._osk = OnScreenKeyboard(self)
        if self._osk.isVisible():
            self._osk.hide()
        else:
            self._osk.layouts = self._kb_layouts     # pick up any reloaded add-ons
            self._osk.show()
            self._osk._restore_pos()
            self._osk.raise_()

    def _osk_type(self, ch):
        """Insert one character from the on-screen keyboard into the page."""
        view = self.current_view()
        if not view:
            show_toast(self, "Click into a text field first")
            return
        self._type_into_focused(view, ch)

    def _osk_backspace(self):
        view = self.current_view()
        if not view:
            return
        js = ("(function(){var e=document.activeElement;if(!e)return;"
              "if(e.isContentEditable){document.execCommand('delete');return;}"
              "if(e.tagName==='INPUT'||e.tagName==='TEXTAREA'){"
              "var s=e.selectionStart,en=e.selectionEnd,val=e.value||'';"
              "if(s===null||s===undefined){s=en=val.length;}"
              "if(s===en){if(s>0){e.value=val.slice(0,s-1)+val.slice(en);"
              "try{e.selectionStart=e.selectionEnd=s-1;}catch(_){}}}"
              "else{e.value=val.slice(0,s)+val.slice(en);"
              "try{e.selectionStart=e.selectionEnd=s;}catch(_){}}"
              "e.dispatchEvent(new Event('input',{bubbles:true}));}})();")
        view.page().runJavaScript(js)

    def _osk_clear_field(self):
        view = self.current_view()
        if not view:
            return
        js = ("(function(){var e=document.activeElement;if(!e)return;"
              "if(e.isContentEditable){e.textContent='';}"
              "else if(e.tagName==='INPUT'||e.tagName==='TEXTAREA'){e.value='';}"
              "e.dispatchEvent(new Event('input',{bubbles:true}));})();")
        view.page().runJavaScript(js)

    def _osk_enter(self):
        """Send an Enter to the focused field: submit its form if it has one."""
        view = self.current_view()
        if not view:
            return
        js = ("(function(){var e=document.activeElement;if(!e)return;"
              "['keydown','keypress','keyup'].forEach(function(t){"
              "e.dispatchEvent(new KeyboardEvent(t,{key:'Enter',code:'Enter',"
              "keyCode:13,which:13,bubbles:true}));});"
              "var f=e.form;if(f){if(f.requestSubmit){try{f.requestSubmit();}"
              "catch(_){if(f.submit)f.submit();}}else if(f.submit){f.submit();}}})();")
        view.page().runJavaScript(js)

    # ------------------------------------------ media downloader (yt-dlp) ----
    def media_queue(self):
        """The one queue of media jobs.  It belongs to the WINDOW (not to the
        download dialog), so hiding the dialog never stops a download."""
        q = getattr(self, "_media_q", None)
        if q is None:
            q = MediaQueue(self)
            self._media_q = q
        return q

    def media_active_count(self):
        q = getattr(self, "_media_q", None)
        return q.active_count() if q is not None else 0

    def open_media_downloader(self, url=None):
        """Show the video/audio downloader, prefilled with `url` (or the current
        page's address).  Non-modal and not owned by this window, so browsing
        goes on while it runs and it may sit behind the browser."""
        if url is None:
            view = self.current_view()
            url = view.url().toString() if view else ""
            if url.startswith(("about:", "data:")) or is_blank_page(url):
                url = ""
        dlg = getattr(self, "_media_dlg", None)
        if dlg is None:
            dlg = MediaDownloadDialog(self, url or "")
            self._media_dlg = dlg
        elif url:
            dlg.url.setText(url)
        dlg.show()
        dlg.setWindowState(dlg.windowState() & ~Qt.WindowState.WindowMinimized)
        dlg.raise_()
        dlg.activateWindow()

    # ------------------------------------------------- torrents (DEL 49) ----
    def torrent_engine(self, create=True):
        """The one BitTorrent engine, made on demand. Creating this object does
        NOT start a torrent session - that happens only when a torrent is
        actually added (see TorrentEngine._ensure_session)."""
        eng = getattr(self, "_torrent_engine", None)
        if eng is None and create:
            eng = TorrentEngine(self)
            eng.finished.connect(self._on_torrent_finished)
            self._torrent_engine = eng
        return eng

    def _torrent_folder(self):
        """Where torrents land: the separate torrent folder if one is set,
        otherwise this profile's normal download folder.

        A torrent folder on a drive that is not currently plugged in is NOT
        quietly replaced by something else - the folder is returned as it is
        so the failure is visible where it belongs (with a log line), because
        silently writing 40 GB to the wrong disk is worse than an error."""
        s = self.settings
        if s.get("torrent_folder_mode", "custom") == "custom":
            folder = (s.get("torrent_folder") or "").strip()
            if folder:
                if os.path.isdir(folder):
                    return folder
                drive = os.path.splitdrive(folder)[0]
                if drive and os.path.isdir(drive + os.sep):
                    return folder            # drive is there, folder isn't yet
                log_line("Torrent folder %r is not reachable - using the "
                         "download folder instead." % folder)
        prof = self._active_profile()
        d = prof.get("save_dir") or os.path.join(os.path.expanduser("~"), "Downloads")
        return d if os.path.isdir(d) else os.path.expanduser("~")

    def handle_torrent_link(self, link, source="", force_action=None,
                            as_torrent=False):
        """THE single place every magnet / .torrent link ends up, wherever it
        came from: a click on a page, the address bar, the clipboard, another
        program, or the right-click menu.

        Returns True when the link was dealt with (including "deliberately
        ignored"), so the caller knows not to try to open it as a web page -
        which is what every browser does with a magnet link today: nothing."""
        link = (link or "").strip()
        # `as_torrent` is for the case where only the SERVER knows: a download
        # whose mime type is application/x-bittorrent but whose address looks
        # like any other (…/download.php?id=123).
        if not link or (not as_torrent and not is_torrent_link(link)):
            return False
        s = self.settings
        if not s.get("torrent_enabled", True):
            return False
        mode = s.get("torrent_mode", "ask")
        if mode == "ignore" and not force_action:
            log_line("Torrent link ignored (%s): %s" % (source or "-", link[:110]))
            return True

        # The same magnet arrives more than once by design - copying it fires
        # the clipboard watch, and clicking it fires the page hook. One question
        # per link per two minutes is enough.
        key = (parse_magnet(link).get("hash") or link).lower()
        seen = getattr(self, "_torrent_seen", None)
        if seen is None:
            seen = self._torrent_seen = {}
        now = time.time()
        for k, t in list(seen.items()):
            if now - t > 120:
                seen.pop(k, None)
        if not force_action and key in seen:
            return True
        seen[key] = now

        folder = self._torrent_folder()
        action = force_action or s.get("torrent_action", "download")

        if not force_action and mode == "ask":
            if getattr(self, "_torrent_ask_open", False):
                return True                     # one pop-up at a time
            self._torrent_ask_open = True
            try:
                answer = TorrentAskDialog(self, link, source).get()
            finally:
                self._torrent_ask_open = False
            if not answer:
                seen.pop(key, None)             # said no: allow a later retry
                return True
            action = answer["action"]
            folder = answer["folder"] or folder
            changed = False
            if answer["set_folder"] and folder:
                s["torrent_folder"] = folder
                s["torrent_folder_mode"] = "custom"
                changed = True
            if answer["always"]:
                s["torrent_mode"] = "auto"
                s["torrent_action"] = action
                changed = True
            if changed:
                save_json(SETTINGS_FILE, self.settings)

        log_line("Torrent link (%s) -> %s in %s : %s"
                 % (source or "-", action, folder, link[:110]))
        self._torrent_do(action, link, folder)
        return True

    def _torrent_do(self, action, link, folder):
        """Carry out one of the three choices on one link."""
        name = torrent_link_title(link)
        if action == "client":
            # Hand it to whatever Windows has registered for magnet: links.
            try:
                open_path(link)
                show_toast(self, "Handed to your torrent program")
            except Exception as e:
                QMessageBox.warning(
                    self, "Open in torrent program",
                    "Windows could not open this link:\n\n%s\n\n"
                    "That usually means no torrent program is installed, or "
                    "none is registered for magnet: links." % e)
            return

        if action == "savelink":
            if is_magnet_link(link):
                path = self._torrent_save_magnet_file(link, folder, name)
                if path:
                    show_toast(self, "Saved: %s" % os.path.basename(path))
                    self.status.showMessage("Torrent link saved to %s" % path, 6000)
            elif is_local_torrent_file(link):
                # Already a file: put a copy where the torrent programs look.
                try:
                    os.makedirs(folder, exist_ok=True)
                    dest = os.path.join(folder, os.path.basename(link))
                    if os.path.abspath(dest) != os.path.abspath(link):
                        shutil.copy2(link, dest)
                    show_toast(self, "Copied: %s" % os.path.basename(dest))
                except Exception as e:
                    QMessageBox.warning(self, "Torrent file",
                                        "Could not copy it into %s:\n\n%s"
                                        % (folder, e))
            else:
                self._torrent_fetch_file(link, folder, then="save")
            return

        # ---- action == "download": the built-in engine --------------------
        eng = self.torrent_engine()
        if not eng.available():
            QMessageBox.information(
                self, "Torrent engine missing",
                "The built-in engine (libtorrent) is not installed, so the "
                "files cannot be fetched here.\n\nInstall it once with:\n\n"
                "    pip install libtorrent\n\n"
                "The link has been saved as a .magnet file in the torrent "
                "folder instead, so nothing is lost.")
            if is_magnet_link(link):
                self._torrent_save_magnet_file(link, folder, name)
            return
        if is_magnet_link(link):
            ok, msg = eng.add_magnet(link, folder, name)
        elif is_local_torrent_file(link):
            ok, msg = eng.add_torrent_file(link, folder, name=name)
        else:
            self._torrent_fetch_file(link, folder, then="download")
            return
        if not ok:
            QMessageBox.warning(self, "Torrent", msg)
            return
        show_toast(self, msg or ("🧲  Downloading: %s" % name[:60]))
        self.open_torrent_manager()

    def _torrent_save_magnet_file(self, link, folder, name):
        """Write '<name>.magnet' - one line, the magnet link itself.

        Every torrent program opens one, and qBittorrent / Deluge /
        Transmission can WATCH a folder for them, which is what makes this the
        no-engine-needed route: the link lands in the folder, the torrent
        program picks it up by itself."""
        try:
            os.makedirs(folder, exist_ok=True)
            base = torrent_safe_name(name, "torrent")
            path = os.path.join(folder, base + ".magnet")
            n = 2
            while os.path.exists(path):
                path = os.path.join(folder, "%s (%d).magnet" % (base, n))
                n += 1
            with open(path, "w", encoding="utf-8") as f:
                f.write(link.strip() + "\n")
            log_line("Magnet link saved: %s" % path)
            return path
        except Exception as e:
            log_line("Saving the magnet file failed: %s" % e)
            QMessageBox.warning(self, "Save torrent link",
                                "Could not write into %s:\n\n%s" % (folder, e))
            return ""

    def _torrent_fetch_file(self, url, folder, then="download"):
        """Fetch an ordinary https://…/x.torrent FILE, then either keep it or
        hand it to the engine.

        The fetch runs in a thread and the MAIN thread polls for the result -
        a .torrent is tiny, but a server that never answers must not freeze
        the window for its whole timeout."""
        box = {"done": False, "data": None, "err": ""}

        def work():
            try:
                req = urllib.request.Request(
                    url, headers={"User-Agent": self._effective_user_agent(self.engine)})
                with urllib.request.urlopen(req, timeout=20) as r:
                    box["data"] = r.read(20 * 1024 * 1024)     # sane ceiling
            except Exception as e:
                box["err"] = str(e)
            box["done"] = True

        threading.Thread(target=work, daemon=True).start()
        self.status.showMessage("Fetching the .torrent file…")
        deadline = time.time() + 30

        def check():
            if not box["done"]:
                if time.time() > deadline:
                    self.status.showMessage("The .torrent file did not arrive.", 5000)
                    return
                QTimer.singleShot(200, check)
                return
            if box["err"] or not box["data"]:
                self.status.showMessage("", 0)
                QMessageBox.warning(self, "Torrent file",
                                    "Could not fetch that .torrent file:\n\n%s"
                                    % (box["err"] or "empty answer"))
                return
            try:
                os.makedirs(folder, exist_ok=True)
                base = torrent_safe_name(torrent_link_title(url), "torrent")
                if not base.lower().endswith(".torrent"):
                    base += ".torrent"
                path = os.path.join(folder, base)
                n = 2
                while os.path.exists(path):
                    path = os.path.join(folder, "%s (%d).torrent"
                                        % (base[:-8], n))
                    n += 1
                with open(path, "wb") as f:
                    f.write(box["data"])
            except Exception as e:
                QMessageBox.warning(self, "Torrent file",
                                    "Could not save the .torrent file:\n\n%s" % e)
                return
            self.status.showMessage("Saved: %s" % path, 5000)
            if then == "download":
                eng = self.torrent_engine()
                if not eng.available():
                    show_toast(self, "Saved the .torrent file (engine not installed)")
                    return
                ok, msg = eng.add_torrent_file(path, folder)
                if not ok:
                    QMessageBox.warning(self, "Torrent", msg)
                    return
                show_toast(self, "🧲  Downloading: %s" % os.path.basename(path))
                self.open_torrent_manager()
            else:
                show_toast(self, "Saved: %s" % os.path.basename(path))

        QTimer.singleShot(200, check)

    def _on_torrent_finished(self, name, folder):
        show_toast(self, "🧲  Finished: %s" % (name or "torrent")[:60], 2500)
        self.status.showMessage("Torrent finished: %s  →  %s" % (name, folder), 8000)
        log_line("Torrent finished: %s -> %s" % (name, folder))

    def open_torrent_manager(self):
        """The Torrents window (non-modal, so browsing continues)."""
        dlg = getattr(self, "_torrent_dlg", None)
        if dlg is not None:
            try:
                if dlg.isVisible():
                    # ToDo (2026-10-27): if it was left off-screen, the menu
                    # item must bring it back, not just raise it out of sight.
                    if dlg.isMinimized():
                        dlg.showNormal()
                    fit_to_screen(dlg)
                    dlg.raise_()
                    dlg.activateWindow()
                    return
            except Exception:
                pass
        self.torrent_engine()          # exists before the window subscribes to it
        self._torrent_dlg = TorrentManagerDialog(self)
        self._torrent_dlg.show()

    # ---- the clipboard watch: "I copied a magnet link" -------------------
    def _start_torrent_clipboard_watch(self):
        try:
            QApplication.clipboard().dataChanged.connect(self._on_clipboard_torrent)
        except Exception as e:
            log_line("Clipboard watch could not start: %s" % e)

    def _on_clipboard_torrent(self):
        """Only magnet links, deliberately. An https link that happens to end
        in .torrent is copied for all sorts of reasons; a magnet link is only
        ever copied for one."""
        s = self.settings
        if not s.get("torrent_enabled", True) or not s.get("torrent_watch_clipboard", True):
            return
        try:
            text = (QApplication.clipboard().text() or "").strip()
        except Exception:
            return
        if not is_magnet_link(text):
            return
        # Deferred: the program you copied FROM still owns the clipboard while
        # this signal runs, and a modal pop-up must not open in the middle of
        # that. A quarter of a second later everything is settled.
        QTimer.singleShot(250, lambda t=text: self.handle_torrent_link(
            t, source="copied to the clipboard"))

    def _resume_torrents_on_start(self):
        """Put last session's unfinished torrents back, if that is wanted."""
        try:
            if not self.settings.get("torrent_enabled", True):
                return
            if not self.settings.get("torrent_resume_on_start", True):
                return
            pending = [x for x in TorrentEngine.saved_items() if not x.get("done")]
            if not pending:
                return
            eng = self.torrent_engine()
            if not eng.available():
                return
            n = eng.resume_unfinished()
            if n:
                show_toast(self, "🧲  Resumed %d unfinished torrent%s"
                           % (n, "" if n == 1 else "s"), 2500)
            if eng.waiting:
                # DEL 55: say so instead of silently forgetting them.
                show_toast(self, "🧲  %d torrent%s could not be resumed — see the "
                           "profile circle ▸ Restart" % (len(eng.waiting),
                                                        "" if len(eng.waiting) == 1 else "s"),
                           4500)
        except Exception as e:
            log_line("Resuming torrents failed: %s" % e)

    # ----------------------------------------------------- password vault ----
    def _vault_path(self, pid=None):
        pid = pid or self.active_id
        if pid == "default":
            return os.path.join(DATA_DIR, "vault.dat")
        return os.path.join(PROFILES_DIR, pid, "vault.dat")

    def _vault_login_for(self, host):
        host = clean_host(host)
        if not self._vault or not host:
            return None
        logins = self._vault.get("logins", {})
        # exact host or a registrable-domain suffix match (stored keys are
        # already clean hosts, but normalise them too for old/hand-edited data)
        if host in logins:
            return logins[host]
        for d, rec in logins.items():
            dc = clean_host(d)
            if host == dc or host.endswith("." + dc) or dc.endswith("." + host):
                return rec
        return None

    def _new_vault(self):
        return {"logins": {},
                "autofill": {"email": self._active_profile().get("name", ""),
                             "name": "", "address": "", "phone": ""}}

    def toggle_vault(self):
        if self._vault_unlocked:
            self.lock_vault()
        else:
            self.unlock_vault()

    def unlock_vault(self):
        path = self._vault_path()
        blob = _vault_blob_read(path)
        want_pin = self.settings.get("vault_pin_enabled", True)
        pin = None
        if blob:
            # Whether the stored file itself was encrypted with a PIN can differ
            # from the current setting (e.g. the vault was first created without
            # one). Decrypt according to the FILE, then reconcile to the SETTING
            # below so the lock button actually honours "Extra security: PIN".
            file_has_pin = vault_needs_pin(blob)
            if file_has_pin:
                pin = self._ask_pin(confirm=False)
                if pin is None:
                    return
            try:
                data = vault_decrypt(blob, pin)
            except Exception as e:
                QMessageBox.warning(self, "Vault", "Could not open the vault:\n%s" % e)
                return
            if data is None:
                QMessageBox.warning(self, "Vault", "Wrong PIN.")
                return
            self._vault = data
            # --- Reconcile the stored file with the current PIN setting ---
            if want_pin and not file_has_pin:
                # Setting wants a PIN but this vault has none yet -> set one now.
                newpin = self._ask_pin(confirm=True)
                if newpin is None:
                    # User declined: keep the setting consistent (no PIN) so the
                    # button doesn't keep nagging on every unlock.
                    self.settings["vault_pin_enabled"] = False
                    save_json(SETTINGS_FILE, self.settings)
                else:
                    pin = newpin
            elif not want_pin and file_has_pin:
                # Setting wants no PIN -> drop it (re-saved without PIN below).
                pin = None
        else:                                    # brand-new vault
            if want_pin:
                pin = self._ask_pin(confirm=True)
                if pin is None:
                    return
            self._vault = self._new_vault()
        self._vault_pin = pin
        self._vault_unlocked = True
        self._save_vault()                       # persist (creates / re-encrypts)
        self._paint_vault_button()
        show_toast(self, "Vault unlocked")
        # Unlocking should fill the page you're already on (not just future loads).
        v = self.current_view()
        if v:
            self._autofill_login(v)
        self._arm_autolock()                     # re-lock after a while, if set

    def _arm_autolock(self):
        """Start (or restart) the auto-relock countdown if the user enabled it."""
        secs = int(self.settings.get("vault_autolock", 0) or 0)
        if not hasattr(self, "_autolock_timer"):
            self._autolock_timer = QTimer(self)
            self._autolock_timer.setSingleShot(True)
            self._autolock_timer.timeout.connect(self._autolock_fire)
        self._autolock_timer.stop()
        if secs > 0 and self._vault_unlocked:
            self._autolock_timer.start(secs * 1000)

    def _autolock_fire(self):
        if self._vault_unlocked:
            self.lock_vault()
            show_toast(self, "Vault auto-locked 🔒")

    def _set_autolock(self, secs):
        self.settings["vault_autolock"] = int(secs)
        save_json(SETTINGS_FILE, self.settings)
        self._arm_autolock()                     # apply immediately if unlocked
        if secs:
            show_toast(self, "Auto-lock: %s" % self._autolock_label(secs))
        else:
            show_toast(self, "Auto-lock off")

    @staticmethod
    def _autolock_label(secs):
        if not secs:
            return "Off"
        if secs < 60:
            return "%d seconds" % secs
        return "%d minute%s" % (secs // 60, "" if secs // 60 == 1 else "s")

    def lock_vault(self):
        self._vault = None
        self._vault_pin = None
        self._vault_unlocked = False
        if hasattr(self, "_autolock_timer"):
            self._autolock_timer.stop()
        self._paint_vault_button()
        show_toast(self, "Vault locked")

    def _require_vault(self):
        if self._vault_unlocked:
            return True
        self.unlock_vault()
        return self._vault_unlocked

    def _save_vault(self):
        if not self._vault_unlocked or self._vault is None:
            return
        pin = self._vault_pin if self.settings.get("vault_pin_enabled", True) else None
        try:
            blob = vault_encrypt(self._vault, pin)
            _vault_blob_write(self._vault_path(), blob)
        except Exception as e:
            log_line("vault save failed: {}".format(e))

    def _load_vault_for_active(self):
        """Load the active profile's vault using the already-entered PIN."""
        path = self._vault_path()
        blob = _vault_blob_read(path)
        if not blob:
            self._vault = self._new_vault()
            self._vault_unlocked = True
            self._save_vault()
            return
        try:
            data = vault_decrypt(blob, self._vault_pin)
        except Exception:
            data = None
        if data is None:                         # different PIN / unreadable -> lock
            self._vault = None
            self._vault_unlocked = False
            self._vault_pin = None
        else:
            self._vault = data
            self._vault_unlocked = True

    def _toggle_vault_pin(self, value):
        self.settings["vault_pin_enabled"] = bool(value)
        save_json(SETTINGS_FILE, self.settings)
        if self._vault_unlocked:
            if value and not self._vault_pin:
                pin = self._ask_pin(confirm=True)
                if pin is None:                  # cancelled -> revert
                    self.settings["vault_pin_enabled"] = False
                    save_json(SETTINGS_FILE, self.settings)
                    return
                self._vault_pin = pin
            self._save_vault()                   # re-encrypt with/without the PIN
        show_toast(self, "Vault PIN: %s" % ("ON" if value else "OFF"))

    def _ask_pin(self, confirm):
        title = "Set a 4-digit PIN" if confirm else "Enter your vault PIN"
        pin, ok = QInputDialog.getText(self, "Vault", title + ":",
                                       echo=QLineEdit.EchoMode.Password)
        if not ok or not pin:
            return None
        pin = pin.strip()
        if confirm:
            pin2, ok2 = QInputDialog.getText(self, "Vault", "Repeat the PIN:",
                                             echo=QLineEdit.EchoMode.Password)
            if not ok2 or pin2.strip() != pin:
                QMessageBox.information(self, "Vault", "The PINs did not match.")
                return None
        return pin

    def _paint_vault_button(self):
        if not hasattr(self, "btn_vault"):
            return
        if self._vault_unlocked:
            self.btn_vault.setText("🔓")
            self.btn_vault.setToolTip("Passwords unlocked - click to lock")
            self.btn_vault.setStyleSheet(self._css_accentbtn())
        else:
            self.btn_vault.setText("🔒")
            self.btn_vault.setToolTip("Passwords: click to unlock the vault")
            self.btn_vault.setStyleSheet(self._css_navbtn())

    def _autofill_login(self, view, _tries=0):
        """Fill saved username/password on a matching HTTPS page.

        Many login pages build their form with JavaScript a moment AFTER the
        page reports "loaded", so a single shot misses them. We therefore retry
        a few times with a short delay until the password field shows up."""
        if not (self._vault_unlocked and self.settings.get("vault_autofill", True)):
            return
        url = view.url()
        if url.scheme() != "https":
            return
        rec = self._vault_login_for(clean_host(url.host()))
        if not rec or not rec.get("pass"):
            return
        # JS returns: 'filled' (we typed something), 'hasvalue' (already filled),
        # 'nofield' (no password box yet -> worth retrying), or 'err'.
        js = ("(function(u,p){try{"
              "var pw=document.querySelector('input[type=password]:not([disabled])');"
              "if(!pw)return 'nofield';var f=pw.form||document;"
              "var us=f.querySelector('input[autocomplete=username],input[type=email],"
              "input[name*=user i],input[name*=email i],input[id*=user i],input[id*=email i],"
              "input[type=text]');var did=false;"
              "if(us&&!us.value){us.value=u;us.dispatchEvent(new Event('input',{bubbles:true}));"
              "us.dispatchEvent(new Event('change',{bubbles:true}));did=true;}"
              "if(!pw.value){pw.value=p;pw.dispatchEvent(new Event('input',{bubbles:true}));"
              "pw.dispatchEvent(new Event('change',{bubbles:true}));did=true;}"
              "return did?'filled':'hasvalue';"
              "}catch(e){return 'err';}})(%s,%s);"
              % (json.dumps(rec.get("user", "")), json.dumps(rec.get("pass", ""))))

        def _cb(res, v=view, t=_tries):
            if res == "filled":
                show_toast(self, "Login filled in 🔑")
            elif res == "nofield" and t < 4:
                # No form yet - try again shortly (SPA / delayed render).
                QTimer.singleShot(700, lambda: self._autofill_login(v, t + 1))

        view.page().runJavaScript(js, _cb)

    # ---- Per-profile auto-login (one password per profile, user = its e-mail) ----
    def _set_profile_password(self, prof, password):
        """Store a profile's login password, DPAPI-encrypted to the Windows account
        (no PIN needed, auto-available next launch). Empty clears it."""
        import base64
        if password:
            try:
                prof["pw_enc"] = base64.b64encode(
                    _dpapi(password.encode("utf-8"), True)).decode("ascii")
            except Exception as e:
                log_line("profile pw encrypt error: %s" % e)
        else:
            prof.pop("pw_enc", None)

    def _profile_password(self, prof=None):
        prof = prof or self._active_profile()
        enc = prof.get("pw_enc")
        if not enc:
            return None
        try:
            import base64
            return _dpapi(base64.b64decode(enc), False).decode("utf-8")
        except Exception:
            return None

    def _autofill_profile_login(self, view, _tries=0):
        """Auto-fill (and optionally submit) THIS profile's single login on any
        HTTPS sign-in page that shows a password field. Username defaults to the
        profile's e-mail/name. Works without unlocking the vault (DPAPI-bound)."""
        prof = self._active_profile()
        if not prof.get("autologin"):
            return
        url = view.url()
        if url.scheme() != "https":
            return
        pw = self._profile_password(prof)
        if not pw:
            return
        user = prof.get("login") or prof.get("name") or ""
        submit = bool(prof.get("autologin_submit"))
        js = ("(function(u,p,submit){try{"
              "var pw=document.querySelector('input[type=password]:not([disabled])');"
              "if(!pw)return 'nofield';var f=pw.form||document;"
              "var us=f.querySelector('input[autocomplete=username],input[type=email],"
              "input[name*=user i],input[name*=email i],input[id*=user i],input[id*=email i],"
              "input[type=text]');var did=false;"
              "if(us&&!us.value){us.value=u;us.dispatchEvent(new Event('input',{bubbles:true}));"
              "us.dispatchEvent(new Event('change',{bubbles:true}));did=true;}"
              "if(!pw.value){pw.value=p;pw.dispatchEvent(new Event('input',{bubbles:true}));"
              "pw.dispatchEvent(new Event('change',{bubbles:true}));did=true;}"
              "if(did&&submit){var b=f.querySelector?f.querySelector("
              "'button[type=submit],input[type=submit],button:not([type])'):null;"
              "try{if(pw.form&&pw.form.requestSubmit){pw.form.requestSubmit();}"
              "else if(pw.form){pw.form.submit();}else if(b){b.click();}}catch(e){if(b)b.click();}}"
              "return did?'filled':'hasvalue';"
              "}catch(e){return 'err';}})(%s,%s,%s);"
              % (json.dumps(user), json.dumps(pw),
                 "true" if submit else "false"))

        def _cb(res, v=view, t=_tries):
            if res == "filled":
                show_toast(self, "Auto-login filled in 🔑")
            elif res == "nofield" and t < 4:
                QTimer.singleShot(700, lambda: self._autofill_profile_login(v, t + 1))

        view.page().runJavaScript(js, _cb)

    def save_login_from_page(self):
        """Read the current page's username/password fields and save them."""
        if not self._require_vault():
            return
        view = self.current_view()
        if not view:
            return
        host = clean_host(view.url().host())
        js = ("(function(){try{var pw=document.querySelector('input[type=password]');"
              "if(!pw||!pw.value)return null;var f=pw.form||document;"
              "var us=f.querySelector('input[autocomplete=username],input[type=email],"
              "input[name*=user i],input[name*=email i],input[id*=user i],input[id*=email i],"
              "input[type=text]');"
              "return JSON.stringify({u:us?us.value:'',p:pw.value});}catch(e){return null;}})();")
        view.page().runJavaScript(js, lambda res, h=host: self._save_login_result(h, res))

    def _save_login_result(self, host, res):
        if not res:
            show_toast(self, "No filled password field found on this page")
            return
        try:
            d = json.loads(res)
        except Exception:
            return
        if not d.get("p"):
            return
        self._vault.setdefault("logins", {})[host] = {"user": d.get("u", ""), "pass": d["p"]}
        self._save_vault()
        show_toast(self, "Login saved for %s" % host)

    # ---- Auto-save: read the login the page-script captured on form submit ----
    def _check_pending_login(self, view):
        if not (self._vault_unlocked and self.settings.get("vault_autosave", True)):
            return                                   # locked/off: leave it for later
        js = ("(function(){try{var k='__wb_pending_login';"
              "var v=sessionStorage.getItem(k);"
              "if(v)sessionStorage.removeItem(k);return v||null;}catch(e){return null;}})();")
        view.page().runJavaScript(js, self._on_pending_login)

    def _on_pending_login(self, res):
        if not res or not self._vault_unlocked:
            return
        try:
            d = json.loads(res)
        except Exception:
            return
        host = clean_host(d.get("host", ""))
        pw = d.get("p", "")
        if not host or not pw or not d.get("https"):
            return                                   # need an HTTPS host + a password
        if (time.time() * 1000 - d.get("t", 0)) > 300000:
            return                                   # stale (> 5 min) - ignore
        user = d.get("u", "")
        logins = self._vault.setdefault("logins", {})
        old = logins.get(host)
        if old and old.get("pass") == pw and old.get("user", "") == user:
            return                                   # already saved exactly this
        if old and old.get("pass") and old.get("pass") != pw:
            if QMessageBox.question(
                    self, "Update password?",
                    "The password for %s changed.\nUpdate the saved login?" % host
                    ) != QMessageBox.StandardButton.Yes:
                return
            verb = "updated"
        else:
            verb = "saved"
        logins[host] = {"user": user, "pass": pw}
        self._save_vault()
        show_toast(self, "Login %s for %s 🔑" % (verb, host))

    def show_vault_dialog(self):
        if not self._require_vault():
            return
        VaultDialog(self).exec()

    def _open_in_current(self, url):
        """Open a bookmark. If the current tab is locked (>=1), use a new tab."""
        c = self.settings.setdefault("bookmark_use_counts", {})
        c[url] = c.get(url, 0) + 1                    # track use for "most used" sort
        save_json(SETTINGS_FILE, self.settings)
        view = self.current_view()
        if view and self._lock(view) >= 1:
            self.add_tab(url, switch=True)
            return
        view = view or self.add_tab(None, navigate=False)
        view.setUrl(QUrl(url))

    # ========================================================================
    #  DEL 44 - THE TEMP TAB  (a place for things you only want to look at)
    # ------------------------------------------------------------------------
    #  One tab (or a few - see temp_tab_slots) that gets REUSED instead of
    #  breeding new tabs. It sits at the top of the strip, right under the
    #  pinned block, and is marked 🕒.
    #
    #  THE RULE THAT MAKES IT USABLE: nothing lands there on its own. Only
    #    * a bookmark whose own "open by default" is set to Temp,
    #    * the page menu's "🕒 Open link in the temp tab",
    #    * the address bar's "open this in the temp tab",
    #    * a "same tab" open that a LOCKED / pinned tab would otherwise have
    #      turned into yet another tab (temp_locked_override).
    #  Ordinary in-page links - clicking item after item on Tradera or Vinted -
    #  keep following the normal new-tab/same-tab rules, so they can never pile
    #  into the temp tab and overwrite each other. That was the whole worry.
    #
    #  A temp tab you PIN or LOCK is never recycled, so anything worth keeping
    #  can be rescued with one click instead of being written over.
    # ========================================================================

    def _temp_views(self):
        """The live temp tabs, oldest use first (dead ones pruned)."""
        order = getattr(self, "_temp_order", None)
        if order is None:
            order = self._temp_order = []
        alive = [v for v in order if self.tabs.indexOf(v) >= 0]
        self._temp_order = alive
        return alive

    def _is_temp_tab(self, view):
        return bool(getattr(view, "_is_temp", False))

    def _mark_temp(self, view, temp=True, quiet=False):
        """Make (or stop making) a tab the reusable temp tab."""
        if view is None:
            return
        view._is_temp = bool(temp)
        order = self._temp_views()
        if temp:
            if view not in order:
                order.append(view)
        elif view in order:
            order.remove(view)
        self._refresh_tab_label(view)
        if not quiet:
            show_toast(self, "Temp tab: %s" % ("ON — this tab gets reused"
                                               if temp else
                                               "OFF — this tab is kept"))

    def _temp_slot_index(self):
        """Where a NEW temp tab goes: after the pinned block, after any temp
        tabs already there, so they always sit together at the top."""
        return self._pinned_count() + len(self._temp_views())

    def open_in_temp(self, url, switch=True):
        """Open `url` in the temp tab, reusing it instead of making a new tab."""
        if not url:
            return None
        if not self.settings.get("temp_tab_enabled", True):
            return self.add_tab(url, switch=switch)
        try:
            slots = int(self.settings.get("temp_tab_slots", 1) or 1)
        except Exception:
            slots = 1
        slots = max(1, min(9, slots))
        views = self._temp_views()
        # A temp tab you pinned or locked is being kept ON PURPOSE - never
        # write over it; make a fresh temp tab instead.
        reusable = [v for v in views
                    if not getattr(v, "_pinned", False) and self._lock(v) < 1]
        if len(views) < slots or not reusable:
            v = self.add_tab(url, switch=switch, at_index=self._temp_slot_index())
            self._mark_temp(v, True, quiet=True)
            return v
        v = reusable[0]                       # least recently used
        self._temp_order.remove(v)
        self._temp_order.append(v)
        if getattr(v, "_asleep", False):
            self._wake_tab(v)
        v.setUrl(QUrl(url))
        if switch:
            i = self.tabs.indexOf(v)
            if i >= 0:
                self.tabs.setCurrentIndex(i)
        self._refresh_tab_label(v)
        return v

    def open_current_in_temp(self):
        """Send the page you are on to the temp tab (☰ / address-bar menu)."""
        view = self.current_view()
        u = view.url().toString() if view else ""
        if u and u.startswith("http"):
            self.open_in_temp(u)
        else:
            show_toast(self, "Nothing to send to the temp tab")

    # ---- open modes: same / new / temp --------------------------------------
    OPEN_MODES = (("same", "↩  In the SAME tab"),
                  ("new",  "🆕  In a NEW tab"),
                  ("temp", "🕒  In the TEMP tab"))

    def _bookmark_open_default(self):
        """The global 'when I open a bookmark' choice. Falls back to the older
        bar_open_new_tab flag so nothing changes until it is set."""
        m = (self.settings.get("open_bookmark_default") or "").strip().lower()
        if m in ("same", "new", "temp"):
            return m
        return "new" if self.settings.get("bar_open_new_tab", True) else "same"

    def _set_bookmark_open_default(self, mode):
        self.settings["open_bookmark_default"] = mode
        # keep the old flag in step, so anything still reading it agrees
        self.settings["bar_open_new_tab"] = (mode != "same")
        save_json(SETTINGS_FILE, self.settings)
        show_toast(self, "Bookmarks open %s by default"
                   % {"same": "in the same tab", "new": "in a new tab",
                      "temp": "in the temp tab"}.get(mode, mode))

    def _bm_open_mode(self, node):
        """How THIS bookmark opens: its own setting, else the global default."""
        m = (node.get("open_mode") or "").strip().lower()
        if m in ("same", "new", "temp"):
            return m
        if node.get("same_tab"):          # the older per-item flag
            return "same"
        return self._bookmark_open_default()

    def _bm_set_open_mode(self, node, mode):
        """Set (or clear, with mode='') this bookmark's own open mode."""
        node.pop("same_tab", None)        # superseded by open_mode
        if mode in ("same", "new", "temp"):
            node["open_mode"] = mode
        else:
            node.pop("open_mode", None)
        self._save_bm()
        self.build_bookmarks_bar()
        show_toast(self, "Opens %s" % {
            "same": "in the same tab", "new": "in a new tab",
            "temp": "in the temp tab"}.get(
                mode, "the default way (%s)" % self._bookmark_open_default()))

    def open_url_in_mode(self, url, mode):
        """The ONE place that turns 'same' / 'new' / 'temp' into a real open."""
        if not url:
            return
        if mode == "temp":
            c = self.settings.setdefault("bookmark_use_counts", {})
            c[url] = c.get(url, 0) + 1
            self.open_in_temp(url)
            return
        if mode == "same":
            view = self.current_view()
            locked = view is not None and (self._lock(view) >= 1
                                           or getattr(view, "_pinned", False))
            # A locked / pinned tab refuses to be navigated away, and the old
            # behaviour was "then open yet another tab". The temp tab is a
            # better answer: you asked for ONE tab, so you get the ONE spare.
            if (locked and self.settings.get("temp_locked_override", True)
                    and self.settings.get("temp_tab_enabled", True)):
                c = self.settings.setdefault("bookmark_use_counts", {})
                c[url] = c.get(url, 0) + 1
                self.open_in_temp(url)
                return
            self._open_in_current(url)
            return
        self.add_tab(url, switch=True)

    # ---- right-click in the address bar -------------------------------------
    def _address_context_menu(self, pos):
        """Qt's own edit menu (cut/copy/paste/select all) PLUS the choice of
        what an opened bookmark should do by default, which is what the user
        goes looking for when a link lands in the wrong place."""
        m = self.address.createStandardContextMenu()
        m.setStyleSheet(self._menu_style())
        m.addSeparator()
        cur = self._bookmark_open_default()
        sub = m.addMenu("🔖  Bookmarks open, by default…")
        sub.setStyleSheet(self._menu_style(1))
        for mode, label in self.OPEN_MODES:
            a = sub.addAction(("●  " if mode == cur else "     ") + label)
            a.triggered.connect(
                lambda _=False, md=mode: self._set_bookmark_open_default(md))
        sub.addSeparator()
        hint = sub.addAction("(a single bookmark can override this — "
                             "right-click it on the bar)")
        hint.setEnabled(False)
        typed = (self.address.text() or "").strip()
        if typed:
            m.addAction("🕒  Open what's typed here in the TEMP tab",
                        lambda t=typed: self.open_in_temp(
                            normalize_url(t, self.settings.get(
                                "search_engine", SEARCH_URL)).toString()))
        m.addAction("🕒  Send THIS page to the temp tab", self.open_current_in_temp)
        m.addSeparator()
        m.addMenu(self._build_address_keywords_menu())
        m.addMenu(self._build_suggestions_menu())
        m.exec(self.address.mapToGlobal(pos))

    def _node_uses(self, n, counts):
        if "folder" in n:
            return sum(self._node_uses(c, counts) for c in n.get("folder", []))
        return counts.get(n.get("url", ""), 0)

    def _sort_nodes(self, nodes, mode, counts):
        def alpha(n):
            return (n.get("title") or n.get("url", "")).lower()
        if mode == "alpha":
            nodes.sort(key=alpha)
        elif mode == "folders_first":
            nodes.sort(key=lambda n: (0 if "folder" in n else 1, alpha(n)))
        elif mode == "most_used":
            nodes.sort(key=lambda n: (-self._node_uses(n, counts), alpha(n)))
        for n in nodes:
            if "folder" in n:
                self._sort_nodes(n.get("folder", []), mode, counts)

    def _sort_bookmarks(self, mode):
        counts = self.settings.get("bookmark_use_counts", {})
        self._sort_nodes(self.bookmarks.setdefault("bar", []), mode, counts)
        self._sort_nodes(self.bookmarks.setdefault("menu", []), mode, counts)
        self._save_bm()
        self.build_bookmarks_bar()
        names = {"folders_first": "folders first", "alpha": "A–Z", "most_used": "most used"}
        show_toast(self, "Bookmarks sorted: %s" % names.get(mode, mode))

    def toggle_bookmarks_bar(self, on):
        self.settings["show_bookmarks_bar"] = bool(on)
        save_json(SETTINGS_FILE, self.settings)
        self.bmbar.setVisible(bool(on))

    def refresh_all_tabs(self):
        """Reload every open tab in this window (profile)."""
        n = 0
        for i in range(self.tabs.count()):
            v = self.tabs.widget(i)
            if v:
                v.reload()
                n += 1
        show_toast(self, "Reloaded {} tab(s)".format(n))

    # ---- Print to PDF (Ctrl+P) ------------------------------------------------
    def print_page_to_pdf(self):
        """Ctrl+P — 'Print to PDF'. Ask where to save, then write the current page
        to a PDF via QtWebEngine's printToPdf byte-callback (no printer needed).
        The default folder is this profile's download folder; the default file
        name is the page title."""
        view = self.current_view()
        if not view:
            return
        try:
            prof = self._active_profile()
        except Exception:
            prof = {}
        base_dir = (prof.get("save_dir")
                    or os.path.join(os.path.expanduser("~"), "Downloads"))
        try:
            if not os.path.isdir(base_dir):
                base_dir = os.path.expanduser("~")
        except Exception:
            base_dir = os.path.expanduser("~")
        title = (view.title() or "page").strip()
        safe = re.sub(r'[\\/:*?"<>|\r\n\t]+', "_", title)[:80].strip(" .") or "page"
        default_path = os.path.join(base_dir, safe + ".pdf")
        path, _ = QFileDialog.getSaveFileName(
            self, "Print to PDF — choose where to save",
            default_path, "PDF files (*.pdf)")
        if not path:
            return
        if not path.lower().endswith(".pdf"):
            path += ".pdf"
        show_toast(self, "Creating PDF…")
        try:
            # Byte-callback form: no per-page signal bookkeeping, fires once.
            view.page().printToPdf(
                lambda data, p=path: self._save_pdf_bytes(data, p))
        except Exception as e:
            log_line("printToPdf error: {}".format(e))
            show_toast(self, "Could not print this page: %s" % e)

    def _save_pdf_bytes(self, data, path):
        """Write the QByteArray produced by printToPdf to disk + report."""
        try:
            raw = bytes(data) if data is not None else b""
            if not raw:
                show_toast(self, "This page could not be printed to PDF")
                return
            with open(path, "wb") as f:
                f.write(raw)
            show_toast(self, "Saved PDF: " + os.path.basename(path))
        except Exception as e:
            log_line("save pdf error: {}".format(e))
            show_toast(self, "PDF save failed: %s" % e)

    def _build_shortcuts(self):
        def sc(seq, fn):
            s = QShortcut(QKeySequence(seq), self)
            s.activated.connect(fn)
            return s
        sc("Ctrl+T", lambda: self.new_tab())
        sc("Ctrl+W",  lambda: self.close_tab(self.tabs.currentIndex()))
        sc("Ctrl+F4", lambda: self.close_tab(self.tabs.currentIndex()))
        sc("Ctrl+L", self.focus_address)
        sc("Ctrl+R", lambda: self._nav_do("reload"))
        sc("F5",     lambda: self._nav_do("reload"))
        sc("Alt+Left",  lambda: self._nav_do("back"))
        sc("Alt+Right", lambda: self._nav_do("forward"))
        # Ctrl+F is NOT a QShortcut: a shortcut consumes the key before the page,
        # so a site with its own find (Google Sheets/Docs) never gets it and we had
        # to re-send a synthetic key (unreliable — it typed into the active cell).
        # Instead an application event filter (see eventFilter) routes Ctrl+F: on
        # native-find sites it lets the key PASS THROUGH to Chromium; elsewhere it
        # opens our find bar.
        try:
            QApplication.instance().installEventFilter(self)
        except Exception:
            pass
        sc("Ctrl+=", lambda: self.zoom_step(+0.1))
        sc("Ctrl++", lambda: self.zoom_step(+0.1))
        sc("Ctrl+-", lambda: self.zoom_step(-0.1))
        sc("Ctrl+0", lambda: self.reset_zoom_current())
        sc("Ctrl+P", self.print_page_to_pdf)     # Print / Save the page as PDF
        sc("F11",    self.toggle_fullscreen)
        sc("Ctrl+Tab",        lambda: self._cycle_tab(+1))
        sc("Ctrl+Shift+Tab",  lambda: self._cycle_tab(-1))
        sc("Ctrl+Shift+A",    self.show_tab_search)
        sc("Ctrl+Shift+F",    self.open_feature_search)
        sc("Ctrl+Shift+B",    self.show_favourites_manager)   # ⭐ Favourites window
        sc("Ctrl+Shift+D",    self.open_bug_report)            # 🐞 Report a bug (DEL 40)
        sc("F1",              lambda: self.toggle_help_mode())  # ❓ hover help (DEL 21K)
        sc("Ctrl+Shift+S",    lambda: self._add_quicklink(self.current_view()))
        sc("Ctrl+\\",         self.toggle_split_view)
        sc("Ctrl+Shift+K",    self.toggle_keyboard)
        sc("Ctrl+M",          self.toggle_mute_current)
        sc("Ctrl+Shift+M",    lambda: self._mute_all(True))
        sc("Ctrl+Shift+T",    self.reopen_closed_tab)
        sc("Ctrl+PgDown",     lambda: self._cycle_tab(+1))
        sc("Ctrl+PgUp",       lambda: self._cycle_tab(-1))
        # F-keys switch profiles (skip F5=reload, F11=full screen)
        for i, fk in enumerate(("F1", "F2", "F3", "F4", "F6", "F7", "F8",
                                "F9", "F10", "F12")):
            sc(fk, lambda i=i: self._switch_profile_index(i))
        # NOTE: Esc is NOT a QShortcut — a shortcut would swallow it before the
        # page sees it, so on Google Sheets/Docs its OWN find box couldn't be
        # closed with Esc. It's handled in eventFilter() instead, where we can
        # let Esc fall through to those sites (see the KeyPress branch there).

    def _cycle_tab(self, step):
        n = self.tabs.count()
        if n > 1:
            self.tabs.setCurrentIndex((self.tabs.currentIndex() + step) % n)

    # ----------------------------------------------------- tab handling ----
    def new_tab(self, switch=True):
        """Open a tab according to the new-tab setting (blank page or home)."""
        if self.settings.get("new_tab_mode", "blank") == "home":
            return self.add_tab(self.settings.get("home_url", DEFAULT_HOME), switch=switch)
        return self.add_tab(None, switch=switch, navigate=True)

    def add_tab(self, url=None, switch=True, navigate=True, adjacent=None,
                container=None, at_index=None):
        # Feature: opening a tab FROM a pinned tab. The new tab should land at the
        # END (not next to the pinned one), and closing it returns you to that
        # pinned tab. We capture the opener before creating the new view.
        opener = self.current_view()
        opener_pinned = bool(opener and getattr(opener, "_pinned", False))
        if opener_pinned and adjacent is None:
            adjacent = False                   # land at the end, not by the pin

        view = BrowserView(self)
        # A CONTAINER tab runs on its own separate cookie store (its own engine),
        # so it can be logged in as a DIFFERENT account than the profile's normal
        # tabs - two Gmail accounts side by side in the same window. A normal tab
        # (container=None) uses the active profile's engine as before.
        if container:
            eng = self._get_engine(container)
        else:
            eng = self.engine
        page = WebPage(eng, self)              # active profile's / container's engine
        view.setPage(page)
        view._pid = self.active_id             # which profile this tab belongs to
                                               # (used for cross-profile message notifications)
        view._container = container or None    # None = normal tab; else container id
        if opener_pinned:
            view._opener = opener              # close -> return to this pinned tab

        # ---- Enable modern features ----
        s = view.settings()
        s.setAttribute(QWebEngineSettings.WebAttribute.FullScreenSupportEnabled, True)
        s.setAttribute(QWebEngineSettings.WebAttribute.JavascriptCanOpenWindows, True)
        s.setAttribute(QWebEngineSettings.WebAttribute.PluginsEnabled, True)
        s.setAttribute(QWebEngineSettings.WebAttribute.ScrollAnimatorEnabled, True)
        s.setAttribute(QWebEngineSettings.WebAttribute.PdfViewerEnabled, True)
        # Let pages read/write the clipboard via JS (needed by e.g. Google
        # Sheets' rich copy/paste - see the permission auto-grant in WebPage).
        s.setAttribute(QWebEngineSettings.WebAttribute.JavascriptCanAccessClipboard, True)
        s.setAttribute(QWebEngineSettings.WebAttribute.JavascriptCanPaste, True)

        # ---- Low-vision accessibility: bigger zoom + minimum font size ----
        if self.settings.get("low_vision"):
            try:
                s.setFontSize(QWebEngineSettings.FontSize.MinimumFontSize,
                              int(self._lv_minfont))
            except Exception:
                pass
            view.setZoomFactor(float(self._lv_zoom))
        else:
            view.setZoomFactor(float(self.settings.get("zoom", 1.0)))

        # ---- Signals ----
        view.urlChanged.connect(lambda u, v=view: self.on_url_changed(v, u))
        view.loadStarted.connect(lambda v=view: self.on_load_started(v))
        # Bound to ITS view, like every other signal here. It used to be
        # connected bare, so any background tab wrote its progress into the
        # one shared status bar - and on_load_finished only clears that bar
        # for the tab you are looking AT, so the number just sat there.
        view.loadProgress.connect(lambda p, v=view: self.on_load_progress(v, p))
        view.loadFinished.connect(lambda ok, v=view: self.on_load_finished(v, ok))
        view.titleChanged.connect(lambda t, v=view: self.on_title_changed(v, t))
        view.iconChanged.connect(lambda ic, v=view: self.on_icon_changed(v, ic))
        page.fullScreenRequested.connect(self.on_fullscreen_request)
        # If a page's renderer crashes (isolated Chromium process), reload it so the
        # tab recovers with a fresh page instead of going blank / taking us down.
        try:
            page.renderProcessTerminated.connect(
                lambda status, code, v=view: self._on_render_terminated(v, status, code))
        except Exception:
            pass

        # Interactive new tabs open right AFTER the current tab (directly to its
        # right, even if pinned tabs are there); session-restore tabs keep their
        # order at the end. 'adjacent' defaults to whether we're switching to it.
        if adjacent is None:
            adjacent = switch
        if at_index is not None:
            # Explicit slot in the strip (used by the temp tabs, which live
            # together right under the pinned block - see DEL 44).
            at = max(0, min(int(at_index), self.tabs.count()))
            idx = self.tabs.insertTab(at, view, "New Tab")
            if switch:
                self.tabs.setCurrentIndex(idx)
        elif adjacent and self.tabs.count() > 0:
            # Right of the current tab, but never INSIDE the pinned block at the
            # front (a new unpinned tab must not land between two pinned tabs).
            at = max(self.tabs.currentIndex() + 1, self._pinned_count())
            idx = self.tabs.insertTab(at, view, "New Tab")
            if switch:
                self.tabs.setCurrentIndex(idx)
        else:
            idx = self.tabs.addTab(view, "New Tab")
            if switch:
                self.tabs.setCurrentIndex(idx)

        if url:
            view.setUrl(QUrl(url))
        elif navigate:
            view.setUrl(new_tab_url())          # blank start page
        # else: leave it alone (createWindow will drive the navigation)
        return view

    def close_tab(self, index):
        if index < 0:
            return
        if self.tabs.count() == 1:
            # Don't leave an empty window; reset to the blank start page instead.
            self.current_view().setUrl(new_tab_url())
            return
        w = self.tabs.widget(index)
        if getattr(w, "_pinned", False):
            return                              # don't close a pinned tab by accident
        try:                                    # remember it for Ctrl+Shift+T reopen
            cu = w.url().toString()
            if cu and cu.startswith("http") and not is_blank_page(cu):
                self._closed_tabs.append(cu)
                self._closed_tabs = self._closed_tabs[-25:]
        except Exception:
            pass
        # After removing, jump to the profile's designated home tab (if any)
        # instead of just landing on the next tab in the strip.
        home_url = self._active_profile().get("home_tab", "").strip()
        opener = getattr(w, "_opener", None)    # the pinned tab that opened this one
        self.tabs.removeTab(index)
        if w:
            self._kill_view_media(w)        # stop audio/video NOW, not on GC
            w.deleteLater()
        self._update_identity_tab_flag()
        # 1) If this tab was opened from another tab and there are still OTHER tabs
        #    opened from the same one (siblings — e.g. 5 links opened from Sellpy),
        #    go to the nearest sibling so you can work through them, instead of
        #    jumping back to the opener every time. Only when the LAST sibling is
        #    closed do we return to the opener.
        if opener is not None:
            sib = None
            for i in range(index, self.tabs.count()):       # to the right first
                v = self.tabs.widget(i)
                if v is not None and getattr(v, "_opener", None) is opener:
                    sib = i
                    break
            if sib is None:
                for i in range(min(index, self.tabs.count()) - 1, -1, -1):  # then left
                    v = self.tabs.widget(i)
                    if v is not None and getattr(v, "_opener", None) is opener:
                        sib = i
                        break
            if sib is not None:
                self.tabs.setCurrentIndex(sib)
                return
            oi = self.tabs.indexOf(opener)
            if oi >= 0:
                self.tabs.setCurrentIndex(oi)
                return
        # 2) Otherwise fall back to the profile's home tab, if any.
        if home_url:
            for i in range(self.tabs.count()):
                v = self.tabs.widget(i)
                if v and v.url().toString().rstrip("/") == home_url.rstrip("/"):
                    self.tabs.setCurrentIndex(i)
                    return

    def reopen_closed_tab(self):
        """Reopen the most recently closed tab (Ctrl+Shift+T)."""
        if self._closed_tabs:
            url = self._closed_tabs.pop()
            self.add_tab(url, switch=True)
        else:
            show_toast(self, "No recently closed tabs")

    def _on_render_terminated(self, view, status, code):
        """A page's Chromium renderer process died. Log it and reload the tab so
        it recovers gracefully (a blank/crashed page otherwise stays blank)."""
        try:
            log_line("render process terminated (status=%s exit=%s): %s"
                     % (status, code, view.url().toString()))
        except Exception:
            pass
        try:
            # Don't auto-reload a normal/clean exit; only a crash/abnormal one.
            normal = getattr(
                QWebEnginePage.RenderProcessTerminationStatus,
                "NormalTerminationStatus", None)
            if status == normal:
                return
            # DEL 56: a ladder instead of "reload forever".
            url = view.url().toString()
            host = self._crash_host(view.url().host())
            if not host:
                QTimer.singleShot(400, lambda v=view: v and v.reload())
                return
            if not hasattr(self, "_crash_ladder"):
                self._crash_ladder = CrashLadder()
            act = self._crash_ladder.record(host)
            log_line("crash-ladder: host=%s crash#%d in window -> %s"
                     % (host, len(self._crash_ladder.state[host]["times"]), act))
            cur = view is self.current_view()
            if act == "reload":
                QTimer.singleShot(400, lambda v=view: v and v.reload())
                if cur:
                    show_toast(self, "Page crashed — reloading it…")
            elif act == "cache":
                self._crash_clear_cache(view, host)
                QTimer.singleShot(2500, lambda v=view: v and v.reload())
                if cur:
                    show_toast(self, "Crashed twice — cleared the page cache, retrying…",
                               duration=6000)
            elif act == "safe":
                self._crash_enter_safe_mode(host)
                QTimer.singleShot(400, lambda v=view: v and v.reload())
                if cur:
                    show_toast(self, "Still crashing — retrying %s with WhyBrowse's "
                                     "page add-ons switched off" % host, duration=6000)
            else:                                     # "giveup" or "quiet"
                if act == "giveup":
                    log_line("crash-ladder: host=%s STILL CRASHED with WhyBrowse's "
                             "additions off (safe=%s) -> engine or site problem; giving up"
                             % (host, self._crash_ladder.is_safe(host)))
                self._crash_show_error(view, url, host, ask=(act == "giveup"))
        except Exception as e:
            log_line("render-terminated handler failed: %s" % e)

    # ---- DEL 56 helpers: "switch things off for ONE site, session only" ----
    #  self._crash_off = {host: {token, ...}}. A token switches one WhyBrowse feature
    #  (or ONE saved HIDE rule, token "hide:<selector>") off for that host until restart.
    #  The automatic safe mode (2nd crash) is just three tokens at once; the error page's
    #  "Try without..." lets YOU pick them one or several at a time. Nothing is saved.
    CRASH_TOKENS = [
        ("cosmetic", "Cosmetic script as a whole (HIDE rules, banners, cookie auto-accept, freezing, search-ad hiding)"),
        ("popup",    "Pop-up kill rules saved for this site"),
        ("stick",    "Sticky + freeze-element rules saved for this site"),
        ("nags",     "Cookie / donation banner hiding"),
        ("freeze",   "Animation freezing (CSS and JavaScript)"),
        ("scroll",   "Scroll-lock guard, Keep my place and scroll memory"),
        ("identity", "Browser identity script (Chrome identity, location spoof, passkeys)"),
        ("addons",   "Add-ons (userscripts)"),
        ("postload", "After-load helpers (auto-fill, form memory, eager images, macros, auction clock)"),
        ("adblock",  "Ad blocker (network blocking)"),
        ("3pc",      "Third-party-cookie blocking"),
        ("headers",  "Header rewriting (User-Agent / Sec-CH-UA)"),
        ("scripts",  "ALL scripts WhyBrowse injects into pages"),
    ]
    CRASH_OVR = {                       # token -> per-site exception it stands for
        "adblock": {"adblock_enabled": False},
        "nags":    {"hide_nag_banners": False},
        "freeze":  {"freeze_animations": False, "freeze_js": False},
        "scroll":  {"scroll_guard": False, "keep_scroll": False, "restore_scroll": False},
        "3pc":     {"block_third_party_cookies": False},
    }
    CRASH_AUTO = ("scripts", "postload", "headers")      # what the automatic safe mode drops

    def _crash_host(self, host):
        h = (host or "").lower()
        return h[4:] if h.startswith("www.") else h

    def _crash_tokens(self, host):
        off = getattr(self, "_crash_off", None)
        if not off:
            return set()
        h = self._crash_host(host)
        out = set()
        for d, toks in off.items():
            if h == d or h.endswith("." + d):
                out |= toks
        return out

    def _crash_has(self, host, *tokens):
        ts = self._crash_tokens(host)
        return bool(ts) and any(t in ts for t in tokens)

    def _crash_hosts_with(self, *tokens):
        """Hosts that have ANY of these tokens (for the script guards)."""
        return sorted(h for h, ts in (getattr(self, "_crash_off", None) or {}).items()
                      if any(t in ts for t in tokens))

    def _crash_overrides(self, host):
        """Per-site exception dict that the temporary tokens stand for."""
        out = {}
        for t in self._crash_tokens(host):
            out.update(self.CRASH_OVR.get(t, {}))
        return out

    def _crash_apply(self):
        """Push the current tokens into the interceptor, ad blocker and injected scripts."""
        try:
            self.adblock.safe_hosts = set(self._crash_hosts_with("headers"))
            self._apply_privacy()               # exemptions + rebuilds the injected scripts
        except Exception as e:
            log_line("crash-ladder: apply failed: %s" % e)

    def _crash_set(self, host, tokens, why):
        if not hasattr(self, "_crash_off"):
            self._crash_off = {}
        if tokens:
            self._crash_off[host] = set(tokens)
        else:
            self._crash_off.pop(host, None)
        self._crash_apply()
        log_line("crash-ladder: host=%s %s, switched off: %s"
                 % (host, why, ", ".join(sorted(tokens)) or "(nothing)"))
        # 20 s later: did it stay up? (the verdict tells which switch-off helped)
        QTimer.singleShot(20000, lambda h=host: self._crash_verdict(h))

    def _crash_clear_cache(self, view, host):
        """Empty the HTTP cache of this tab's profile (async, ~1-2 s). FOUND 2026-11-15:
        a stale/corrupt cache made boardgamegeek.com kill the renderer on every load."""
        try:
            view.page().profile().clearHttpCache()
            log_line("crash-ladder: host=%s cleared the HTTP cache of this profile" % host)
        except Exception as e:
            log_line("crash-ladder: clearHttpCache failed: %s" % e)
        QTimer.singleShot(22000, lambda h=host: self._crash_cache_verdict(h))

    def _crash_cache_verdict(self, host):
        try:
            if self._crash_ladder.cache_verdict(host) != "held":
                return
            log_line("crash-ladder: host=%s HELD for 20 s after clearing the HTTP cache "
                     "-> a bad cache entry was the cause" % host)
            v = self.current_view()
            if v is not None and self._crash_host(v.url().host()) == host:
                show_toast(self, "%s works again after clearing the page cache" % host,
                           duration=8000)
        except Exception:
            pass

    def _crash_clear_and_retry(self, view, url):
        """Error-page link 'Clear cache and try again'."""
        host = self._crash_host(QUrl(url).host())
        if not hasattr(self, "_crash_ladder"):
            self._crash_ladder = CrashLadder()
        st = self._crash_ladder._st(host)
        st["times"] = []
        st["gaveup"] = 0.0
        st["cache_at"] = time.time()
        st["cbase"] = st["total"]
        self._crash_clear_cache(view, host)
        QTimer.singleShot(2500, lambda v=view, u=url: v.setUrl(QUrl(u)))

    def _crash_merged_overrides(self):
        """settings' site_overrides plus the temporary 'Try without...' switches
        (a copy: the saved settings are never touched)."""
        base = self.settings.get("site_overrides", {}) or {}
        off = getattr(self, "_crash_off", None)
        if not off:
            return base
        out = {k: dict(v) if isinstance(v, dict) else v for k, v in base.items()}
        for h in off:
            tmp = self._crash_overrides(h)
            if tmp:
                cur = out.get(h)
                cur = dict(cur) if isinstance(cur, dict) else {}
                cur.update(tmp)
                out[h] = cur
        return out

    def _crash_enter_safe_mode(self, host):
        self._crash_ladder.mark_safe(host)
        self._crash_set(host, set(self._crash_tokens(host)) | set(self.CRASH_AUTO),
                        "safe mode")

    def _crash_verdict(self, host):
        try:
            if self._crash_ladder.verdict(host) != "held":
                return
            toks = sorted(t for t in self._crash_tokens(host))
            log_line("crash-ladder: host=%s HELD for 20 s with these switched off: %s "
                     "-> the cause is among them" % (host, ", ".join(toks)))
            v = self.current_view()
            if v is not None and self._crash_host(v.url().host()) == host:
                show_toast(self, "%s stayed up for 20 s without: %s"
                           % (host, ", ".join(toks)), duration=9000)
        except Exception:
            pass

    def _crash_show_error(self, view, url, host, ask):
        """Stop the reload loop: a static page instead of the crashing one."""
        from html import escape as _esc
        from urllib.parse import quote as _q
        try:
            view.stop()
        except Exception:
            pass
        newer = getattr(self, "_engine_newer", None)
        hint = ""
        if newer:
            hint = ("<p><b>A newer browser engine exists (PyQt6-WebEngine %s &rarr; %s).</b> "
                    "Close WhyBrowse and run <code>Update_engine.bat</code> in "
                    "Helpfiles\\WhyBrowse.</p>" % (_esc(str(newer[0])), _esc(str(newer[1]))))
        off = sorted(self._crash_tokens(host))
        offtxt = ("<p>Already switched off for this site (until you restart): <b>%s</b></p>"
                  % _esc(", ".join(off))) if off else ""
        page = ("<html><head><title>Page keeps crashing</title></head>"
                "<body style='font-family:Segoe UI,Arial;margin:48px;max-width:680px'>"
                "<h2>This page keeps crashing</h2>"
                "<p>The browser engine's page process for <b>%s</b> died several times in a "
                "row, so WhyBrowse stopped reloading it.</p>%s%s"
                "<p style='font-size:120%%'><a href=\"%s\">Try again</a> &nbsp;&nbsp;|&nbsp;&nbsp; "
                "<a href=\"wbcrash://clearcache/?u=%s\">Clear cache and try again</a> "
                "&nbsp;&nbsp;|&nbsp;&nbsp; "
                "<a href=\"wbcrash://without/?u=%s\">Try without&hellip;</a></p>"
                "<p><b>Try without&hellip;</b> lets you switch off one or several things "
                "WhyBrowse puts on this site (your HIDE rules, add-ons, ad blocker &hellip;) "
                "and try again, to find which one it is.</p>"
                "<p>Meanwhile this site can be opened in your system browser "
                "(menu: open in system browser).</p>"
                "<p style='color:#888'>Details are in the log (lines starting "
                "&quot;crash-ladder&quot;).</p></body></html>"
                % (_esc(host), hint, offtxt, _esc(url, quote=True), _esc(_q(url, safe="")),
                   _esc(_q(url, safe=""))))
        try:
            view.setHtml(page, QUrl(url))
        except Exception as e:
            log_line("crash-ladder: error page failed: %s" % e)
        if ask:
            def _ask(u=url, h=host):
                try:
                    r = QMessageBox.question(
                        self, "Page keeps crashing",
                        "%s crashed its page process several times in a row.\n\n"
                        "Open it in your system browser instead?\n"
                        "(Choose No to stay here: the error page has 'Try without...'.)" % h)
                    if r == QMessageBox.StandardButton.Yes:
                        self._open_in_system_browser(u)
                except Exception:
                    pass
            QTimer.singleShot(300, _ask)

    def _crash_without_dialog(self, view, url):
        """The 'Try without...' dialog: tick what to switch off for this site, then try."""
        host = self._crash_host(QUrl(url).host())
        if not host:
            return
        # Start from nothing ticked (the automatic safe mode switched a lot off at once,
        # which would hide which single thing matters); only YOUR earlier choices come back.
        have = (self._crash_tokens(host)
                if host in getattr(self, "_crash_manual", set()) else set())
        dlg = QDialog(self)
        dlg.setWindowTitle("Try %s without..." % host)
        dlg.setFixedSize(720, 600)
        lay = QVBoxLayout(dlg)
        lab = QLabel("Tick what WhyBrowse should leave OFF on <b>%s</b> for the next try. "
                     "Nothing is saved: it all comes back when you restart WhyBrowse.<br>"
                     "Start with your suspect (a single HIDE rule), then add more if it still "
                     "crashes. If the page stays up, the log and a message say which ones were "
                     "off." % host)
        lab.setWordWrap(True)
        lab.setFixedHeight(64)
        lay.addWidget(lab)
        area = QScrollArea()
        area.setWidgetResizable(True)
        inner = QWidget()
        il = QVBoxLayout(inner)
        boxes = []                                   # (token, checkbox)

        def add_head(text):
            h = QLabel("<b>%s</b>" % text)
            il.addWidget(h)

        def add_box(token, text, tip=""):
            cb = QCheckBox()
            cb.setText(text if len(text) <= 92 else text[:89] + "...")
            cb.setToolTip(tip or text)
            cb.setChecked(token in have)
            il.addWidget(cb)
            boxes.append((token, cb))

        def host_matches(dom):
            d = (dom or "").lower()
            return d == "*" or (d and d in host)
        hides = [r for r in (self.settings.get("element_hide_rules") or [])
                 if host_matches(r.get("domain")) and r.get("selector")]
        if hides:
            add_head("Your HIDE rules for this site (%d)" % len(hides))
            add_box("hide:*", "ALL of the HIDE rules below")
            for r in hides:
                add_box("hide:" + r["selector"], "HIDE  " + r["selector"], r["selector"])
        add_head("Features")
        for tok, text in self.CRASH_TOKENS:
            add_box(tok, text)
        il.addStretch(1)
        area.setWidget(inner)
        lay.addWidget(area, 1)
        row = QHBoxLayout()
        b_none = QPushButton("Untick all")
        b_try = QPushButton("Try now")
        b_cancel = QPushButton("Cancel")
        b_try.setDefault(True)
        row.addWidget(b_none)
        row.addStretch(1)
        row.addWidget(b_try)
        row.addWidget(b_cancel)
        lay.addLayout(row)
        b_none.clicked.connect(lambda: [cb.setChecked(False) for _t, cb in boxes])
        b_try.clicked.connect(dlg.accept)
        b_cancel.clicked.connect(dlg.reject)
        # Modal, in the house order: grab -> focus -> Escape closes (QDialog.exec_ is modal;
        # Escape = reject is built into QDialog).
        if not dlg.exec():
            return
        chosen = {t for t, cb in boxes if cb.isChecked()}
        # tokens of hide rules that are no longer listed (none) are dropped on purpose
        if not hasattr(self, "_crash_ladder"):
            self._crash_ladder = CrashLadder()
        self._crash_ladder.restart(host)             # fresh window, no auto-escalation
        if not hasattr(self, "_crash_manual"):
            self._crash_manual = set()
        self._crash_manual.add(host)
        self._crash_set(host, chosen, "manual try")
        try:
            view.setUrl(QUrl(url))
        except Exception:
            pass

    def _kill_view_media(self, w):
        """Immediately stop a view's audio/video before it is destroyed. Qt's
        deleteLater() is deferred, so a playing YouTube video would otherwise keep
        talking after the tab was closed (user had to kill the whole browser).
        We mute, stop the load, and blank the page to tear the renderer down now."""
        try:
            pg = w.page()
            if pg:
                pg.setAudioMuted(True)
            w.stop()
            if pg:
                pg.setUrl(QUrl("about:blank"))
        except Exception:
            pass

    def toggle_mute_current(self):
        """Mute/unmute the CURRENT tab's audio (the 🔊 toolbar button)."""
        v = self.current_view()
        if not v or not v.page():
            return
        pg = v.page()
        pg.setAudioMuted(not pg.isAudioMuted())
        self._update_mute_button()
        show_toast(self, "Tab muted 🔇" if pg.isAudioMuted() else "Tab unmuted 🔊")

    def _mute_all(self, state):
        for i in range(self.tabs.count()):
            v = self.tabs.widget(i)
            if v and v.page():
                v.page().setAudioMuted(state)
        self._update_mute_button()
        show_toast(self, "All tabs muted 🔇" if state else "All tabs unmuted 🔊")

    def _show_volume_menu(self):
        """Right-click the 🔊 button: a volume slider for THIS tab (QtWebEngine has
        no native per-tab volume, so we set the media elements' .volume via JS),
        plus mute/unmute-all actions."""
        m = QMenu(self)
        m.setStyleSheet(self._menu_style())
        v = self.current_view()
        cur = int(round(getattr(v, "_volume", 1.0) * 100)) if v else 100
        wa = QWidgetAction(m)
        box = QWidget()
        bl = QVBoxLayout(box)
        bl.setContentsMargins(12, 8, 12, 8)
        bl.addWidget(QLabel("Volume (this tab)"))
        s = QSlider(Qt.Orientation.Horizontal)
        s.setRange(0, 100)
        s.setValue(cur)
        s.setFixedWidth(170)
        s.valueChanged.connect(self._set_tab_volume)
        bl.addWidget(s)
        wa.setDefaultWidget(box)
        m.addAction(wa)
        m.addSeparator()
        m.addAction("🔇  Mute all tabs", lambda: self._mute_all(True))
        m.addAction("🔊  Unmute all tabs", lambda: self._mute_all(False))
        m.exec(QCursor.pos())

    def _set_tab_volume(self, val):
        v = self.current_view()
        if not v:
            return
        vol = max(0, min(100, int(val))) / 100.0
        v._volume = vol
        if vol > 0 and v.page() and v.page().isAudioMuted():
            v.page().setAudioMuted(False)      # raising volume implies unmute
            self._update_mute_button()
        self._apply_tab_volume(v)

    def _apply_tab_volume(self, view):
        try:
            vol = getattr(view, "_volume", None)
            if vol is None or not view.page():
                return
            view.page().runJavaScript(
                "document.querySelectorAll('video,audio').forEach("
                "function(m){try{m.volume=%f;}catch(e){}});" % float(vol))
        except Exception:
            pass

    def _toggle_clean_toolbar(self):
        """Toolbar 🧹: toggle global plain/clean mode (all features off) + reflect it."""
        new = not bool(self.settings.get("clean_mode"))
        self._toggle_setting("clean_mode", new)
        self._update_clean_button()

    def _update_clean_button(self):
        try:
            on = bool(self.settings.get("clean_mode"))
            if on:
                self.btn_clean.setStyleSheet(
                    "QPushButton{background:%s; color:%s; border:none; border-radius:6px;"
                    " font-size:13pt;}" % (C_ACCENT, C_ACCENT_FG))
            else:
                self.btn_clean.setStyleSheet(self._css_navbtn())
        except Exception:
            pass

    def _update_mute_button(self):
        try:
            v = self.current_view()
            muted = bool(v and v.page() and v.page().isAudioMuted())
            self.btn_mute.setText("🔇" if muted else "🔊")
        except Exception:
            pass

    def current_view(self):
        return self.tabs.currentWidget()

    # ======================================================================
    #  DEL 40 - ACTIVITY TRAIL + BUG REPORTER
    #  A cheap in-memory record of what happened in the active tab (which
    #  profile, which page, load ok/fail, tab & profile switches). When a page
    #  misbehaves (e.g. Tradera shows only a few ads and won't scroll) you
    #  press "Report a bug", add a comment, and everything is written to a file
    #  so the exact what / when / how can be reviewed later.
    # ======================================================================
    def _log_activity(self, kind, detail="", view=None):
        """Append one event to the activity trail. Never raises; cheap enough
        to sit on load / tab-change hot paths."""
        try:
            if view is None:
                view = self.current_view()
            prof = "?"
            try:
                prof = self._active_profile().get("name", self.active_id)
            except Exception:
                pass
            title = url = ""
            if view is not None:
                try:
                    title = view.title() or ""
                except Exception:
                    pass
                try:
                    url = view.url().toString() or ""
                except Exception:
                    pass
            self._activity.append({
                "t":       time.strftime("%H:%M:%S"),
                "ts":      time.time(),
                "profile": str(prof),
                "kind":    str(kind),
                "title":   title[:90],
                "url":     url[:220],
                "detail":  str(detail)[:220],
            })
            if len(self._activity) > self._activity_max:
                del self._activity[:-self._activity_max]
        except Exception:
            pass

    def open_bug_report(self):
        """Save-a-bug-report dialog (Ctrl+Shift+B / ☰ menu)."""
        self._log_activity("bug-report-opened")
        def _open():
            dlg = BugReportDialog(self)
            dlg.show()
            dlg.raise_()
            dlg.activateWindow()
            dlg.exec()
        QTimer.singleShot(0, _open)

    def open_profiles_overview(self):
        """Profiles overview / stats dashboard (☰ menu). Modeless so you can
        keep browsing while its memory / CPU figures update live. A single
        reference is kept so it isn't garbage-collected the moment it opens;
        re-opening raises the existing window instead of stacking copies."""
        def _open():
            dlg = getattr(self, "_profiles_dlg", None)
            if dlg is not None:
                try:
                    dlg._build()          # refresh contents
                    dlg.show()
                    dlg.raise_()
                    dlg.activateWindow()
                    return
                except Exception:
                    self._profiles_dlg = None
            dlg = ProfilesOverviewDialog(self)
            self._profiles_dlg = dlg
            dlg.show()
            dlg.raise_()
            dlg.activateWindow()
        QTimer.singleShot(0, _open)

    def _all_profile_views(self):
        """Every LIVE view across all profiles, grouped for the dashboard and
        the bug report. Returns a list of dicts:
            {pid, name, active, badge, views:[view, ...]}
        The active profile's tabs come from the tab bar; every other profile's
        tabs come from live_views (kept alive when keep_profile_tabs_alive is
        on, which is the default)."""
        out = []
        seen = set()
        # Active profile first, from the visible tab bar.
        act_views = [self.tabs.widget(i) for i in range(self.tabs.count())]
        act_views = [v for v in act_views if v is not None]
        try:
            act = self._active_profile() or {}
        except Exception:
            act = {}
        out.append({"pid": self.active_id, "name": act.get("name", self.active_id),
                    "active": True, "badge": act.get("badge", ""), "views": act_views})
        seen.add(self.active_id)
        # Other profiles that still have views kept alive this session.
        for pid, views in (self.live_views or {}).items():
            if pid in seen:
                continue
            live = [v for v in (views or []) if v is not None]
            if not live:
                continue
            prof = self._profile_by_id(pid) or {}
            out.append({"pid": pid, "name": prof.get("name", pid), "active": False,
                        "badge": prof.get("badge", ""), "views": live})
            seen.add(pid)
        # Finally, list EVERY other configured profile with no live tabs this
        # session, so the overview shows all profiles (not just the ones opened
        # so far). Their per-tab rows appear once the profile is opened. The
        # virtual "Favourites" (99) profile is skipped - it holds no real tabs.
        for p in (self.settings.get("profiles") or []):
            pid = p.get("id")
            if not pid or pid in seen or pid == FAV_PROFILE_ID:
                continue
            out.append({"pid": pid, "name": p.get("name", pid), "active": False,
                        "badge": p.get("badge", ""), "views": [], "empty": True})
            seen.add(pid)
        return out

    def _dash_set_flag(self, view, flag, value):
        """Quick-set a tab flag from the dashboard. For the ACTIVE profile's
        tabs we call the real setters (so the tab bar / labels update). For a
        background profile's kept-alive view we set the attribute directly -
        the tab bar has no entry for it, and the value is honoured when you
        switch back to that profile."""
        in_bar = self.tabs.indexOf(view) >= 0
        try:
            if flag == "pin":
                if bool(getattr(view, "_pinned", False)) == bool(value):
                    return
                if in_bar:
                    self._toggle_pin(view)
                else:
                    view._pinned = bool(value)
                    try:
                        view.page().keep_pinned = bool(value)
                    except Exception:
                        pass
                    if value and not getattr(view, "_pin_url", None):
                        view._pin_url = view.url().toString()
                    elif not value:
                        view._pin_url = None
            elif flag == "autorefresh":
                if in_bar:
                    self._set_tab_autorefresh(view, value)
                else:
                    view._auto_refresh = bool(value)
            elif flag == "nosleep":
                if in_bar:
                    self._set_no_sleep(view, value)
                else:
                    # A background profile's view: just set the flag. If it is
                    # already asleep it stays asleep until you switch back to
                    # that profile and click it - waking a hidden page here
                    # would only spend the memory we just saved.
                    view._no_sleep = bool(value)
            elif flag == "lock":
                # value is the numeric level (0..3)
                try:
                    view.page().lock_level = int(value)
                except Exception:
                    pass
                if in_bar:
                    self._refresh_tab_label(view)
        except Exception:
            pass

    def _bug_flag_str(self, v):
        parts = []
        if getattr(v, "_pinned", False):       parts.append("pin")
        if getattr(v, "_auto_refresh", False): parts.append("refresh")
        if getattr(v, "_no_sleep", False):     parts.append("nosleep")
        if getattr(v, "_asleep", False):       parts.append("ASLEEP")
        try:
            lv = self._lock(v)
        except Exception:
            lv = 0
        if lv:
            parts.append("lock%d" % lv)
        return ",".join(parts) or "-"

    def _bug_tab_dict(self, v):
        d = {"pinned":       bool(getattr(v, "_pinned", False)),
             "auto_refresh": bool(getattr(v, "_auto_refresh", False)),
             "no_sleep":     bool(getattr(v, "_no_sleep", False)),
             "asleep":       bool(getattr(v, "_asleep", False))}
        try:
            d["lock"] = int(self._lock(v))
        except Exception:
            d["lock"] = 0
        try:
            d["title"] = v.title() or ""
        except Exception:
            d["title"] = ""
        try:
            d["url"] = v.url().toString()
        except Exception:
            d["url"] = ""
        try:
            d["zoom"] = round(v.zoomFactor(), 2)
        except Exception:
            pass
        return d

    def _bug_context_text(self):
        """Human-readable snapshot of the current tab + browser state."""
        v = self.current_view()
        try:
            prof = self._active_profile() or {}
        except Exception:
            prof = {}
        L = ["Profile:    %s   (id=%s)" % (prof.get("name", "?"), self.active_id)]
        if v is not None:
            try:
                L.append("Tab title:  %s" % (v.title() or ""))
            except Exception:
                pass
            try:
                L.append("Tab URL:    %s" % v.url().toString())
            except Exception:
                pass
            L.append("Tab flags:  %s" % self._bug_flag_str(v))
            try:
                L.append("Zoom:       %.2fx" % v.zoomFactor())
            except Exception:
                pass
        L.append("Low-vision: %s      Plain/clean mode: %s"
                 % ("on" if self.settings.get("low_vision") else "off",
                    "on" if prof.get("clean") else "off"))
        L.append("Ad blocker: %s"
                 % ("on" if self.settings.get("adblock_enabled", True) else "off"))
        L.append("Live profiles / tabs:")
        for g in self._all_profile_views():
            L.append("    %s%s : %d tab(s)"
                     % ("* " if g["active"] else "  ", g["name"], len(g["views"])))
        return "\n".join(L)

    def _activity_trail_text(self, n=120):
        if not self._activity:
            return "(no activity recorded yet)"
        out = []
        for e in self._activity[-n:]:
            line = "[%s] %-13s (%s) %s" % (
                e["t"], e["kind"], e["profile"][:14],
                (e["title"] or e["url"])[:70])
            if e["detail"]:
                line += "  -- " + e["detail"]
            out.append(line)
        return "\n".join(out)

    def _write_bug_report(self, comment):
        """Write the report (.txt + .json sidecar) to BUGREPORT_DIR. The report
        deliberately contains NO passwords, vault contents or cookies -- only
        metadata about tabs, settings and the activity trail. Returns the .txt
        path, or None on failure."""
        try:
            os.makedirs(BUGREPORT_DIR, exist_ok=True)
            stamp = time.strftime("%Y-%m-%d_%H-%M-%S")
            base = os.path.join(BUGREPORT_DIR, "bugreport_%s" % stamp)

            try:
                from PyQt6.QtCore import QT_VERSION_STR as _QTV
            except Exception:
                _QTV = "?"
            engine = "?"
            try:
                from PyQt6.QtWebEngineCore import (qWebEngineVersion,
                                                   qWebEngineChromiumVersion)
                engine = "QtWebEngine %s / Chromium %s" % (
                    qWebEngineVersion(), qWebEngineChromiumVersion())
            except Exception:
                pass

            T = ["WhyBrowse bug report",
                 "Saved: %s" % time.strftime("%Y-%m-%d %H:%M:%S"),
                 "=" * 66, "",
                 "YOUR COMMENT", "-" * 66,
                 (comment or "(none)").strip(), "",
                 "SYSTEM", "-" * 66,
                 "App:     %s" % APP_VERSION,
                 "Engine:  %s" % engine,
                 "Qt:      %s" % _QTV,
                 "Python:  %s" % platform.python_version(),
                 "OS:      %s %s" % (platform.system(), platform.release()),
                 "Base:    %s" % BASE_DIR,
                 "psutil:  %s" % ("yes" if psutil else "no (mem/cpu unavailable)"),
                 "",
                 "CONTEXT", "-" * 66,
                 self._bug_context_text(), "",
                 "OPEN TABS (all live profiles)", "-" * 66]
            for g in self._all_profile_views():
                T.append("Profile %s%s:" % ("* " if g["active"] else "", g["name"]))
                for v in g["views"]:
                    try:
                        T.append("   - [%s] %s  <%s>"
                                 % (self._bug_flag_str(v), (v.title() or "")[:70],
                                    v.url().toString()[:120]))
                    except Exception:
                        pass
            T += ["", "ACTIVITY TRAIL (oldest first)", "-" * 66,
                  self._activity_trail_text(self._activity_max)]
            with open(base + ".txt", "w", encoding="utf-8") as f:
                f.write("\n".join(T))

            data = {
                "saved":  time.strftime("%Y-%m-%d %H:%M:%S"),
                "app":    APP_VERSION, "engine": engine, "qt": _QTV,
                "python": platform.python_version(),
                "os":     "%s %s" % (platform.system(), platform.release()),
                "comment": comment or "",
                "active_profile": self.active_id,
                "profiles": [
                    {"pid": g["pid"], "name": g["name"], "active": g["active"],
                     "tabs": [self._bug_tab_dict(v) for v in g["views"]]}
                    for g in self._all_profile_views()],
                "activity": list(self._activity)}
            try:
                with open(base + ".json", "w", encoding="utf-8") as f:
                    json.dump(data, f, ensure_ascii=False, indent=2)
            except Exception:
                pass
            log_line("Bug report saved: %s.txt" % base)
            return base + ".txt"
        except Exception as e:
            log_line("Bug report save failed: %s" % e)
            return None

    def show_tab_search(self):
        """Find/jump to any open tab by typing - handy with lots of tabs."""
        TabSearchDialog(self).exec()

    # ----------------------------------------------------- split view ----
    def toggle_split_view(self):
        """Show/hide a second page beside the tabs (its own scroll); optional
        synced scrolling via the checkbox in the pane's little toolbar."""
        if self.second_pane.isVisible():
            self.second_pane.hide()
            if hasattr(self, "_sync_timer"):
                self._sync_timer.stop()
            return
        if self.second_view is None:
            self.second_view = BrowserView(self)
            self.second_view.setPage(WebPage(self.engine, self))
            try:
                s = self.second_view.settings()
                s.setAttribute(QWebEngineSettings.WebAttribute.PluginsEnabled, True)
                s.setAttribute(QWebEngineSettings.WebAttribute.PdfViewerEnabled, True)
                s.setAttribute(QWebEngineSettings.WebAttribute.JavascriptCanAccessClipboard, True)
                s.setAttribute(QWebEngineSettings.WebAttribute.JavascriptCanPaste, True)
            except Exception:
                pass
            self.second_view.urlChanged.connect(
                lambda u: self.second_addr.setText("" if is_blank_page(u.toString()) else u.toString()))
            self._second_lay.addWidget(self.second_view, 1)
            cur = self.current_view()
            start = cur.url().toString() if cur else self.settings.get("home_url", DEFAULT_HOME)
            self.second_view.setUrl(QUrl(start if start.startswith("http")
                                         else self.settings.get("home_url", DEFAULT_HOME)))
        self.second_pane.show()
        self.split.setSizes([max(1, self.width() // 2), max(1, self.width() // 2)])
        if self.second_sync.isChecked():
            self._toggle_sync_scroll(True)

    def _second_navigate(self):
        if self.second_view is None:
            return
        q = normalize_url(self.second_addr.text(), self.settings.get("search_engine", SEARCH_URL))
        self.second_view.setUrl(q)

    def _toggle_sync_scroll(self, on):
        if on and self.second_pane.isVisible():
            if not hasattr(self, "_sync_timer"):
                self._sync_timer = QTimer(self)
                self._sync_timer.timeout.connect(self._sync_tick)
            self._sync_timer.start(120)
        elif hasattr(self, "_sync_timer"):
            self._sync_timer.stop()

    def _sync_tick(self):
        """Mirror the active tab's vertical scroll onto the second pane."""
        lv, rv = self.current_view(), self.second_view
        if not (lv and rv) or not self.second_pane.isVisible():
            return
        try:
            lv.page().runJavaScript(
                "Math.round(window.scrollY)",
                lambda y, r=rv: r.page().runJavaScript(
                    "window.__wbScrollOK=1;window.scrollTo(0,%d)" % int(y))
                if isinstance(y, (int, float)) else None)
        except Exception:
            pass

    # ----------------------------------------------------- tab right-click ----
    # ======================================================================
    #  CONTAINER TABS  (separate logins in the SAME window - no profile switch)
    # ----------------------------------------------------------------------
    #  A container is a named, independent cookie store. A container tab reuses
    #  the normal per-id engine machinery (_get_engine / _build_engine), so its
    #  login persists across restarts exactly like a profile's does - but it
    #  shows up as an ordinary tab in the current window. That lets you keep,
    #  say, two Gmail accounts open as two tabs at once without switching
    #  profiles. Container ids are prefixed "ctr_" so they never clash with
    #  profile ids, and their Chromium storage lives in Helpfiles/.../profiles/
    #  <ctr_id>/ (see profile_paths()).
    # ======================================================================
    def _containers(self):
        c = self.settings.get("containers")
        if not isinstance(c, list):
            c = []
            self.settings["containers"] = c
        return c

    def _container_by_id(self, cid):
        for c in self._containers():
            if c.get("id") == cid:
                return c
        return None

    def _container_name(self, cid):
        # Resolve a real container OR a profile id (a Favourites tab bound to
        # another profile's login rides the same _container slot for its label).
        c = self._container_by_id(cid)
        if c:
            return c.get("name")
        return self._engine_label(cid) or "Container"

    def _container_color(self, cid):
        c = self._container_by_id(cid)
        return (c.get("color") if c else None) or "#e08a3c"

    def _save_containers(self):
        save_json(SETTINGS_FILE, self.settings)

    def _create_container(self, name, color="#e08a3c"):
        import uuid
        cid = "ctr_" + uuid.uuid4().hex[:8]
        self._containers().append(
            {"id": cid, "name": (name or "Container").strip()[:24], "color": color})
        self._save_containers()
        return cid

    def _prompt_and_open_container(self, url=None):
        name, ok = QInputDialog.getText(
            self, "New container",
            "Name this container (e.g. 'Work Gmail', 'Personal'):")
        if not ok or not name.strip():
            return
        col = QColorDialog.getColor(QColor("#e08a3c"), self, "Container colour")
        cid = self._create_container(name, col.name() if col.isValid() else "#e08a3c")
        self._open_container_tab(cid, url)

    def _open_container_tab(self, cid, url=None):
        v = self.add_tab(url or new_tab_url(), switch=True, container=cid)
        self._refresh_tab_label(v)
        show_toast(self, "New tab in container: %s" % self._container_name(cid))
        return v

    def _move_tab_to_container(self, view, cid):
        """Open the current tab's URL in a container tab (its own login)."""
        url = view.url().toString()
        if not url.startswith("http"):
            url = None
        self._open_container_tab(cid, url)

    def _rename_container(self, cid):
        c = self._container_by_id(cid)
        if not c:
            return
        name, ok = QInputDialog.getText(self, "Rename container",
                                        "Container name:", text=c.get("name", ""))
        if ok and name.strip():
            c["name"] = name.strip()[:24]
            self._save_containers()
            self._relabel_container_tabs(cid)

    def _recolor_container(self, cid):
        c = self._container_by_id(cid)
        if not c:
            return
        col = QColorDialog.getColor(QColor(c.get("color", "#e08a3c")), self,
                                    "Container colour")
        if col.isValid():
            c["color"] = col.name()
            self._save_containers()
            self._relabel_container_tabs(cid)

    def _relabel_container_tabs(self, cid):
        for i in range(self.tabs.count()):
            v = self.tabs.widget(i)
            if v and getattr(v, "_container", None) == cid:
                self._refresh_tab_label(v)

    def _delete_container(self, cid):
        c = self._container_by_id(cid)
        if not c:
            return
        if QMessageBox.question(
                self, "Delete container",
                "Delete container '%s'?\n\nIts open tabs will be closed and its "
                "saved login / cookies forgotten." % c.get("name", "?"),
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.Cancel
                ) != QMessageBox.StandardButton.Yes:
            return
        for i in range(self.tabs.count() - 1, -1, -1):
            v = self.tabs.widget(i)
            if v and getattr(v, "_container", None) == cid:
                self.tabs.removeTab(i)
                self._kill_view_media(v)
                v.deleteLater()
        self.settings["containers"] = [x for x in self._containers()
                                       if x.get("id") != cid]
        self._save_containers()
        # Best-effort wipe of its on-disk cookie store (may be locked while the
        # engine is still alive this session; then it's just leftover disk).
        try:
            shutil.rmtree(os.path.join(PROFILES_DIR, cid), ignore_errors=True)
        except Exception:
            pass
        show_toast(self, "Container deleted")

    def _build_containers_menu(self, parent_menu, view):
        cm = parent_menu.addMenu("🫙  Containers  (separate logins)")
        cm.setStyleSheet(self._menu_style(1))
        cur = getattr(view, "_container", None)
        if cur:
            a = cm.addAction("● In container: %s" % self._container_name(cur))
            a.setEnabled(False)
            cm.addSeparator()
        cm.addAction("➕  New container + blank tab...",
                     lambda: self._prompt_and_open_container(None))
        cont = self._containers()
        if cont:
            nt = cm.addMenu("➕  New tab in container")
            nt.setStyleSheet(self._menu_style(2))
            for c in cont:
                nt.addAction(c.get("name", "?"),
                             lambda _=False, cid=c["id"]: self._open_container_tab(cid))
            mv = cm.addMenu("↪  Open THIS page in container")
            mv.setStyleSheet(self._menu_style(2))
            for c in cont:
                mv.addAction(c.get("name", "?"),
                             lambda _=False, cid=c["id"], v=view:
                             self._move_tab_to_container(v, cid))
            mng = cm.addMenu("⚙  Manage containers")
            mng.setStyleSheet(self._menu_style(2))
            for c in cont:
                sub = mng.addMenu(c.get("name", "?"))
                sub.setStyleSheet(self._menu_style(2))
                sub.addAction("✎  Rename...",
                              lambda _=False, cid=c["id"]: self._rename_container(cid))
                sub.addAction("🎨  Colour...",
                              lambda _=False, cid=c["id"]: self._recolor_container(cid))
                sub.addAction("🗑  Delete",
                              lambda _=False, cid=c["id"]: self._delete_container(cid))

    def _tab_context_menu(self, pos):
        bar = self.tabs.tabBar()
        idx = bar.tabAt(pos)
        if idx < 0:
            return
        view = self.tabs.widget(idx)
        host = clean_host(view.url().host())
        menu = QMenu(self)
        menu.setStyleSheet(self._menu_style())

        # --- General actions: one compact, centred icon row at the top ---
        menu.addAction(self._tab_actions_row(menu, view, idx))

        # --- THIS TAB (one-off, only this physical tab) ---
        self._section_header(menu, "THIS TAB", "#26334d")          # bluish band
        self._add_behavior_items(menu, view, host, domain=False)
        menu.addAction("✎  Rename tab...", lambda: self._rename_tab(view))
        if getattr(view, "_custom_title", None):
            menu.addAction("↺  Use the page's own title", lambda: self._rename_tab(view, ""))
        menu.addAction("🔍  Custom size for this page/domain...",
                       lambda: ZoomSizeDialog(self, view).exec())

        # --- THIS DOMAIN (applies to any tab that visits this domain) ---
        menu.addSeparator()
        self._section_header(menu, "THIS DOMAIN" + (" · %s" % host if host else ""),
                             "#24402f")                            # greenish band
        if host:
            self._add_behavior_items(menu, view, host, domain=True)
            menu.addAction("🏷  Rename this domain...",
                           lambda: self._rename_domain(view, per_page=False))
            # Scroll-position memory toggle here too — handy for sites like Google
            # Sheets that hijack the PAGE right-click, so the page menu can't reach it.
            sc = menu.addAction("📍  Remember scroll position here")
            sc.setCheckable(True)
            sc.setChecked(self._restore_scroll_on(host))
            sc.triggered.connect(
                lambda v, h=host: self._set_site_override(h, "restore_scroll", v))
            # Content cousin of the above: land on a WORD instead of a pixel row.
            cur_w, _cur_o = self._find_word_for(host)
            fw_lbl = ("🔎  Jump to a word here…  (now: “%s”)" % cur_w[:18]) if cur_w \
                else "🔎  Jump to a word on this site…"
            menu.addAction(fw_lbl,
                           lambda _=False, v=view, h=host: self._prompt_find_word(v, h))
            # Which folder this site's UPLOAD picker starts in (downloads are
            # separate and all go to your one download folder).
            cur_up = self._upload_dir_for(host)
            up_lbl = ("📤  Upload folder here…  (now: %s)" % self._short_path(cur_up)) \
                if cur_up else "📤  Upload folder for this site…"
            menu.addAction(up_lbl, lambda _=False, h=host: self._set_upload_dir(h))
            if cur_up:
                menu.addAction("✖  Clear upload folder for this site",
                               lambda _=False, h=host: self._clear_upload_dir(h))
            # Bulk upload: pick every picture once, then the file dialog stops
            # appearing at all (DEL 21J).
            if getattr(self, "_upload_queue", None):
                menu.addAction("📤  Bulk upload: %d of %d sent — stop it"
                               % (self._bulk_sent, self._bulk_total),
                               self._bulk_stop)
            else:
                menu.addAction("📤📤  Upload SEVERAL files here (one after another)…",
                               self.start_bulk_upload)
            ql = self._build_quicklinks_menu(view)
            ql.setTitle("🔗  Quick links / saved sub-pages")
            menu.addMenu(ql)
            # Google Sheets: browser-side "go to row/cell" + saved jumps (per sheet).
            if self._sheet_info(view):
                sm = self._sheet_jumps_menu(view)
                sm.setTitle("📊  Go to row / cell  (Sheets jumps)")
                menu.addMenu(sm)
        else:
            na = menu.addAction("(no domain here)")
            na.setEnabled(False)

        menu.addSeparator()
        menu.addAction("☆  Copy to bookmarks bar",
                       lambda: self._copy_tab_to_bar(view))
        pop_menu = menu.addMenu("🪟  Pop out to floating window")
        pop_menu.setStyleSheet(self._menu_style(1))
        pop_menu.addAction("📌  Always on top",
                           lambda: self._pop_out_tab(view, True))
        pop_menu.addAction("🪟  Normal window (can go behind others)",
                           lambda: self._pop_out_tab(view, False))
        # Container tabs: separate logins (e.g. a 2nd Gmail) without switching profile.
        self._build_containers_menu(menu, view)
        menu.addSeparator()
        cm = menu.addMenu("✕  Close")
        cm.setStyleSheet(self._menu_style(1))
        cm.addAction("Close this tab", lambda: self.close_tab(self.tabs.indexOf(view)))
        cm.addAction("Close tabs to the LEFT", lambda: self._close_side(idx, "left"))
        cm.addAction("Close tabs to the RIGHT", lambda: self._close_side(idx, "right"))
        cm.addAction("Close other tabs", lambda: self._close_others(view))
        if self._closed_tabs:
            cm.addSeparator()
            cm.addAction("↩  Reopen last closed tab (Ctrl+Shift+T)",
                         self.reopen_closed_tab)
        menu.exec(bar.mapToGlobal(pos))

    def _pop_out_tab(self, view, always_on_top=True):
        """Open the current tab's page in a floating mini window on the SAME
        profile engine (so it survives profile switches + shares login).
        `always_on_top` is chosen per pop-out (see the "Pop out..." submenu)
        and can still be flipped afterwards with the floating window's own
        📌 button."""
        try:
            url = view.url().toString()
            if not url.startswith("http"):
                show_toast(self, "Nothing to pop out here")
                return
            if not hasattr(self, "_floats"):
                self._floats = []
            self._floats = [f for f in self._floats if f.isVisible()]
            ft = FloatingTab(self, self.engine, url, view.title(),
                             always_on_top=always_on_top)
            self._floats.append(ft)
            ft.show()
            # Without WindowStaysOnTopHint, some window managers don't
            # automatically bring a freshly created window to the front if
            # the main window still has focus (e.g. right after a context-
            # menu click) - it can end up hidden right behind the main
            # window, looking like it "never opened". Force it forward once
            # at creation time regardless of always_on_top; after that, the
            # on-top setting alone decides whether it STAYS in front.
            ft.raise_()
            ft.activateWindow()
            show_toast(self, "Popped out (always on top)" if always_on_top
                      else "Popped out (normal window, can go behind others)")
        except Exception as e:
            log_line("pop out error: %s" % e)

    # ---------------------------------- Google Sheets: browser-side jumps ----
    #  A "jump" goes to a cell, optionally on a named sheet-tab: target "Sold:D260"
    #  = tab "Sold", cell D260 (just "D260" or "260" = current tab). We click the
    #  named bottom tab (no reload) then type the cell into Sheets' Name Box. Jumps
    #  are saved per spreadsheet; an "auto" jump fires when you open/switch to its
    #  tab (shown with a • dot). Robust retries cover the slow blue-loading phase.
    #
    #  Multiple AUTO jumps per spreadsheet, one per tab (e.g. Games:D260 AND
    #  Sold:D2075 in the SAME spreadsheet), are supported: each jump remembers
    #  the internal tab id ("gid") it belongs to. When a jump names a tab you
    #  were NOT sitting on while saving it, we don't guess the wrong gid - we
    #  leave it unresolved and learn the real one automatically the first time
    #  you actually land on that tab (see _sheet_resolve_active_tab_name), by
    #  reading the tab's own name off the page. After that it's remembered.
    def _sheet_parse_target(self, s):
        """'Sold:D260' -> ('Sold','D260'); 'D260'/'260' -> ('','D260'/'A260');
        a pure range like 'A1:B5' stays a range with no tab."""
        s = (s or "").strip()
        if re.match(r'^[A-Za-z]+\d+(:[A-Za-z]+\d+)?$', s) or s.isdigit():
            cell = ("A" + s) if s.isdigit() else s.upper()
            return "", cell
        tab, cell = "", s
        if ":" in s:
            tab, cell = s.split(":", 1)
        tab = tab.strip()
        cell = cell.strip().upper().replace(" ", "")
        if cell.isdigit():
            cell = "A" + cell
        return tab, cell

    def _sheet_target_str(self, j):
        cell = j.get("cell", "")
        tab = j.get("tab", "")
        return ("%s:%s" % (tab, cell)) if tab else cell

    def _sheet_jumps(self, sid):
        """The migrated jump list for a spreadsheet (old {name,range,gid} and old
        sheet_autojump entries are folded into the new {name,tab,cell,gid,auto})."""
        store = self.settings.setdefault("sheet_jumps", {})
        lst = store.setdefault(sid, [])
        for j in lst:
            if "cell" not in j and "range" in j:
                j["cell"] = j.pop("range")
            j.setdefault("tab", "")
            j.setdefault("cell", "")
            j.setdefault("gid", "")
            j.setdefault("auto", False)
        auto = (self.settings.get("sheet_autojump") or {}).get(sid)
        if auto:
            for gid, cell in auto.items():
                if not any(x.get("gid") == gid and x.get("auto") for x in lst):
                    lst.append({"name": "Auto " + cell, "tab": "", "cell": cell,
                                "gid": gid, "auto": True})
            self.settings.get("sheet_autojump", {}).pop(sid, None)
            save_json(SETTINGS_FILE, self.settings)
        return lst

    def _sheet_jump_js(self, tab, cell):
        return ("(function(tab,cell){try{"
                "function setCell(){var nb=document.getElementById('t-name-box');"
                "if(!nb)return false;nb.focus();nb.value=cell;"
                "nb.dispatchEvent(new Event('input',{bubbles:true}));"
                "['keydown','keypress','keyup'].forEach(function(t){"
                "nb.dispatchEvent(new KeyboardEvent(t,{key:'Enter',code:'Enter',"
                "keyCode:13,which:13,bubbles:true}));});"
                "setTimeout(function(){try{nb.blur();}catch(_){}},80);return true;}"
                "var done=false;"
                "if(tab){var ts=document.querySelectorAll('.docs-sheet-tab');"
                "for(var i=0;i<ts.length;i++){var nm=ts[i].querySelector('.docs-sheet-tab-name');"
                "var lbl=((nm?nm.textContent:ts[i].textContent)||'').trim().toLowerCase();"
                "if(lbl===tab.trim().toLowerCase()){ts[i].click();done=true;break;}}}"
                "if(tab&&done){setTimeout(setCell,400);return 'tab';}"
                "return setCell()?'cell':false;"
                "}catch(e){return false;}})(%s,%s);"
                % (json.dumps(tab or ""), json.dumps(cell or "")))

    def _sheet_exec_jump(self, view, tab, cell, tries=0):
        """Run a jump, retrying while the sheet is still loading (Name Box absent)."""
        if not cell:
            return
        js = self._sheet_jump_js(tab, cell)

        def cb(res, v=view, tb=tab, c=cell, t=tries):
            if res is False and t < 12:            # not ready yet -> keep trying ~14s
                QTimer.singleShot(1200, lambda: self._sheet_exec_jump(v, tb, c, t + 1))
        try:
            view.page().runJavaScript(js, cb)
        except Exception:
            pass

    def _sheet_go_jump(self, view, jump):
        self._sheet_exec_jump(view, jump.get("tab", ""), jump.get("cell", ""))
        show_toast(self, "Going to %s" % self._sheet_target_str(jump))

    def _open_sheet_jumps(self, view):
        info = self._sheet_info(view)
        if info:
            SheetJumpsDialog(self, view, info[0]).exec()

    def _maybe_sheet_autojump(self, view):
        """On load / tab-switch: an explicit auto-jump for THIS tab wins; otherwise
        return to the LAST active cell we remembered for it (so an auto-refresh
        doesn't drop you back to A1). Both off → do nothing.

        A spreadsheet can have SEVERAL auto-jumps at once, one per tab (e.g.
        Games:D260 and Sold:D2075 side by side) - matched fast by "gid" once
        known. A jump saved with an explicit "Tab:Cell" target may not have
        its real gid yet (it can be added without first switching to that
        tab) - for those we fall back to reading the ACTUAL active tab's own
        name off the page and matching it by name instead; once matched, the
        gid is learned permanently so future visits use the fast path."""
        info = self._sheet_info(view)
        if not info:
            return
        sid, gid = info
        jumps = self._sheet_jumps(sid)

        # Fast path: this jump's gid is already known and matches THIS tab.
        for j in jumps:
            if j.get("auto") and j.get("cell") and str(j.get("gid", "")) == str(gid):
                self._sheet_exec_jump(view, "", j["cell"])
                return

        # Fallback: auto-jumps that name a tab but aren't (yet) resolved to
        # THIS tab's gid - read the real tab name and try to match by name.
        pending = [j for j in jumps
                   if j.get("auto") and j.get("cell") and j.get("tab")
                   and str(j.get("gid", "")) != str(gid)]
        if pending:
            self._sheet_resolve_active_tab_name(view, sid, gid, pending)
            return  # the resolver handles firing the jump (or the fallback below)

        if self.settings.get("sheet_remember_cell", True):
            cell = ((self.settings.get("sheet_lastcell") or {}).get(sid)
                    or {}).get(str(gid))
            if cell:
                self._sheet_exec_jump(view, "", cell)

    def _sheet_resolve_active_tab_name(self, view, sid, gid, pending):
        """Read the CURRENTLY active Sheets tab's own name off the page. If it
        matches one of the 'pending' auto-jumps' saved tab name, fire that jump
        and permanently learn its gid (so _maybe_sheet_autojump takes the fast
        gid-matched path next time instead of doing this lookup again). If
        nothing matches, fall back to the last-remembered cell for this tab."""
        js = ("(function(){try{"
              "var el=document.querySelector('.docs-sheet-tab.docs-sheet-active-tab')"
              "||document.querySelector('.docs-sheet-tab[aria-selected=\"true\"]');"
              "if(!el){var all=document.querySelectorAll('.docs-sheet-tab');"
              "for(var i=0;i<all.length;i++){if(all[i].getAttribute('aria-selected')==='true'"
              "||/active/i.test(all[i].className)){el=all[i];break;}}}"
              "if(!el)return '';"
              "var nm=el.querySelector('.docs-sheet-tab-name');"
              "return ((nm?nm.textContent:el.textContent)||'').trim();"
              "}catch(e){return '';}})();")

        def cb(name, view=view, sid=sid, gid=gid, pending=pending):
            name = (name or "").strip().lower()
            if name:
                for j in pending:
                    if (j.get("tab") or "").strip().lower() == name:
                        j["gid"] = gid          # learned - fast path from now on
                        save_json(SETTINGS_FILE, self.settings)
                        self._sheet_exec_jump(view, "", j["cell"])
                        return
            # No name match for this tab among the pending jumps - same
            # fallback as the normal (non-pending) path.
            if self.settings.get("sheet_remember_cell", True):
                cell = ((self.settings.get("sheet_lastcell") or {}).get(sid)
                        or {}).get(str(gid))
                if cell:
                    self._sheet_exec_jump(view, "", cell)
        try:
            view.page().runJavaScript(js, cb)
        except Exception:
            pass

    def _sheet_capture_lastcell(self, view):
        """Remember the current active cell of a Sheets tab (the Name Box value),
        so we can return to it on the next (re)load. Only writes when it changed."""
        if not self.settings.get("sheet_remember_cell", True):
            return
        info = self._sheet_info(view)
        if not info:
            return
        sid, gid = info
        js = ("(function(){try{var nb=document.getElementById('t-name-box');"
              "return nb?(nb.value||''):'';}catch(e){return '';}})();")

        def cb(res, sid=sid, gid=str(gid)):
            cell = (res or "").strip().upper()
            # keep single cells (A1, D260) AND ranges (A1:B5); skip blanks/odd values
            if not re.match(r'^[A-Z]+\d+(:[A-Z]+\d+)?$', cell):
                return
            store = self.settings.setdefault("sheet_lastcell", {})
            cur = store.setdefault(sid, {})
            if cur.get(gid) != cell:
                cur[gid] = cell
                save_json(SETTINGS_FILE, self.settings)
        try:
            view.page().runJavaScript(js, cb)
        except Exception:
            pass

    def _sheet_jumps_menu(self, view):
        """Quick submenu: saved jumps (• = auto) + Manage."""
        m = QMenu(self)
        m.setStyleSheet(self._menu_style(2))
        info = self._sheet_info(view)
        if info:
            for j in self._sheet_jumps(info[0]):
                dot = "● " if j.get("auto") else "    "
                a = m.addAction("%s%s   (%s)" % (dot, j.get("name", "?"),
                                                 self._sheet_target_str(j)))
                a.triggered.connect(lambda _=False, v=view, jj=j: self._sheet_go_jump(v, jj))
            m.addSeparator()
        m.addAction("⚙  Manage jumps  (Save / Edit / Delete)…",
                    lambda: self._open_sheet_jumps(view))
        return m

    def _sheet_info(self, view):
        """Return (spreadsheet_id, gid) if this tab is a Google Sheet, else None."""
        try:
            u = view.url()
            if "docs.google.com" not in (u.host() or ""):
                return None
            path = u.path() or ""
            if "/spreadsheets/d/" not in path:
                return None
            sid = path.split("/spreadsheets/d/", 1)[1].split("/", 1)[0]
            gid = "0"
            for part in (u.fragment() or "").split("&"):
                if part.startswith("gid="):
                    gid = part[4:]
            return (sid, gid) if sid else None
        except Exception:
            return None

    def _copy_tab_to_bar(self, view):
        """Add the current tab's URL to the bookmarks bar, duplicates allowed."""
        url = view.url().toString()
        if not url.startswith("http"):
            show_toast(self, "Nothing to bookmark here")
            return
        title = view.title() or url
        self.bookmarks.setdefault("bar", []).append({"title": title, "url": url})
        self._save_bm()
        self.build_bookmarks_bar()
        show_toast(self, "Added to bookmarks bar")

    def _section_header(self, menu, text, bg):
        lbl = QLabel("  " + text)
        lbl.setStyleSheet("background:%s; color:#dce6ff; font-weight:bold;"
                          "font-size:8pt; letter-spacing:1px; padding:4px 10px;" % bg)
        wa = QWidgetAction(menu)
        wa.setDefaultWidget(lbl)
        menu.addAction(wa)

    def _tab_actions_row(self, menu, view, idx):
        """A compact, centred row of general-action icon buttons for the menu."""
        w = QWidget()
        w.setStyleSheet("background:%s;" % self._menu_bg(0))
        lay = QHBoxLayout(w)
        lay.setContentsMargins(6, 4, 6, 4)
        lay.setSpacing(2)
        lay.addStretch(1)

        def add(txt, tip, fn, enabled=True):
            b = QToolButton()
            b.setText(txt)
            b.setToolTip(tip)
            b.setAutoRaise(True)
            b.setEnabled(enabled)
            b.setCursor(Qt.CursorShape.PointingHandCursor)
            b.setStyleSheet("QToolButton{color:#e8edf6; font-size:13pt; padding:3px 8px;"
                            "border:none;}QToolButton:hover{background:%s; border-radius:5px;}"
                            "QToolButton:disabled{color:#55607a;}" % C_BTN_BG_HOV)
            b.clicked.connect(lambda: (menu.close(), fn()))
            lay.addWidget(b)

        add("➕", "New tab", lambda: self.new_tab())
        add("↻", "Reload", lambda: view.reload())
        add("⧉", "Duplicate", lambda: self.add_tab(view.url().toString(), switch=True))
        if getattr(view, "_asleep", False):
            add("☀", "Wake this tab now", lambda: self._wake_tab(view))
        else:
            add("💤", "Sleep this tab now (hibernate to free memory)",
                lambda: self._sleep_tab(view), enabled=view is not self.current_view())
        add("✕", "Close tab", lambda: self.close_tab(self.tabs.indexOf(view)))
        lay.addStretch(1)
        wa = QWidgetAction(menu)
        wa.setDefaultWidget(w)
        return wa

    def _add_behavior_items(self, menu, view, host, domain):
        """The shared toggles - auto-refresh / lock / pin / not-auto-sleep - wired
        to the tab itself (domain=False) or to the domain rule (domain=True)."""
        # Auto-refresh
        a = menu.addAction("🔄  Auto-refresh")
        a.setCheckable(True)
        if domain:
            a.setChecked(bool(self._domain_rule(host, "autorefresh")))
            a.triggered.connect(lambda v: self._set_domain_rule(host, "autorefresh", v))
        else:
            a.setChecked(bool(getattr(view, "_auto_refresh", False)))
            a.triggered.connect(lambda v, w=view: self._set_tab_autorefresh(w, v))
        # Lock (submenu of levels)
        cur_lock = int((self._domain_rule(host, "lock") or 0) if domain else self._lock(view))
        lockm = menu.addMenu("🔒  Lock")
        lockm.setStyleSheet(self._menu_style(1))
        for L, txt in ((0, "Unlocked"), (1, "1: ignore bookmark clicks"),
                       (2, "2: + ignore address bars"),
                       (3, "3: + links open a new tab"),
                       (4, "3+: stay on this domain, others open a new tab")):
            la = lockm.addAction(("● " if L == cur_lock else "    ") + txt)
            if domain:
                la.triggered.connect(lambda _=False, L=L: self._set_domain_rule(host, "lock", L))
            else:
                la.triggered.connect(lambda _=False, w=view, L=L: self._set_tab_lock(w, L))
        # Pin - per TAB only (rev79). A domain used to be able to auto-pin
        # every tab that visited it, which fought the very feature meant to
        # protect a pinned tab: a link click correctly opened a new tab, that
        # new tab correctly landed on the same domain, and the domain rule
        # then pinned it anyway - so every extra tab on the site had to be
        # un-pinned by hand. Pin several tabs of the same site by hand
        # instead; it's the same one click, just never done FOR you.
        if not domain:
            a = menu.addAction("📌  Pin")
            a.setCheckable(True)
            a.setChecked(bool(getattr(view, "_pinned", False)))
            a.triggered.connect(lambda v, w=view: self._toggle_pin(w))
        # Not auto-sleep (rev87). Turned round: idle background tabs sleep on
        # their own, so the box you tick is the EXCEPTION, and it starts empty
        # on every new tab and every new domain.
        a = menu.addAction("☕  Not auto-sleep (keep this one loaded)")
        a.setCheckable(True)
        if domain:
            a.setChecked(bool(self._domain_rule(host, "nosleep")))
            a.triggered.connect(lambda v: self._set_domain_rule(host, "nosleep", v))
        else:
            a.setChecked(bool(getattr(view, "_no_sleep", False)))
            a.triggered.connect(lambda v, w=view: self._set_no_sleep(w, v))
        # Sleep delay for THIS tab / THIS domain (rev88). "Use the general delay"
        # clears it. A number here also lifts the built-in never-sleep list, so
        # it is how you make a chat/video site sleep after all.
        gen = int(self.settings.get("tab_autosleep_min", 15) or 15)
        if domain:
            cur_sm = int(self._domain_rule(host, "sleepmin") or 0)
        else:
            cur_sm = int(getattr(view, "_sleep_min", 0) or 0)
        smm = menu.addMenu("💤  Sleep delay  (%s)"
                           % ("%d min" % cur_sm if cur_sm else "general: %d min" % gen))
        smm.setStyleSheet(self._menu_style(1))
        for m, txt in self.SLEEP_DELAY_CHOICES:
            label = txt if m else "%s (%d min)" % (txt, gen)
            sa = smm.addAction(("● " if m == cur_sm else "    ") + label)
            if domain:
                sa.triggered.connect(
                    lambda _=False, m=m: self._set_domain_rule(host, "sleepmin", m))
            else:
                sa.triggered.connect(
                    lambda _=False, w=view, m=m: self._set_tab_sleepmin(w, m))
        if not domain:
            # The reusable temp tab (DEL 44). Un-ticking it is how you RESCUE a
            # temp page you decided to keep - it is then never written over.
            tt = menu.addAction("🕒  Temp tab (gets reused by 'open in temp')")
            tt.setCheckable(True)
            tt.setChecked(bool(getattr(view, "_is_temp", False)))
            tt.triggered.connect(lambda v, w=view: self._mark_temp(w, v))

    def _protected(self, v):
        """Pinned or locked tabs are never closed by bulk-close actions."""
        return getattr(v, "_pinned", False) or self._lock(v) > 0

    def _rename_tab(self, view, forced=None):
        """One-off name for THIS tab only. It is dropped when the tab navigates
        to a different domain (so a 'Blocket' tab doesn't stay 'Blocket' on
        Amazon). For a name that sticks to a site, use Rename domain instead."""
        if forced is None:
            text, ok = QInputDialog.getText(self, "Rename tab", "Tab name:",
                                            text=getattr(view, "_custom_title", "") or view.title())
            if not ok:
                return
            forced = text.strip()
        view._custom_title = forced or None
        view._custom_title_host = clean_host(view.url().host()) if forced else None
        self._refresh_tab_label(view)

    # ---- saved per-domain / per-page names (auto-applied on every visit) ----
    def _auto_tab_name(self, qurl):
        names = self.settings.get("tab_names", {}) or {}
        u = qurl.toString()
        by_url = names.get("by_url", {})
        if u in by_url:
            return by_url[u]
        host = clean_host(qurl.host())
        return names.get("by_host", {}).get(host) if host else None

    def _rename_domain(self, view, per_page):
        """Save a persistent name for this page's domain (per_page=False) or its
        exact URL (per_page=True). Auto-applied on every future visit + startup."""
        qurl = view.url()
        host = clean_host(qurl.host())
        if not host:
            show_toast(self, "No site to name here")
            return
        key = qurl.toString() if per_page else host
        bucket = "by_url" if per_page else "by_host"
        names = self.settings.setdefault("tab_names", {"by_host": {}, "by_url": {}})
        names.setdefault(bucket, {})
        cur = names[bucket].get(key, "")
        label = "Name for this page" if per_page else "Name for the whole %s domain" % host
        text, ok = QInputDialog.getText(self, "Rename domain", label + ":", text=cur)
        if not ok:
            return
        text = text.strip()
        if text:
            names[bucket][key] = text
        else:
            names[bucket].pop(key, None)            # empty clears it
        save_json(SETTINGS_FILE, self.settings)
        self._relabel_all_tabs()                    # apply to every open matching tab
        show_toast(self, "Saved" if text else "Name cleared")

    def _relabel_all_tabs(self):
        for i in range(self.tabs.count()):
            v = self.tabs.widget(i)
            if v:
                self._refresh_tab_label(v)

    # ---- per-domain tab rules (apply a behaviour to ANY tab on that domain) ----
    def _domain_rule(self, host, key):
        host = clean_host(host)
        return (self.settings.get("domain_tab_rules") or {}).get(host, {}).get(key)

    def _apply_rule_to_view(self, view, key, value):
        if key == "lock":
            try:
                view.page().lock_level = int(value or 0)
            except Exception:
                pass
        elif key == "autorefresh":
            view._auto_refresh = bool(value)
        elif key == "nosleep":
            view._no_sleep = bool(value)
        elif key == "sleepmin":
            # Nothing to store on the view - _sleep_delay_min reads the domain
            # rule live - but the new delay should count from NOW, not from
            # whenever this tab was last looked at.
            view._last_active = time.time()
        # ("pin" used to be settable as a domain rule too - removed in rev79,
        # see _apply_domain_rules; pin is per-TAB only now, so nothing calls
        # this with key=="pin" any more.)
        self._refresh_tab_label(view)

    def _apply_domain_rules(self, view):
        """Apply this host's saved rules to a tab (called when it lands here)."""
        host = clean_host(view.url().host())
        rules = (self.settings.get("domain_tab_rules") or {}).get(host) or {}
        for key, value in rules.items():
            if not value:
                continue
            # Pin is per-TAB only (rev79) - a domain can no longer auto-pin a
            # tab, so ignore any "pin" left over in an old settings.json.
            if key == "pin":
                continue
            self._apply_rule_to_view(view, key, value)
        view._rules_host = host

    def _set_domain_rule(self, host, key, value):
        host = clean_host(host)
        if not host:
            return
        rules = self.settings.setdefault("domain_tab_rules", {})
        d = rules.setdefault(host, {})
        if value in (None, False, 0, ""):
            d.pop(key, None)
            if not d:
                rules.pop(host, None)
        else:
            d[key] = value
        save_json(SETTINGS_FILE, self.settings)
        # Apply (or clear) on every open tab currently on this domain.
        for i in range(self.tabs.count()):
            v = self.tabs.widget(i)
            if v and clean_host(v.url().host()) == host:
                self._apply_rule_to_view(v, key, value if value not in (None, "") else False)
        label = {"autorefresh": "Auto-refresh", "lock": "Lock", "pin": "Pin",
                 "nosleep": "Not auto-sleep", "sleepmin": "Sleep delay"}.get(key, key)
        if key == "sleepmin":
            state = "%d min" % int(value) if value else "the general delay"
        else:
            state = "ON" if value else "OFF"
        show_toast(self, "%s for %s: %s" % (label, host, state))

    def _set_tab_autorefresh(self, view, value):
        view._auto_refresh = bool(value)
        self._mark_tab(view)
        show_toast(self, "Auto-refresh: %s" % ("ON" if value else "OFF"))

    def _set_tab_lock(self, view, level):
        try:
            view.page().lock_level = int(level)
        except Exception:
            return
        self._refresh_tab_label(view)
        names = {0: "unlocked", 1: "level 1", 2: "level 2", 3: "level 3",
                 4: "level 3+ (same domain stays, others open a new tab)"}
        show_toast(self, "Tab %s" % names.get(int(level), level))

    def _pinned_count(self):
        n = 0
        for i in range(self.tabs.count()):
            if getattr(self.tabs.widget(i), "_pinned", False):
                n += 1
        return n

    def _toggle_pin(self, view):
        pinned = not getattr(view, "_pinned", False)
        view._pinned = pinned
        # Pinned tabs keep their page (links open in new tabs). Record the chosen
        # page so we can restore to it, and flag the page for the nav interceptor.
        try:
            view.page().keep_pinned = pinned
        except Exception:
            pass
        if pinned:
            if not getattr(view, "_pin_url", None):
                view._pin_url = view.url().toString()
        else:
            # Forget the pinned page so a later re-pin binds to the NEW page (else
            # the stale _pin_url would make the auto-unpin fire immediately).
            view._pin_url = None
        cur = self.tabs.indexOf(view)
        if pinned:
            # move to the end of the pinned block at the front
            self.tabs.tabBar().moveTab(cur, max(0, self._pinned_count() - 1))
        else:
            # move just after the (now smaller) pinned block
            self.tabs.tabBar().moveTab(cur, self._pinned_count())
        self._refresh_tab_label(view)
        show_toast(self, "Tab pinned" if pinned else "Tab unpinned")

    def _close_others(self, keep):
        for i in range(self.tabs.count() - 1, -1, -1):
            v = self.tabs.widget(i)
            if v is not keep and not self._protected(v):
                self.tabs.removeTab(i)
                v.deleteLater()

    def _close_side(self, idx, side):
        """Close tabs to the left/right of idx (never pinned or locked tabs)."""
        rng = range(idx - 1, -1, -1) if side == "left" \
            else range(self.tabs.count() - 1, idx, -1)
        n = 0
        for i in rng:
            v = self.tabs.widget(i)
            if v and not self._protected(v):
                self.tabs.removeTab(i)
                v.deleteLater()
                n += 1
        show_toast(self, "Closed %d tab(s)" % n)

    def on_tab_changed(self, index):
        view = self.tabs.widget(index)
        if view:
            self._log_activity("tab-activated", view=view)
            url = view.url().toString()
            self.address.setText("" if is_blank_page(url) else url)
            self.address.setCursorPosition(0)
            self._update_nav_buttons(view)
            self.setWindowTitle("{} - {}".format(view.title() or "New Tab", APP_NAME))
            view._last_active = time.time()          # reset this tab's idle clock
            self._update_mute_button()               # reflect this tab's mute state
            self._update_popup_marker()              # 🚫 count is per tab (DEL 21I)
            # The status bar and the reload/stop button belong to whichever tab
            # you are LOOKING at: show this one's loading state and wipe
            # anything left over from another tab.
            if getattr(view, "_is_loading", False):
                self.btn_rel.setText("✕")
                self._show_load_status(view)
                self._load_ticker().start()
            else:
                self.btn_rel.setText("↻")
                self._load_ticker().stop()
                self._clear_load_status()
            if getattr(view, "_notify", False):      # you're looking at it now
                view._notify = False
                self._refresh_tab_label(view)
            if getattr(view, "_asleep", False):
                self._wake_tab(view)                 # waking already reloads it fresh
            elif getattr(view, "_auto_refresh", False) and not is_blank_page(url):
                # Auto-refresh tabs reload the moment you RETURN to them - tab
                # switch or profile switch - if the delay has passed since the
                # last load; never on a background timer while you're sitting on
                # it (that would interrupt reading/scrolling a page you're
                # actively looking at, which is not what "auto-refresh" is for
                # here). Throttled by "Auto-refresh delay" (tab_autorefresh_min)
                # so quick tab-hopping doesn't spam reloads. NOTE: switch_profile
                # calls this method directly after restoring a profile's tabs,
                # because Qt's currentChanged signal does NOT fire when the
                # landing tab's index happens to already be the current one
                # (very common - see switch_profile) - relying on the signal
                # alone silently skipped this check on many profile returns.
                delay_sec = int(self.settings.get("tab_autorefresh_min", 5) or 0) * 60
                lr = getattr(view, "_last_refresh", None)
                if lr is None or (time.time() - lr) >= delay_sec:
                    view.reload()          # on_load_finished stamps _last_refresh when it lands
            else:
                # Returning to a LIVE tab (no reload): some sites (Bandcamp)
                # re-lazy their off-screen covers back to a placeholder when the
                # tab is hidden then shown, so images loaded earlier go blank on
                # tab-switch-and-back. Re-promote them (a no-op on ordinary
                # pages). Reload paths above already re-run this via load-finished.
                self._maybe_eager_images(view)

    # ----------------------------------------------------- navigation ----
    def _nav_do(self, what):
        view = self.current_view()
        if not view:
            return
        if what == "back":
            view.back()
        elif what == "forward":
            # The button is no longer disabled when there is nothing forward
            # (it has a right-click job of its own), so say so instead of
            # doing nothing - and name the right-click while we are here.
            try:
                if not view.history().canGoForward():
                    show_toast(self, "Nothing forward from here \u2014 right-click "
                                     "\u25b6 for a copy of this page in a new tab")
                    return
            except Exception:
                pass
            view.forward()
        elif what == "reload":
            view.reload()

    def _nav_first_page(self):
        """Right-click ◀ : all the way back to the page this tab STARTED on,
        in one step instead of tapping Back a dozen times.

        "First page" means the first REAL one: our own blank new-tab page and
        about:blank are skipped, because landing on an empty page is not going
        back anywhere. What you do land on is whatever opened the tab - the
        bookmark you clicked, the search results you came in through, the front
        page you started from."""
        view = self.current_view()
        if not view:
            return
        try:
            h = view.history()
            items = h.items()
            cur = h.currentItemIndex()
        except Exception:
            return
        target = None
        for i in range(0, max(0, cur)):
            try:
                if not is_blank_page(items[i].url().toString()):
                    target = items[i]
                    break
            except Exception:
                continue
        if target is None:
            show_toast(self, "This is already the first page in this tab")
            return
        try:
            where = pretty_target(target.url().toString())
        except Exception:
            where = ""
        try:
            h.goToItem(target)
        except Exception:
            return
        show_toast(self, "Back to the first page" + (": " + where if where else ""))

    def _nav_duplicate_here(self):
        """Right-click ▶ : a COPY of the page you are on, in a new tab right
        beside this one, and you land in the copy. The point is having both:
        follow a link in the copy and the original is still sitting exactly
        where you left it - which is the other half of what Back is for."""
        view = self.current_view()
        if not view:
            return
        url = view.url().toString()
        if not url or is_blank_page(url):
            show_toast(self, "Nothing to copy \u2014 this tab is empty")
            return
        self.add_tab(url, switch=True, adjacent=True)
        show_toast(self, "Copy of this page opened in a new tab")

    def _lock(self, view):
        try:
            return int(view.page().lock_level)
        except Exception:
            return 0

    def _address_copy_all(self):
        """Select all the address text AND copy it to the clipboard (one click)."""
        self.address.setFocus()
        self.address.selectAll()
        txt = self.address.text()
        if txt:
            QApplication.clipboard().setText(txt)
            show_toast(self, "Address copied")

    def _address_select_all(self):
        """Focus the address bar and select all its text (one-click copy prep)."""
        self.address.setFocus()
        self.address.selectAll()

    def navigate_from_address(self):
        view = self.current_view()
        # Pasting a magnet link into the address bar and pressing Enter is the
        # other half of "I copied a torrent link" (DEL 49).
        if self.handle_torrent_link(self.address.text(), source="the address bar"):
            # Put the address bar back to the page that is actually open, so a
            # magnet link is not left sitting there looking like the address.
            if view:
                u = view.url().toString()
                self.address.setText("" if is_blank_page(u) else u)
                self.address.setCursorPosition(0)
            return
        qurl = self._resolve_typed_url(self.address.text(), self.address)
        # Lock level >= 2: don't change this tab - open in a new one instead.
        if view and self._lock(view) >= 2:
            self.add_tab(qurl.toString(), switch=True)
            return
        if not view:
            view = self.add_tab(None)
        view.setUrl(qurl)
        view.setFocus()

    def navigate_quick(self):
        """Load whatever is typed in the small quick box, then clear it."""
        text = self.quick.text().strip()
        if not text:
            # Empty quick box: fall back to the main address bar.
            self.navigate_from_address()
            return
        if self.handle_torrent_link(text, source="the quick box"):   # DEL 49
            self.quick.clear()
            return
        self._remember_typed(text)          # DEL 45c - the way back
        self.quick._wb_hist_idx = -1
        qurl = self._resolve_typed_url(text, self.quick)
        view = self.current_view()
        if view and self._lock(view) >= 2:      # locked: open in a new tab
            self.add_tab(qurl.toString(), switch=True)
        else:
            view = view or self.add_tab(None, navigate=False)
            view.setUrl(qurl)
            view.setFocus()
        self.quick.clear()                  # always empty for the next address

    def navigate_newtab(self):
        """Open whatever is typed in the 'New tab' box in a brand-new tab."""
        text = self.opentab.text().strip()
        if not text:
            return
        if self.handle_torrent_link(text, source="the new-tab box"):   # DEL 49
            self.opentab.clear()
            return
        self._remember_typed(text)          # DEL 45c - the way back
        self.opentab._wb_hist_idx = -1
        qurl = self._resolve_typed_url(text, self.opentab)
        view = self.add_tab(None, switch=True, navigate=False)
        view.setUrl(qurl)
        self.opentab.clear()                # always empty for the next address
        view.setFocus()

    # ---------------------------------------------------------------- translate ----
    _TRANSLATE_LANGS = [
        ("sv", "Swedish"),  ("en", "English"),  ("de", "German"),
        ("fr", "French"),   ("es", "Spanish"),  ("fi", "Finnish"),
        ("no", "Norwegian"),("da", "Danish"),   ("ar", "Arabic"),
        ("zh-CN", "Chinese (simplified)"), ("ja", "Japanese"), ("ru", "Russian"),
    ]

    def _translate_page(self):
        """Wrap the current page through Google Translate (auto-detect → target lang)."""
        view = self.current_view()
        if not view:
            return
        url = view.url().toString()
        if not url.startswith("http"):
            show_toast(self, "No page to translate")
            return
        tl = self.settings.get("translate_lang", "sv")
        gt = "https://translate.google.com/translate?sl=auto&tl={}&u={}".format(
            tl, urllib.request.quote(url, safe=""))
        self.add_tab(gt, switch=True)

    def _translate_selection(self):
        """Grab the selected text from the page and open Google Translate with it."""
        view = self.current_view()
        if not view:
            return
        tl = self.settings.get("translate_lang", "sv")

        def _got(text):
            text = (text or "").strip()
            if not text:
                show_toast(self, "Select some text on the page first")
                return
            gt = "https://translate.google.com/?sl=auto&tl={}&text={}".format(
                tl, urllib.request.quote(text[:5000], safe=""))
            self.add_tab(gt, switch=True)

        view.page().runJavaScript("window.getSelection().toString()", _got)

    def _show_translate_menu(self):
        """Right-click on the 🌍 Translate button."""
        tl = self.settings.get("translate_lang", "sv")
        tl_name = next((n for c, n in self._TRANSLATE_LANGS if c == tl), tl)
        m = QMenu(self)
        m.setStyleSheet(self._menu_style())
        m.addAction("🌐  Translate this page  (→ %s)" % tl_name, self._translate_page)
        m.addAction("🔤  Translate selected text  (→ %s)" % tl_name,
                    self._translate_selection)
        m.addSeparator()
        lm = m.addMenu("🗣  Target language")
        lm.setStyleSheet(self._menu_style(1))
        for code, name in self._TRANSLATE_LANGS:
            a = lm.addAction(("● " if code == tl else "    ") + name)
            a.triggered.connect(lambda _=False, c=code: self._set_translate_lang(c))
        m.exec(QCursor.pos())

    def _set_translate_lang(self, code):
        self.settings["translate_lang"] = code
        save_json(SETTINGS_FILE, self.settings)
        lang_name = next((n for c, n in self._TRANSLATE_LANGS if c == code), code)
        show_toast(self, "Translate target language set to %s" % lang_name)

    # -----------------------------------------------------------------------
    def go_home(self):
        view = self.current_view() or self.add_tab(None)
        view.setUrl(QUrl(self.settings.get("home_url", DEFAULT_HOME)))

    def focus_address(self):
        self.address.setFocus()
        self.address.selectAll()

    def _build_completer(self):
        """Suggest addresses as you type, from your history + bookmarks +
        saved keyword shortcuts (see _keyword_inline_suggest for the actual
        'b' -> boardgamegeek.com instant completion; this popup list is the
        broader "contains" fallback for anything not typed as an exact
        keyword)."""
        cands = set()
        blocked = self._history_blocked()

        def add_url(u, t=None):
            # A domain you chose to keep out of history is kept out of the
            # suggestions too - INCLUDING its page titles, which are the part
            # that actually embarrasses you in a drop-down.
            if u and blocked and any(self._host_matches(clean_host(u), d)
                                     for d in blocked):
                return
            if u and u.startswith("http"):
                cands.add(u)
                try:
                    cands.add(u.split("://", 1)[1].split("/", 1)[0].replace("www.", ""))
                except Exception:
                    pass
            if t:
                cands.add(t)
        for h in self.history[:2000]:
            add_url(h.get("url"), h.get("title"))
        for n in (bookmark_flatten(self.bookmarks.get("bar", [])) +
                  bookmark_flatten(self.bookmarks.get("menu", []))):
            add_url(n.get("url"), n.get("title"))
        for kw, url in (self.settings.get("address_keywords") or {}).items():
            add_url(url)
        model = sorted(c for c in cands if c and len(c) < 120)
        # Kept, because _gate_suggestions swaps it for an empty one while what
        # you have typed is still too short to mean anything.
        self._completer_list = model
        self._completer_starved = False
        comp = QCompleter(QStringListModel(model, self), self)
        comp.setCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive)
        comp.setFilterMode(Qt.MatchFlag.MatchContains)
        comp.setCompletionMode(QCompleter.CompletionMode.PopupCompletion)
        comp.setMaxVisibleItems(12)
        self._completer = comp
        self.address.setCompleter(comp)
        self.quick.setCompleter(comp)
        self.opentab.setCompleter(comp)

    # ---- address-bar KEYWORD SHORTCUTS (DEL 45): type "b", land on
    # boardgamegeek.com; type "bl", land on blocket.se - a short exact
    # keyword mapped to one site, checked in all three address boxes. ----
    def _resolve_typed_url(self, text, edit=None):
        """Turn typed address-bar text into a QUrl.

        ORDER MATTERS, and this is the order:

          1. A TRAILING DOT means "I mean the domain, not my shortcut".
             "imdb." is imdb.com even when "imdb" is a saved shortcut - the
             deliberate way to reach the plain site, asked for by name.
          2. An exact (trimmed, case-insensitive) keyword shortcut. YOUR
             shortcuts win over the URL-or-search guess, always. It is also
             what makes a fast Enter right after typing "b" work before the
             inline suggestion has visually caught up.
          3. Text that IS the inline completion of a keyword, in the box that
             was completed. The box reads "youtube.com" because you typed "y",
             so the shortcut is still what you meant - and its saved target
             ("https://www.youtube.com/") is not always reachable as the bare
             host. Any edit in that box clears this, so it can never fire on
             something you typed yourself.
          4. Otherwise the usual URL-or-search guess.
        """
        kw = (text or "").strip().lower()
        if kw.endswith(".") and " " not in kw:
            stem = kw.rstrip(".")
            if stem:
                return QUrl("https://" + (stem if "." in stem else stem + ".com"))
        kws = self.settings.get("address_keywords") or {}
        target = kws.get(kw)
        if target:
            return QUrl(target)
        done = getattr(edit, "_wb_kw_done", None) if edit is not None else None
        if done and done[0] == kw and kws.get(done[1]):
            return QUrl(kws[done[1]])
        return normalize_url(text, self.settings.get("search_engine", SEARCH_URL))

    def _keyword_inline_suggest(self, edit, text):
        """As you type in an address box, the instant what you have typed so
        far exactly matches a saved keyword, the target site's host is appended
        and pre-selected - "y" becomes "y|outube.com" (| = selection start), so
        Enter/Tab keeps it and typing straight over the selection replaces it:
        the same feel as a normal browser completing an address from history.

        THE BUG THIS CARRIES A SCAR FROM (rev93). It used to do that for EVERY
        shortcut, using the bare host - and for a shortcut that points anywhere
        deeper than the front page the bare host is a DIFFERENT PLACE. Worse,
        the lie came true: the box now read "imdb.com", so Enter no longer
        matched the keyword "imdb" at all and _resolve_typed_url sent you to
        imdb.com instead of the IMDb search page you saved. Measured in his own
        settings.json, SIX shortcuts were silently downgraded to a front page
        this way - c, p, b, t, v and imdb - because their host happened to
        start with their keyword. So: complete ONLY when the target really is
        the site's front page; for anything deeper leave what you typed exactly
        as typed (the exact-keyword match in _resolve_typed_url takes it from
        there) and put the destination in the status bar instead, where it can
        be read without changing what Enter does."""
        # Any edit invalidates a previous completion (see _resolve_typed_url).
        edit._wb_kw_done = None
        if not text or text != text.strip():
            return                              # mid-word space -> not a keyword
        kw = text.lower()
        target = (self.settings.get("address_keywords") or {}).get(kw)
        if not target:
            return
        if not is_root_target(target):
            try:
                self.status.showMessage(
                    "⌨  %s  →  %s" % (kw, pretty_target(target)[:90]), 4000)
            except Exception:
                pass
            return
        display = clean_host(target)
        if not display or not display.startswith(kw):
            return
        edit.blockSignals(True)
        edit.setText(text + display[len(kw):])
        edit.setSelection(len(text), len(display) - len(kw))
        edit.blockSignals(False)
        # The box now says "youtube.com" where you typed "y". Enter must still
        # resolve the SHORTCUT, not the host it was completed to: the saved
        # target is "https://www.youtube.com/" and the host alone is
        # "youtube.com" - the same place for a site that redirects its apex to
        # www, and a dead end for one that does not.
        edit._wb_kw_done = (display.strip().lower(), kw)

    # ---- WHAT YOU TYPED in the two small boxes (DEL 45c) -------------------
    #
    #  The "New tab" and "This tab" boxes empty themselves on Enter, and that
    #  is deliberate: it is what lets you type the next address without
    #  selecting the old one first. What was missing is the way BACK. The big
    #  address bar keeps the URL you landed on, which is no help when the
    #  thing you want is the QUERY that produced a bad page - by then the bar
    #  reads https://www.google.com/search?q=imdb+passenger and the two words
    #  you actually typed are buried inside it. So a search that came out
    #  slightly wrong had to be retyped from the first letter.
    #
    #  ONE list, shared by BOTH boxes on purpose - they are the same habit and
    #  you should not have to remember which one you used. Newest first, no
    #  duplicates, capped, saved in settings so it survives a restart.
    #
    #  This is NOT the address completer. That popup offers pages you have
    #  VISITED (history + bookmarks), so it can suggest "imdb.com" and never
    #  the words "imdb passenger" - a search that gave a bad page is not a
    #  page you kept. This list is what you TYPED, which is what you want to
    #  edit.
    TYPED_HISTORY_MAX = 60

    def _typed_history(self):
        h = self.settings.get("typed_history")
        return [x for x in h if isinstance(x, str) and x.strip()] \
            if isinstance(h, list) else []

    def _remember_typed(self, text):
        """Called from navigate_quick / navigate_newtab with the RAW text,
        before the box is cleared."""
        t = (text or "").strip()
        if not t:
            return
        hist = [x for x in self._typed_history() if x.strip().lower() != t.lower()]
        hist.insert(0, t)
        del hist[self.TYPED_HISTORY_MAX:]
        self.settings["typed_history"] = hist
        save_json(SETTINGS_FILE, self.settings)

    def _wire_typed_history(self, edit):
        """Give one of the small boxes the arrow-key walk and the right-click
        list. Both boxes call this; both read the same list."""
        edit._wb_hist_idx = -1
        edit._wb_hist_draft = ""
        edit.installEventFilter(self)
        edit.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        edit.customContextMenuRequested.connect(
            lambda p, e=edit: self._small_box_menu(e, p))

    def _small_box_edited(self, edit, text):
        """textEdited on either small box: typing means you have left the
        history walk, so the next Up starts from the top again. Then the
        keyword inline suggestion as before."""
        edit._wb_hist_idx = -1
        edit._wb_hist_draft = text
        self._keyword_inline_suggest(edit, text)
        self._gate_suggestions(edit, text)

    def _address_edited(self, edit, text):
        """textEdited on the big address bar."""
        self._keyword_inline_suggest(edit, text)
        self._gate_suggestions(edit, text)

    def _suggest_min_chars(self):
        try:
            return max(0, min(8, int(self.settings.get("suggest_min_chars", 3))))
        except Exception:
            return 3

    def _gate_suggestions(self, edit, text):
        """No suggestion pop-up until you have typed enough to mean something.

        The completer matches on CONTAINS, so a single letter matches very
        nearly every page you have ever visited: "i" produced a screenful.
        That is useless - and if you would rather not be reminded of what you
        looked at last week, worse than useless.

        TWO things, not one, and deliberately so. QLineEdit drives its own
        completer from the same textEdited signal we are on, and which of the
        two slots runs first is a Qt implementation detail this code has no
        business betting on:

          * the model is STARVED - swapped for an empty one while the text is
            too short. If Qt completes after us it finds nothing to show, and
            nothing is ever painted.
          * the pop-up is HIDDEN as well. If Qt completed before us it is
            already up, and hiding it inside the same event still gets there
            before the paint.

        Either order, no flicker. The swap only happens when the state
        actually changes, so it is two model changes per word, not one per
        keystroke."""
        n = self._suggest_min_chars()
        short = bool(n) and len((text or "").strip()) < n
        c = getattr(self, "_completer", None)
        if c is None:
            return
        try:
            if short != getattr(self, "_completer_starved", False):
                m = c.model()
                if isinstance(m, QStringListModel):
                    m.setStringList([] if short
                                    else getattr(self, "_completer_list", []))
                self._completer_starved = short
            if short and c.popup() is not None and c.popup().isVisible():
                c.popup().hide()
        except Exception as e:
            log_line("suggestion gate: %s" % e)

    def _typed_walk(self, edit, step):
        """Up (step +1) walks back through the shared typed list, Down (-1)
        walks forward. Index -1 is the half-finished line you were on when you
        started walking, kept so that Down past the top hands it straight back
        - a glance at an older search then costs you nothing. The line arrives
        EDITABLE with the cursor at the end, which is the whole point: change
        the one word that was wrong and press Enter."""
        hist = self._typed_history()
        if not hist:
            return False
        idx = getattr(edit, "_wb_hist_idx", -1)
        if idx < 0:
            edit._wb_hist_draft = edit.text()
        idx = max(-1, min(idx + step, len(hist) - 1))
        if idx == getattr(edit, "_wb_hist_idx", -1):
            return True                     # already at an end - eat the key
        edit._wb_hist_idx = idx
        edit._wb_kw_done = None             # this line is not a completion
        new = getattr(edit, "_wb_hist_draft", "") if idx < 0 else hist[idx]
        edit.blockSignals(True)             # no keyword inline-suggest here
        edit.setText(new)
        edit.blockSignals(False)
        edit.setCursorPosition(len(new))
        return True

    def _typed_put(self, edit, text):
        """Picked from the right-click list: put it in the box but do NOT
        navigate, so it can still be edited before Enter."""
        edit.blockSignals(True)
        edit.setText(text)
        edit.blockSignals(False)
        edit._wb_kw_done = None             # picked from the list, not completed
        edit._wb_hist_idx = -1
        edit._wb_hist_draft = text
        edit.setFocus()
        edit.setCursorPosition(len(text))

    def _typed_remove(self, text):
        """Drop ONE line from the shared typed list."""
        t = (text or "").strip().lower()
        hist = [x for x in self._typed_history() if x.strip().lower() != t]
        self.settings["typed_history"] = hist
        save_json(SETTINGS_FILE, self.settings)
        show_toast(self, "Removed from the typed list")

    def _typed_clear(self):
        self.settings["typed_history"] = []
        save_json(SETTINGS_FILE, self.settings)
        show_toast(self, "Typed list cleared")

    def _small_box_menu(self, edit, pos):
        """Right-click on either small box: the shared typed list on top, the
        normal Cut/Copy/Paste underneath (nothing is taken away)."""
        menu = edit.createStandardContextMenu()
        menu.setStyleSheet(self._menu_style(1))
        sub = QMenu("🕘  Recent - both boxes", self)
        sub.setStyleSheet(self._menu_style(2))
        hist = self._typed_history()
        if not hist:
            sub.addAction("Nothing typed yet").setEnabled(False)
        else:
            for t in hist[:20]:
                label = t if len(t) <= 60 else t[:57] + "…"
                row = sub.addMenu(label.replace("&", "&&"))
                row.setStyleSheet(self._menu_style(2))
                row.addAction("↑  Put it in the box",
                              lambda _c=False, s=t, e=edit: self._typed_put(e, s))
                # One line at a time. A search wording that names no site
                # cannot be reached by the per-domain rule, so this is the way
                # to be rid of exactly one thing without clearing the lot.
                row.addAction("🗑  Remove just this one",
                              lambda _c=False, s=t: self._typed_remove(s))
            sub.addSeparator()
            sub.addAction("Clear this list", self._typed_clear)
        first = menu.actions()[0] if menu.actions() else None
        if first is not None:
            menu.insertMenu(first, sub)
            menu.insertSeparator(first)
        else:
            menu.addMenu(sub)
        menu.exec(edit.mapToGlobal(pos))

    def _add_address_keyword(self, view):
        """Prompt for a keyword and bind it to the given tab's current page
        (right-click the address bar -> Add a shortcut for this page)."""
        if not view:
            show_toast(self, "Nothing to save here")
            return
        url = view.url().toString()
        if not url.startswith("http"):
            show_toast(self, "Nothing to save here")
            return
        # The whole first label, not one letter: "imdb", not "i". A three- or
        # four-letter shortcut is the useful kind - long enough to mean
        # something and to be typed without thinking, short enough to be worth
        # having - and a one-letter default quietly pushed every new shortcut
        # into the crowded end of the alphabet.
        default = (clean_host(url).split(".")[0][:8] if clean_host(url) else "")
        kw, ok = QInputDialog.getText(
            self, "Add address shortcut",
            "Type this keyword anywhere you type an address to jump "
            "straight to\n%s" % pretty_target(url), text=default)
        if not ok or not kw.strip():
            return
        kw = kw.strip().lower()
        if " " in kw:
            show_toast(self, "A shortcut can't contain a space")
            return
        existing = (self.settings.get("address_keywords") or {}).get(kw)
        if existing and clean_host(existing) != clean_host(url):
            if QMessageBox.question(
                    self, "Shortcut already used",
                    "\"%s\" already jumps to %s. Point it at %s instead?"
                    % (kw, clean_host(existing), clean_host(url))
                    ) != QMessageBox.StandardButton.Yes:
                return
        self.settings.setdefault("address_keywords", {})[kw] = url
        save_json(SETTINGS_FILE, self.settings)
        self._build_completer()
        show_toast(self, "\"%s\" now jumps to %s" % (kw, clean_host(url)))

    def _del_address_keyword(self, kw):
        kws = self.settings.setdefault("address_keywords", {})
        kws.pop(kw, None)
        save_json(SETTINGS_FILE, self.settings)
        self._build_completer()
        show_toast(self, "Shortcut removed")

    def _rename_address_keyword(self, kw):
        kws = self.settings.get("address_keywords") or {}
        url = kws.get(kw)
        if url is None:
            return
        new_kw, ok = QInputDialog.getText(self, "Change shortcut", "Keyword:", text=kw)
        if not ok or not new_kw.strip():
            return
        new_kw = new_kw.strip().lower()
        if " " in new_kw:
            show_toast(self, "A shortcut can't contain a space")
            return
        if new_kw != kw:
            kws.pop(kw, None)
            kws[new_kw] = url
            save_json(SETTINGS_FILE, self.settings)
            self._build_completer()
            show_toast(self, "Renamed to \"%s\"" % new_kw)

    def _build_address_keywords_menu(self):
        """The saved-shortcuts submenu shown from the address bar's right-click
        menu: every keyword -> its site, plus rename/remove per row."""
        m = QMenu("⌨  Address shortcuts", self)
        m.setStyleSheet(self._menu_style(1))
        kws = sorted((self.settings.get("address_keywords") or {}).items())
        if not kws:
            na = m.addAction("(none saved yet)")
            na.setEnabled(False)
        for kw, url in kws:
            # Show where it REALLY goes. Just the host would hide the whole
            # point of a shortcut that lands on a search page or an inbox -
            # and hiding that is what rev93 had to fix in the first place.
            where = pretty_target(url)
            row = m.addMenu("%s  →  %s"
                            % (kw, where if len(where) <= 52 else where[:49] + "…"))
            row.setStyleSheet(self._menu_style(2))
            row.addAction("✎  Change keyword...",
                          lambda _=False, k=kw: self._rename_address_keyword(k))
            row.addAction("🗑  Remove",
                          lambda _=False, k=kw: self._del_address_keyword(k))
        m.addSeparator()
        m.addAction("➕  Add a shortcut for THIS page...",
                    lambda: self._add_address_keyword(self.current_view()))
        return m

    def _dim_button(self, btn, dim):
        """Grey a button out WITHOUT disabling it (see _css_navbtn)."""
        want = "true" if dim else "false"
        try:
            if btn.property("wbdim") != want:
                btn.setProperty("wbdim", want)
                btn.style().unpolish(btn)
                btn.style().polish(btn)
        except Exception:
            pass

    def _update_nav_buttons(self, view):
        try:
            h = view.history()
            self.btn_back.setEnabled(h.canGoBack())
            # Forward is DIMMED, not disabled: a disabled button receives no
            # mouse events, and its right-click (open a copy of this page in a
            # new tab) has to work on every page, forward history or not.
            self._dim_button(self.btn_fwd, not h.canGoForward())
        except Exception:
            pass

    # ----------------------------------------------------- page signals ----
    def on_url_changed(self, view, url):
        host = clean_host(url.host())
        # NOTE: pinning is strictly PER TAB — a tab stays pinned until YOU unpin
        # it, and nothing here auto-unpins on navigation. A pinned tab is instead
        # prevented from drifting in the first place: the navigation interceptor
        # (acceptNavigationRequest) sends any move to a different document off to
        # a NEW tab, so opening another item/spreadsheet never takes over — nor
        # unpins — the page you pinned. (Previously this auto-unpinned pinned
        # tabs, which wrongly un-pinned e.g. Vinted whenever you opened a new one.)
        # Drop a one-off tab name once we leave the domain it was given on.
        if getattr(view, "_custom_title", None):
            if host and host != getattr(view, "_custom_title_host", None):
                view._custom_title = None
                view._custom_title_host = None
        # Apply this domain's saved tab rules when we arrive on a new domain.
        if host and host != getattr(view, "_rules_host", None):
            self._apply_domain_rules(view)
        if view is self.current_view():
            self._update_popup_marker()             # the policy is per site (DEL 21I)
        self._apply_saved_zoom(view)                 # pick up a saved custom page/domain size
        self._refresh_tab_label(view)               # pick up saved domain/page names
        self._update_identity_tab_flag()            # keep "any Google tab open?" current
        # Google Sheets: switching sheet-tabs only changes the URL fragment (gid).
        # When the gid changes, fire any auto-jump saved for the tab we landed on.
        info = self._sheet_info(view)
        if info and str(info[1]) != str(getattr(view, "_last_sheet_gid", None)):
            view._last_sheet_gid = info[1]
            self._maybe_sheet_autojump(view)
        if view is self.current_view():
            u = url.toString()
            self.address.setText("" if is_blank_page(u) else u)
            self.address.setCursorPosition(0)
            self._update_nav_buttons(view)

    def on_load_started(self, view):
        view._is_loading = True
        self._log_activity("load-start", view=view)
        # Bumped on EVERY load start, anywhere. _maybe_diagnose_failure captures
        # it and re-checks it later, so a load that was merely superseded by the
        # next navigation can never be mistaken for a real failure.
        self._load_seq = getattr(self, "_load_seq", 0) + 1
        view._load_seq = self._load_seq
        view._load_t0 = time.time()
        view._load_pct = 0
        if view is self.current_view():
            self.btn_rel.setText("✕")        # X = stop hint while loading
            self._show_load_status(view)
            self._load_ticker().start()

    def on_load_progress(self, view, p):
        view._load_pct = p
        # A background tab must NEVER write the status bar: it is shared by every
        # tab, and only the tab you are looking at gets its message cleared when
        # it finishes. That is the whole "Loading... 80% that never goes away".
        if view is self.current_view() and 0 < p < 100:
            self._show_load_status(view)

    # ---- one shared "is it still working?" clock for the status bar --------
    def _load_ticker(self):
        t = getattr(self, "_load_tick", None)
        if t is None:
            t = self._load_tick = QTimer(self)
            t.setInterval(1000)
            t.timeout.connect(self._tick_load_status)
        return t

    def _show_load_status(self, view):
        """'Loading... 80%  ·  12s'.

        The percentage alone reads like a stall, because it is nearly always
        the SAME number: Chromium's steps are coarse and it only reports 100
        together with loadFinished, which would flash for a single frame - so
        the last figure ever drawn is the highest step below 100 (usually 80).
        80% never meant 80% done; it meant 'this is where the counter stopped'.
        The seconds are what tell a working page from a stuck one."""
        p = int(getattr(view, "_load_pct", 0) or 0)
        t0 = getattr(view, "_load_t0", None)
        secs = int(time.time() - t0) if t0 else 0
        txt = "Loading... {}%".format(p) if p > 0 else "Loading..."
        if secs >= 3:
            # Only after 3 s, so an ordinary quick load never shows a ticking
            # counter at all - nothing on screen changes that did not need to.
            txt += "  ·  {}s".format(secs)
        if txt != self.status.currentMessage():
            self.status.showMessage(txt)

    def _tick_load_status(self):
        view = self.current_view()
        if view is None or not getattr(view, "_is_loading", False):
            self._load_ticker().stop()
            self._clear_load_status()
            return
        self._show_load_status(view)

    def _clear_load_status(self):
        """Wipe a 'Loading...' message, but leave anything else alone - the
        status bar is also used for saved-file and download messages."""
        try:
            if self.status.currentMessage().startswith("Loading"):
                self.status.clearMessage()
        except Exception:
            pass

    def on_load_finished(self, view, ok):
        view._is_loading = False
        self._log_activity("load-ok" if ok else "LOAD-FAILED", view=view)
        view._load_pct = 100
        if view is self.current_view():
            self.btn_rel.setText("↻")
            self._load_ticker().stop()
            self._clear_load_status()
            self._update_nav_buttons(view)
        if not ok:
            self._maybe_https_fallback(view)
            self._maybe_diagnose_failure(view)
        if ok:
            view._last_refresh = time.time()         # for the auto-refresh delay throttle
            # An http->https upgrade that reached a good load: https works here,
            # so forget the pending http fallback for this host.
            try:
                _h = (view.url().host() or "").lower()
                _b = _h[4:] if _h.startswith("www.") else _h
                (getattr(self, "_https_pending", None) or {}).pop(_b, None)
            except Exception:
                pass
            # A completed load means the tab is AWAKE. An auto-slept (discarded)
            # tab reloads itself when refocused, and that reload fires here — but
            # if the _asleep bookkeeping flag is still set at that instant (a race
            # with on_tab_changed's wake), the eager-images / scroll / find steps
            # below early-return on it and quietly do nothing. THIS is why Bandcamp
            # covers loaded on first open but not after the tab had slept ~10 min.
            # Clearing it here makes any successful load reliably re-run them.
            if getattr(view, "_asleep", False):
                view._asleep = False
                self._refresh_tab_label(view)
            # Every post-load step runs INDEPENDENTLY: one throwing must never
            # skip the rest. THIS is the bug behind "Bandcamp covers stopped
            # loading" — a silent exception in the login chain aborted the whole
            # method before _maybe_eager_images ever ran, so only the ~8 covers
            # already in `src` showed. Now each step is guarded and a failing one
            # is NAMED in the log (Helpfiles/0---Empty) instead of vanishing, and
            # eager-images runs FIRST so nothing upstream can block it again.
            def _step(fn, *a):
                try:
                    fn(*a)
                except Exception as e:
                    log_line("on_load step %s failed: %s"
                             % (getattr(fn, "__name__", fn), e))
            _step(self._record_history, view.url().toString(), view.title())
            if self._crash_has(view.url().host(), "postload"):
                return          # DEL 56: switched off for this site - no post-load JavaScript
            _step(self._maybe_eager_images, view)   # lazy data-src images (Bandcamp) — first, so it can't be blocked
            _step(self._autofill_login, view)       # per-site vault login (if unlocked)
            _step(self._autofill_profile_login, view)  # this profile's single login (DPAPI)
            _step(self._check_pending_login, view)
            _step(self._maybe_restore_scroll, view)  # "go to last position" on opt-in sites
            _step(self._maybe_find_word, view)       # "jump to a word" on opt-in sites
            _step(self._maybe_sheet_autojump, view)  # Sheets: auto-go to saved row on open
            _step(self._maybe_fill_form, view)       # refill remembered form fields
            _step(self._maybe_challenge_help, view)  # stuck on "Verify you are human"?
            _step(self._maybe_auction_clock, view)   # server-checked auction countdown
            _step(self._apply_popupkill, view)       # in-page advert boxes (DEL 21L)
            if getattr(view, "_volume", None) is not None:
                QTimer.singleShot(500, lambda v=view: self._apply_tab_volume(v))
            # Site macros: keep recording across navigations; auto-run if enabled.
            if getattr(self, "_macro_recording", None):
                try:
                    view.page().runJavaScript(MACRO_RECORD_SCRIPT)
                except Exception:
                    pass
            elif view is self.current_view():   # only the ACTIVE tab, never background
                m = self._macro_for(view.url().host())
                if m and m.get("auto") and m.get("steps"):
                    now = time.time()
                    # Per-view + global cooldowns so an auto-macro can't cascade
                    # (e.g. open tab → loads → auto-runs → opens tab → ...).
                    if (now - getattr(view, "_macro_last_run", 0) > 3
                            and now - getattr(self, "_macro_last_run_any", 0) > 1.5):
                        view._macro_last_run = now
                        self._macro_last_run_any = now
                        QTimer.singleShot(600, lambda v=view: self.run_macro(v))

    # ------------------------------------------------- auction clock (DEL 21G) ----
    #  A site's own countdown is drawn with the BROWSER's clock and can be stale,
    #  throttled or simply wrong - which is how a bid goes in at "8 seconds left"
    #  and bounces because the auction had already closed. This injects a second
    #  countdown built from the auction's absolute end time plus a measured
    #  offset to the AUCTION SITE'S OWN server clock, and names the difference.
    def _is_auction_host(self, host):
        h = (host or "").lower().replace("www.", "")
        for d in (self.settings.get("auction_hosts") or []):
            d = (d or "").lower().strip()
            if d and (h == d or h.endswith("." + d)):
                return True
        return False

    def _maybe_auction_clock(self, view):
        """Run the auction clock on auction pages (on by default; per-site
        override 'auction_clock' in site_overrides wins, as everywhere else)."""
        try:
            url = view.url().toString()
            if not url.startswith("http"):
                return
            host = clean_host(view.url().host())
            ov = (self.settings.get("site_overrides") or {}).get(
                (host or "").replace("www.", ""), {})
            on = ov.get("auction_clock")
            if on is None:
                # No explicit choice: run it on the known auction sites only.
                on = bool(self.settings.get("auction_clock", True)) and \
                    self._is_auction_host(host)
            if not on:
                return
            cfg = json.dumps({"margin": int(self.settings.get("auction_margin_s", 20) or 20),
                              "showWithin": int(self.settings.get("auction_show_within_s", 180) or 0),
                              "debug": False})
            js = AUCTION_CLOCK_SCRIPT.replace("__CFG__", cfg)
            # A moment after load, so the page's own data is in the DOM.
            QTimer.singleShot(900, lambda v=view, s=js: self._run_js_safe(v, s))
        except Exception as e:
            log_line("auction clock: %s" % e)

    def _run_js_safe(self, view, js):
        try:
            if view and not getattr(view, "_asleep", False):
                view.page().runJavaScript(js)
        except Exception:
            pass

    def _force_auction_clock(self, view):
        """Run the clock right now on ANY page (useful on an auction site this
        build doesn't know about yet). It quietly does nothing if the page has
        no end time in it."""
        # Manual run: you asked for it, so show it regardless of time left
        # (showWithin=0 = always show), even at "8 days" or after it ended.
        cfg = json.dumps({"margin": int(self.settings.get("auction_margin_s", 20) or 20),
                          "showWithin": 0,
                          "debug": False})
        self._run_js_safe(view, AUCTION_CLOCK_SCRIPT.replace("__CFG__", cfg))
        show_toast(self, "Auction clock: looking for an end time on this page")

    def _toggle_auction_clock_here(self):
        """Turn the auction clock on/off for the CURRENT site (per-host)."""
        v = self.current_view()
        if not v:
            return
        host = (clean_host(v.url().host()) or "").replace("www.", "")
        if not host:
            return
        ov = self.settings.setdefault("site_overrides", {}).setdefault(host, {})
        cur = ov.get("auction_clock")
        if cur is None:
            cur = self._is_auction_host(host) and bool(
                self.settings.get("auction_clock", True))
        ov["auction_clock"] = not cur
        save_json(SETTINGS_FILE, self.settings)
        show_toast(self, "Auction clock on %s: %s"
                   % (host, "ON (reloading)" if ov["auction_clock"] else "OFF"))
        v.reload()

    def _set_auction_margin(self):
        """How many seconds before the hammer the clock should call it too late."""
        cur = int(self.settings.get("auction_margin_s", 20) or 20)
        val, ok = QInputDialog.getInt(
            self, "Auction clock",
            "Stop calling it safe this many seconds before the end.\n"
            "The measured ping to the site is added on top of this.",
            cur, 0, 300, 1)
        if ok:
            self.settings["auction_margin_s"] = int(val)
            save_json(SETTINGS_FILE, self.settings)
            show_toast(self, "Bid margin: %d s" % val)

    # ---------------------------------- scroll-position memory ("last position") ----
    def _restore_scroll_on(self, host):
        if self._crash_has(host, "scroll"):          # DEL 56: switched off for this site
            return False
        host = (host or "").lower().replace("www.", "")
        ov = (self.settings.get("site_overrides") or {}).get(host, {})
        return bool(ov.get("restore_scroll",
                           self.settings.get("restore_scroll", False)))

    def _scroll_capture_tick(self):
        """Snapshot the CURRENT tab's scroll position if its host opted in. Cheap:
        one runJavaScript on the active tab only, every 4 s."""
        v = self.current_view()
        if not v:
            return
        try:
            if getattr(v, "_asleep", False):
                return
            host = v.url().host()
            if not self._restore_scroll_on(host) or self._crash_has(host, "postload"):
                return
            url = v.url().toString()
            if not url.startswith("http"):
                return

            def store(res, url=url):
                if not res:
                    return
                try:
                    self._scroll_pos[url] = json.loads(res)
                    save_json(SCROLL_POS_FILE, self._scroll_pos)
                except Exception:
                    pass
            v.page().runJavaScript(SCROLL_CAPTURE_JS, store)
        except Exception:
            pass

    def _maybe_restore_scroll(self, view):
        """On load, if this host remembers scroll and we have a saved position for
        this URL, restore it (retried a few times for lazy apps like Sheets)."""
        try:
            if not self._restore_scroll_on(view.url().host()):
                return
            pos = self._scroll_pos.get(view.url().toString())
            if not pos:
                return
            js = SCROLL_RESTORE_JS % json.dumps(pos)
            for delay in (400, 1200, 2500):
                QTimer.singleShot(
                    delay, lambda j=js, v=view: self._run_js_safe(v, j))
        except Exception:
            pass

    def _run_js_safe(self, view, js):
        try:
            if view and view.page():
                view.page().runJavaScript(js)
        except Exception:
            pass

    # ---------------------------------- "jump to a word" (per site) ----
    #  A content-based cousin of "Remember scroll position": instead of a pixel
    #  position, a site can remember a WORD/phrase; when a page there opens we
    #  scroll to the first place that word appears (row above / exact / below).
    #  Read-only DOM search — great for normal pages (Google Sheets already has
    #  its own Ctrl+F, so this deliberately leaves the Sheets grid to that).
    def _find_word_for(self, host):
        host = (host or "").lower().replace("www.", "")
        ov = (self.settings.get("site_overrides") or {}).get(host, {})
        w = ov.get("find_word")
        if not w:
            return None, 0
        try:
            off = int(ov.get("find_offset", 0) or 0)
        except Exception:
            off = 0
        return w, off

    def _set_find_word(self, host, word, offset):
        host = clean_host(host) or host
        ov = self.settings.setdefault("site_overrides", {}).setdefault(host, {})
        word = (word or "").strip()
        if word:
            ov["find_word"] = word[:120]
            ov["find_offset"] = int(offset)
        else:
            ov.pop("find_word", None)
            ov.pop("find_offset", None)
        save_json(SETTINGS_FILE, self.settings)
        if word:
            show_toast(self, "Will jump to “%s” on %s" % (word[:30], host))
            v = self.current_view()
            if v and clean_host(v.url().host()) == host:
                self._do_find_word(v, word, int(offset))
        else:
            show_toast(self, "Word-jump cleared for %s" % host)

    def _do_find_word(self, view, word, offset, tries=0):
        if not word:
            return
        try:
            js = FIND_WORD_JS % (json.dumps(word), int(offset))
        except Exception:
            return

        def cb(res, v=view, w=word, o=offset, t=tries):
            # Retry while the page (or a lazy panel) is still filling in.
            if not res and t < 4:
                QTimer.singleShot(
                    900, lambda: self._do_find_word(v, w, o, t + 1))
        try:
            view.page().runJavaScript(js, cb)
        except Exception:
            pass

    def _maybe_find_word(self, view):
        """On load: if this host has a saved word, scroll to it."""
        try:
            if getattr(view, "_asleep", False):
                return
            url = view.url().toString()
            if not url.startswith("http"):
                return
            word, off = self._find_word_for(view.url().host())
            if word:
                self._do_find_word(view, word, off)
        except Exception:
            pass

    def _lazy_images_on(self, host):
        """Per-site-aware 'load lazy images' flag (global default, per-site off)."""
        ov = (self.settings.get("site_overrides") or {}).get(host, {})
        return bool(ov.get("eager_lazy_images",
                           self.settings.get("eager_lazy_images", True)))

    def _maybe_eager_images(self, view):
        """Promote data-src / data-original lazy images to load immediately, so
        covers/thumbnails below the first screen appear without needing the
        site's own scroll-triggered lazy-loader (which our custom scroll can
        miss). Re-run a couple of times for grids that render just after load."""
        try:
            if getattr(view, "_asleep", False):
                return
            url = view.url().toString()
            if not url.startswith("http"):
                return
            if not self._lazy_images_on(clean_host(view.url().host())):
                return
            for delay in (0, 700, 1800):
                QTimer.singleShot(delay, lambda v=view: self._run_eager_images(v))
        except Exception:
            pass

    def _run_eager_images(self, view):
        try:
            if view is not None and view.page():
                host = clean_host(view.url().host())
                # JS returns {p: placeholder->real promotions, f: blank-bitmap
                # re-fetches}. Log ONLY when it actually did something, so
                # ordinary pages (0/0) never spam the log. 'forced' being > 0 on
                # a tab-return is the fingerprint of the discarded-bitmap case.
                def _cb(res, h=host):
                    p = f = 0
                    if isinstance(res, dict):
                        p, f = res.get("p", 0) or 0, res.get("f", 0) or 0
                    if p or f:
                        log_line("eager-images: host=%s promoted=%s forced=%s"
                                 % (h, p, f))
                view.page().runJavaScript(LAZY_IMAGES_JS, _cb)
        except Exception:
            pass

    def _prompt_find_word(self, view, host):
        """Ask for the word + where to land (row above / exact / below)."""
        host = clean_host(host) or host
        cur_word, cur_off = self._find_word_for(host)
        word, ok = QInputDialog.getText(
            self, "Jump to a word",
            "When a page on '%s' opens, scroll to the FIRST place this "
            "word or phrase appears.\nLeave it empty to turn this off." % host,
            text=cur_word or "")
        if not ok:
            return
        word = word.strip()
        if not word:
            self._set_find_word(host, "", 0)
            return
        choices = ["Row ABOVE the word", "EXACTLY that row", "Row BELOW the word"]
        cur_idx = {-1: 0, 0: 1, 1: 2}.get(int(cur_off), 1)
        pick, ok2 = QInputDialog.getItem(
            self, "Where to land", "Land on:", choices, cur_idx, False)
        if not ok2:
            return
        off = {0: -1, 1: 0, 2: 1}[choices.index(pick)]
        self._set_find_word(host, word, off)

    # ---------------------------------- form-field memory ("remember & refill") ----
    def _form_capture_tick(self):
        """Periodic snapshot of the current tab. Each part has its OWN setting:
        form-field memory (only if AUTO-remember is on), message drafts, and the
        Google Sheets last-active-cell — so drafts/Sheets work even with AUTO off."""
        v = self.current_view()
        if not v or getattr(v, "_asleep", False):
            return
        if not v.url().toString().startswith("http"):
            return
        if self.settings.get("form_memory", False):
            self._form_capture_fields(v)
        self._draft_capture(v)          # message-draft safety net (own setting)
        self._sheet_capture_lastcell(v)  # Sheets last cell (own setting)

    def _form_capture_fields(self, v):
        try:
            host = clean_host(v.url().host())
            if not host:
                return

            def store(res, host=host):
                if not res:
                    return
                try:
                    data = json.loads(res)
                except Exception:
                    return
                if not isinstance(data, dict) or not data:
                    return
                cur = dict(self._form_mem.get(host, {}))
                before = dict(cur)
                cur.update(data)
                # Cap per-host keys so it can't grow without bound.
                if len(cur) > 60:
                    cur = dict(list(cur.items())[-60:])
                if cur == before:
                    return                       # nothing changed -> no disk write
                self._form_mem[host] = cur
                save_json(FORM_MEMORY_FILE, self._form_mem)
            v.page().runJavaScript(FORM_CAPTURE_JS, store)
        except Exception:
            pass

    # ---------------------------------- message-draft live-save (7-day) ----
    def _draft_capture(self, view):
        if not self.settings.get("draft_save", True):
            return
        try:
            url = view.url().toString()
            if not url.startswith("http"):
                return
            host = clean_host(view.url().host())
            title = view.title() or host

            def store(res, url=url, host=host, title=title):
                if not res:
                    return
                try:
                    items = json.loads(res)
                except Exception:
                    return
                if not items:
                    return
                now = time.time()
                changed = False
                for it in items:
                    field = it.get("k", "")
                    text = (it.get("t") or "").strip()
                    if len(text) < 2:
                        continue
                    # Update the existing draft for this url+field, else add one.
                    hit = next((d for d in self._drafts
                                if d.get("url") == url and d.get("field") == field), None)
                    if hit:
                        if hit.get("text") != text:
                            hit["text"] = text
                            hit["ts"] = now
                            changed = True
                    else:
                        self._drafts.append({"ts": now, "host": host, "url": url,
                                             "title": title, "field": field, "text": text})
                        changed = True
                if changed:
                    self._purge_old_drafts()
                    if len(self._drafts) > 300:
                        self._drafts = self._drafts[-300:]
                    save_json(DRAFTS_FILE, self._drafts)
            view.page().runJavaScript(DRAFT_CAPTURE_JS, store)
        except Exception:
            pass

    def _purge_old_drafts(self):
        cutoff = time.time() - 7 * 24 * 3600
        n = len(self._drafts)
        self._drafts = [d for d in self._drafts if d.get("ts", 0) >= cutoff]
        if len(self._drafts) != n:
            try:
                save_json(DRAFTS_FILE, self._drafts)
            except Exception:
                pass

    def show_drafts(self):
        DraftsDialog(self).exec()

    def _maybe_fill_form(self, view):
        """On load, refill remembered field values (empty fields only). Fills BOTH
        auto-captured and manually-saved entries — so manual 'remember this field'
        works even when AUTO-remember is off."""
        try:
            host = clean_host(view.url().host())
            data = self._form_mem.get(host)
            if not data:
                return
            js = FORM_FILL_JS % json.dumps(data)
            for delay in (500, 1500):
                QTimer.singleShot(delay, lambda j=js, v=view: self._run_js_safe(v, j))
        except Exception:
            pass

    def _clear_form_memory(self):
        self._form_mem = {}
        save_json(FORM_MEMORY_FILE, self._form_mem)
        show_toast(self, "Saved form data cleared")

    def _remember_field(self, view):
        """Manually save the value of the field the user just right-clicked (the
        focused/active field) for THIS site, so it auto-fills next time. This is the
        opt-in alternative to AUTO-remember (which over-remembered search/Vinted)."""
        host = clean_host(view.url().host())
        if not host:
            return
        js = ("(function(){try{var el=document.activeElement;"
              "if(!el||!('value' in el))return null;"
              "var k=el.name||el.id||el.getAttribute('placeholder');"
              "if(!k)return null;return JSON.stringify({k:k,v:(el.value||'')});"
              "}catch(e){return null;}})();")

        def cb(res, host=host):
            if not res:
                show_toast(self, "Click into a field first, then use this")
                return
            try:
                d = json.loads(res)
            except Exception:
                return
            if not d or not d.get("k") or d.get("v", "") == "":
                show_toast(self, "That field is empty — nothing to remember")
                return
            self._form_mem.setdefault(host, {})[d["k"]] = d["v"]
            save_json(FORM_MEMORY_FILE, self._form_mem)
            show_toast(self, "Field remembered for %s 💾" % host)
        view.page().runJavaScript(js, cb)

    def _cp_click(self):
        """CP button: manual copy/paste memory for ONE field at a time (see
        tool_btn tooltip for the 3-step flow). Independent of AUTO-remember -
        works even with that setting off, and even on fields the automatic
        form-field memory can't see (no name/id/placeholder, living inside a
        shadow DOM, or inside a same-page-embedded iframe like a payment
        widget - Swish-number fields on checkout pages, for example) because
        it always targets whatever field currently has focus (via the
        FIELD_FOCUS_TRACKER_JS cross-frame relay) instead of scanning the
        whole page."""
        view = self.current_view()
        if not view:
            return
        host = clean_host(view.url().host())
        if not host:
            return

        def cb(res, view=view, host=host):
            d = None
            if res:
                try:
                    d = json.loads(res)
                except Exception:
                    d = None
            if not d or not d.get("k"):
                QMessageBox.information(
                    self, "CP - Copy/Paste field",
                    "Click into the field you want to remember first, then click CP.")
                return
            key = d["k"]
            cur_val = d.get("v", "")
            frame = d.get("frame")   # non-null when the field lives inside an iframe
            saved = self._form_mem.get(host, {})
            if saved.get(key):
                fill_js = CP_FILL_JS_TMPL % (
                    json.dumps(key), json.dumps(saved[key]), json.dumps(frame))

                def fill_cb(ok, view=view, frame=frame):
                    if not ok:
                        show_toast(self, "Couldn't paste - click into the field first")
                        return
                    if not frame:
                        show_toast(self, "Pasted saved value ✅")
                        return
                    # Iframe case: the fill was only requested (broadcast via
                    # postMessage), not confirmed yet - check the ack flag a
                    # beat later so we never claim success we didn't see.
                    def check_ack(ack):
                        if ack:
                            show_toast(self, "Pasted saved value ✅")
                        else:
                            show_toast(self, "Couldn't confirm the paste - click "
                                             "into the field again and retry")
                    def _ask_ack(view=view, check_ack=check_ack):
                        try:
                            if view and view.page():
                                view.page().runJavaScript(
                                    "window.__wbFillAck === true", check_ack)
                        except Exception:
                            pass
                    QTimer.singleShot(250, _ask_ack)
                view.page().runJavaScript(fill_js, fill_cb)
            elif cur_val:
                self._form_mem.setdefault(host, {})[key] = cur_val
                save_json(FORM_MEMORY_FILE, self._form_mem)
                show_toast(self, "Saved for %s 💾 — next time: click the field, then CP" % host)
            else:
                QMessageBox.information(
                    self, "CP - Copy/Paste field",
                    "Nothing saved for this field yet.\n\n"
                    "Type the value into the field, then click CP again to save it.")
        view.page().runJavaScript(CP_PROBE_JS, cb)

    def _forget_site_fields(self, host):
        host = clean_host(host)
        if host in self._form_mem:
            self._form_mem.pop(host, None)
            save_json(FORM_MEMORY_FILE, self._form_mem)
            show_toast(self, "Forgot saved fields for %s" % host)

    def _refresh_tab_label(self, view):
        idx = self.tabs.indexOf(view)
        if idx < 0:
            return
        # Title precedence: a one-off "rename tab" > a saved domain/page name >
        # the page's own title.
        custom = getattr(view, "_custom_title", None)
        title = custom or self._auto_tab_name(view.url()) or view.title() or "New Tab"
        # Optionally show only the first word of a PAGE title (not custom names),
        # e.g. "Vinted - köp, sälj..." -> "Vinted". Great for narrow side tabs.
        if not custom and self.settings.get("tab_first_word_only"):
            first = title.strip().split()
            if first:
                title = first[0]
        short = (title[:24] + "...") if len(title) > 26 else title
        # Container tabs (separate logins) get their container name in front, so
        # two accounts of the same site are easy to tell apart on the strip.
        cid = getattr(view, "_container", None)
        if cid:
            short = "[%s] %s" % (self._container_name(cid)[:10], short)
        # ONE coloured dot whose colour encodes WHICH functions are active (see
        # COMBO_COLORS), drawn onto the favicon. As text prefixes we keep only the
        # states a glyph-less marker can't show: 🔴 new messages, 💤 asleep. A LOCK
        # is shown by colouring the vertical-tab ✕ red instead (saves tab width).
        mark = ""
        if getattr(view, "_is_temp", False):
            mark += "🕒"                 # the reusable temp tab (DEL 44)
        if getattr(view, "_notify", False):
            mark += "🔴"
        if getattr(view, "_asleep", False):
            mark += "💤"
        if mark:
            mark += " "
        self.tabs.setTabText(idx, mark + (short or "New Tab"))
        self._compose_tab_icon(view)
        # Names of the active functions live in the tooltip.
        flags = []
        if cid:
            flags.append("Container: %s 🫙" % self._container_name(cid))
        if getattr(view, "_is_temp", False):
            flags.append("Temp tab 🕒 (reused for the next 'open in temp')")
        if getattr(view, "_pinned", False):
            flags.append("Pinned")
        lv = self._lock(view)
        if lv:
            flags.append("Lock %d" % lv)
        if getattr(view, "_auto_refresh", False):
            flags.append("Auto-refresh")
        if getattr(view, "_no_sleep", False):
            flags.append("Not auto-sleep ☕")
        if getattr(view, "_asleep", False):
            flags.append("Asleep 💤")
        if getattr(view, "_notify", False):
            flags.append("New messages 🔴")
        tip = view.url().toString()
        if flags:
            tip += "\n• " + ", ".join(flags)
        self.tabs.setTabToolTip(idx, tip)

    # ONE dot, colour = the combination of active functions. Codes (fixed order):
    # P=pinned, L=locked, R=auto-refresh, S=NOT auto-sleep (rev87: the letter
    # kept its place, its meaning turned round with the feature). Edit any
    # colour freely; an unknown combination falls back to grey.
    COMBO_COLORS = {
        "P":    "#3b82f6",   # pin                        - blue
        "L":    "#ef4444",   # lock                       - red
        "R":    "#22c55e",   # auto-refresh               - green
        "S":    "#a855f7",   # not auto-sleep             - purple
        "PL":   "#f97316",   # pin + lock                 - orange
        "PR":   "#06b6d4",   # pin + refresh              - cyan
        "PS":   "#14b8a6",   # pin + nosleep              - teal
        "LR":   "#eab308",   # lock + refresh             - amber
        "LS":   "#ec4899",   # lock + nosleep             - pink
        "RS":   "#84cc16",   # refresh + nosleep          - lime
        "PLR":  "#d946ef",   # pin + lock + refresh       - magenta
        "PLS":  "#7c3aed",   # pin + lock + nosleep       - violet
        "PRS":  "#0ea5e9",   # pin + refresh + nosleep    - sky
        "LRS":  "#f43f5e",   # lock + refresh + nosleep   - rose
        "PLRS": "#ffffff",   # all four                   - white
    }

    def _combo_key(self, view):
        key = ""
        if getattr(view, "_pinned", False):
            key += "P"
        if self._lock(view) > 0:
            key += "L"
        if getattr(view, "_auto_refresh", False):
            key += "R"
        if getattr(view, "_no_sleep", False):
            key += "S"
        return key

    def _compose_tab_icon(self, view):
        """Draw the favicon with one corner dot coloured for this tab's active
        function combination (no functions = just the favicon)."""
        idx = self.tabs.indexOf(view)
        if idx < 0:
            return
        key = self._combo_key(view)
        base = getattr(view, "_favicon", None)
        if not key:
            self.tabs.setTabIcon(idx, base if (base and not base.isNull()) else QIcon())
            return
        color = self.COMBO_COLORS.get(key, "#9aa6bf")     # grey for any odd combo
        S, d = 32, 17
        pm = QPixmap(S, S)
        pm.fill(Qt.GlobalColor.transparent)
        p = QPainter(pm)
        p.setRenderHint(QPainter.RenderHint.Antialiasing)
        if base and not base.isNull():
            p.drawPixmap(0, 0, base.pixmap(S, S))
        p.setPen(Qt.PenStyle.NoPen)
        p.setBrush(QColor("#11151f"))                     # dark halo for contrast
        p.drawEllipse(S - d - 1, S - d - 1, d + 1, d + 1)
        p.setBrush(QColor(color))
        p.drawEllipse(S - d, S - d, d, d)
        p.end()
        self.tabs.setTabIcon(idx, QIcon(pm))

    def _mark_tab(self, view):
        self._refresh_tab_label(view)

    def on_title_changed(self, view, title):
        if title and title.startswith("WBZAP::"):     # the element zapper reported a hit
            self._zap_add(view, title[7:])
            return
        if title and title.startswith("WBKILL::"):     # pop-up killer picked a box
            self._popupkill_picked(view, title[8:])
            return
        if title and title.startswith("WBCLICK::"):    # "remember a choice" picked a button
            self._autoclick_picked(view, title[9:])
            return
        if title and title.startswith("WBSTICK::"):    # the sticky picker reported a hit
            self._sticky_add(view, title[9:])
            return
        if title and title.startswith("WBFREEZE::"):   # the movement freezer reported a hit
            self._freezeel_add(view, title[10:])
            return
        if title and title.startswith("WBUNHIDE::"):   # un-hide one specific element
            self._unhide_one(view, title[10:])
            return
        idx = self.tabs.indexOf(view)
        if idx >= 0:
            # Messaging notification: a background tab whose title gains an unread
            # count like "(3) WhatsApp" lights a 🔴 marker until you switch to it
            # (cleared in on_tab_changed). Great for WhatsApp/Messenger profiles.
            if view is not self.current_view() and _title_has_unread_count(title):
                view._notify = True
            self._refresh_tab_label(view)
        else:
            # idx < 0 = a kept-alive tab belonging to ANOTHER profile (not in the
            # current strip). If that profile is a Messaging profile and the title
            # shows an unread count, pop a notification beside the main window.
            if _title_has_unread_count(title):
                self._maybe_cross_profile_notify(view, title)
        if view is self.current_view():
            self.setWindowTitle("{} - {}".format(title or "New Tab", APP_NAME))

    # ------------------------------------------- cross-profile message popups ----
    def _maybe_cross_profile_notify(self, view, title):
        """A kept-alive tab in ANOTHER (Messaging) profile gained an unread count.
        Pop a notification beside the window so you see it without switching there."""
        try:
            pid = getattr(view, "_pid", None)
            if not pid or pid == self.active_id:
                return
            prof = self._profile_by_id(pid)
            if not prof or not prof.get("messaging"):
                return
            if getattr(view, "_last_msg_title", None) == title:
                return                       # same count as last time, don't repeat
            view._last_msg_title = title
            self._show_message_popup(
                "💬  %s\n%s" % (prof.get("name", pid), title), pid, view)
        except Exception:
            pass

    def _show_message_popup(self, text, pid, view):
        if not hasattr(self, "_msg_popups"):
            self._msg_popups = []
        self._msg_popups = [p for p in self._msg_popups if p and p.isVisible()]

        def go(pid=pid, view=view):
            self.switch_profile(pid)
            i = self.tabs.indexOf(view)
            if i >= 0:
                self.tabs.setCurrentIndex(i)
            self.raise_()
            self.activateWindow()

        pop = MessagePopup(text, go)
        geo = self.frameGeometry()
        x = geo.right() - pop.width() - 24
        y = geo.top() + 70 + len(self._msg_popups) * 78
        pop.move(max(0, x), max(0, y))
        pop.show()
        self._msg_popups.append(pop)

    # ----------------------------------------------------- element zapper ----
    def enter_zap_mode(self, view=None):
        view = view or self.current_view()
        if view:
            view.page().runJavaScript(ZAP_SCRIPT)
            show_toast(self, "Click an element to hide it (Esc cancels)")

    def enter_sticky_mode(self, view=None):
        view = view or self.current_view()
        if view:
            view.page().runJavaScript(STICKY_SCRIPT)
            show_toast(self, "Click a section to freeze it at the top (Esc cancels)")

    def _sticky_add(self, view, selector):
        host = view.url().host().replace("www.", "")
        try:
            view.page().runJavaScript("try{document.title=window.__wbOrigTitle||document.title;}catch(e){}")
        except Exception:
            pass
        selector = (selector or "").strip()
        if not host or not selector:
            return
        rules = self.settings.setdefault("sticky_rules", [])
        if not any(r.get("domain") == host and r.get("selector") == selector for r in rules):
            rules.append({"domain": host, "selector": selector})
            save_json(SETTINGS_FILE, self.settings)
            self._apply_privacy()
        show_toast(self, "Section frozen to top on %s" % host)

    def _sticky_clear(self, host):
        rules = self.settings.get("sticky_rules", [])
        self.settings["sticky_rules"] = [r for r in rules if r.get("domain") != host]
        save_json(SETTINGS_FILE, self.settings)
        self._apply_privacy()
        self._refresh_current()
        show_toast(self, "Un-froze sections on %s" % host)

    # ---- per-element movement freezer (click one moving thing to stop it) ----
    def enter_freezeel_mode(self, view=None):
        view = view or self.current_view()
        if view:
            view.page().runJavaScript(FREEZE_PICK_SCRIPT)
            show_toast(self, "Click a moving element to stop it (Esc cancels)")

    def _freezeel_add(self, view, selector):
        host = view.url().host().replace("www.", "")
        try:
            view.page().runJavaScript("try{document.title=window.__wbOrigTitle||document.title;}catch(e){}")
        except Exception:
            pass
        selector = (selector or "").strip()
        if not host or not selector:
            return
        rules = self.settings.setdefault("freeze_rules", [])
        if not any(r.get("domain") == host and r.get("selector") == selector for r in rules):
            rules.append({"domain": host, "selector": selector})
            save_json(SETTINGS_FILE, self.settings)
            self._apply_privacy()                # persist: re-freezes on every reload
        show_toast(self, "Element movement stopped on %s" % host)

    def _freezeel_clear(self, host):
        rules = self.settings.get("freeze_rules", [])
        self.settings["freeze_rules"] = [r for r in rules if r.get("domain") != host]
        save_json(SETTINGS_FILE, self.settings)
        self._apply_privacy()
        self._refresh_current()
        show_toast(self, "Re-enabled element movement on %s" % host)

    # ---- Site macros: record DOM actions on a site and replay them ----
    def _macro_for(self, host):
        return (self.settings.get("site_macros") or {}).get(clean_host(host))

    def start_macro_record(self, view=None):
        view = view or self.current_view()
        if not view:
            return
        self._macro_recording = clean_host(view.url().host())
        try:
            view.page().runJavaScript("try{sessionStorage.removeItem('__wb_macro');}catch(e){}")
            view.page().runJavaScript(MACRO_RECORD_SCRIPT)
        except Exception:
            pass
        show_toast(self, "Recording on %s — a red ● REC badge shows the count; "
                   "right-click → Site macro → Stop when done" % self._macro_recording)

    def stop_macro_record(self):
        host = getattr(self, "_macro_recording", None)
        if not host:
            return
        self._macro_recording = None
        v = self.current_view()
        if not v:
            return
        # Pull the recorded steps out of the page's sessionStorage, then clean up.
        js = ("(function(){try{var a=sessionStorage.getItem('__wb_macro')||'[]';"
              "sessionStorage.removeItem('__wb_macro');window.__wbRec=false;"
              "var b=document.getElementById('__wbRecBadge'); if(b)b.remove();"
              "return a;}catch(e){return '[]';}})()")
        try:
            v.page().runJavaScript(js, lambda res, h=host: self._macro_save(h, res))
        except Exception:
            pass

    def _macro_save(self, host, res):
        try:
            steps = json.loads(res or "[]")
        except Exception:
            steps = []
        if not steps:
            show_toast(self, "Macro: nothing was recorded")
            return
        macros = self.settings.setdefault("site_macros", {})
        prev = macros.get(host, {})
        macros[host] = {"steps": steps, "auto": bool(prev.get("auto", False))}
        save_json(SETTINGS_FILE, self.settings)
        show_toast(self, "Macro saved for %s (%d steps)" % (host, len(steps)))

    def run_macro(self, view=None):
        view = view or self.current_view()
        if not view:
            return
        m = self._macro_for(view.url().host())
        if not m or not m.get("steps"):
            show_toast(self, "No macro recorded for this site")
            return
        js = MACRO_PLAY_SCRIPT.replace("__STEPS__", json.dumps(m["steps"]))
        try:
            view.page().runJavaScript(js)
            show_toast(self, "Running macro (%d steps)…" % len(m["steps"]))
        except Exception:
            pass

    def _toggle_macro_auto(self, host):
        host = clean_host(host)
        m = (self.settings.get("site_macros") or {}).get(host)
        if not m:
            return
        m["auto"] = not m.get("auto", False)
        save_json(SETTINGS_FILE, self.settings)
        show_toast(self, "Auto-run macro on %s: %s" % (host, "ON" if m["auto"] else "OFF"))

    def _clear_macro(self, host):
        host = clean_host(host)
        (self.settings.get("site_macros") or {}).pop(host, None)
        save_json(SETTINGS_FILE, self.settings)
        show_toast(self, "Macro cleared for %s" % host)

    def _macro_help(self):
        QMessageBox.information(
            self, "Site macro — experimental",
            "Site macros are in their infancy.\n\n"
            "• They record MOUSE actions (clicks, dropdown/filter choices) and Enter, as "
            "page elements — not screen positions — so window size doesn't matter.\n"
            "• They replay best for actions that stay on the SAME page (pick a sort, tick "
            "a filter, click a button). A 'red ● REC' badge shows the step count while "
            "recording.\n"
            "• They do NOT reliably cross a page load (e.g. typing a search + Enter that "
            "loads a results page), and very dynamic sites can shift between visits.\n\n"
            "Tip: for things like 'search then sort', record ONLY the sort on the results "
            "page and turn on Auto-run — or use 🔗 Quick links to save the finished page "
            "(e.g. a search URL) and jump straight to it.")

    # ---- Per-site quick links (saved sub-pages: search URLs etc.) ----
    def _quicklinks_for(self, host):
        return (self.settings.get("site_quicklinks") or {}).get(clean_host(host), [])

    def _open_quicklink(self, url):
        """Open a saved sub-page in a NEW tab next to the current one, keeping the
        original page open. Marked EPHEMERAL: never saved for session restore, so
        these sub-tabs always close on restart and never auto-start."""
        v = self.add_tab(url, switch=True, adjacent=True)
        if v is not None:
            v._ephemeral = True
        return v

    def _add_quicklink(self, view):
        if not view:
            return
        url = view.url().toString()
        host = clean_host(view.url().host())
        if not host or not url.startswith("http"):
            show_toast(self, "Nothing to save here")
            return
        default = view.title() or url[:40]
        name, ok = QInputDialog.getText(self, "Save quick link",
                                        "Name for this page (under %s):" % host, text=default)
        if not ok or not name.strip():
            return
        links = self.settings.setdefault("site_quicklinks", {}).setdefault(host, [])
        links[:] = [l for l in links if l.get("url") != url]      # replace dup
        links.append({"name": name.strip(), "url": url})
        save_json(SETTINGS_FILE, self.settings)
        show_toast(self, "Saved “%s” under %s" % (name.strip(), host))

    def _del_quicklink(self, host, url):
        host = clean_host(host)
        ql = self.settings.setdefault("site_quicklinks", {})
        ql[host] = [l for l in ql.get(host, []) if l.get("url") != url]
        if not ql[host]:
            ql.pop(host, None)
        save_json(SETTINGS_FILE, self.settings)
        show_toast(self, "Quick link removed")

    def _build_quicklinks_menu(self, view):
        """Menu of a tab's saved sub-pages (open here) + save/manage. Reused by
        the tab right-click and the tab hover."""
        host = clean_host(view.url().host()) if view else ""
        m = QMenu(self)
        m.setStyleSheet(self._menu_style())
        hdr = m.addAction("🔗  Quick links · %s" % (host or "—"))
        hdr.setEnabled(False)
        m.addSeparator()
        links = self._quicklinks_for(host)
        for l in links:
            a = m.addAction(l.get("name") or l.get("url", "")[:40])
            a.setToolTip(l.get("url", ""))
            a.triggered.connect(lambda _=False, u=l.get("url"): self._open_quicklink(u))
        if not links:
            na = m.addAction("(none saved yet)")
            na.setEnabled(False)
        m.addSeparator()
        m.addAction("➕  Save this page as a quick link...", lambda: self._add_quicklink(view))
        if links:
            rn = m.addMenu("✎  Rename")
            rn.setStyleSheet(self._menu_style(1))
            up = m.addMenu("⬆  Move up")
            up.setStyleSheet(self._menu_style(1))
            dl = m.addMenu("🗑  Remove")
            dl.setStyleSheet(self._menu_style(1))
            for j, l in enumerate(links):
                lbl = l.get("name") or l.get("url", "")[:30]
                rn.addAction(lbl, lambda _=False, h=host, u=l.get("url"):
                             self._rename_quicklink(h, u))
                a_up = up.addAction(lbl, lambda _=False, h=host, u=l.get("url"):
                                    self._move_quicklink(h, u, -1))
                a_up.setEnabled(j > 0)
                dl.addAction(lbl, lambda _=False, h=host, u=l.get("url"):
                             self._del_quicklink(h, u))
        return m

    def _rename_quicklink(self, host, url):
        host = clean_host(host)
        links = (self.settings.get("site_quicklinks") or {}).get(host, [])
        l = next((x for x in links if x.get("url") == url), None)
        if not l:
            return
        name, ok = QInputDialog.getText(self, "Rename quick link", "Name:",
                                        text=l.get("name", ""))
        if ok and name.strip():
            l["name"] = name.strip()
            save_json(SETTINGS_FILE, self.settings)
            show_toast(self, "Renamed")

    def _move_quicklink(self, host, url, delta):
        host = clean_host(host)
        links = (self.settings.get("site_quicklinks") or {}).get(host, [])
        i = next((k for k, x in enumerate(links) if x.get("url") == url), -1)
        j = i + delta
        if i >= 0 and 0 <= j < len(links):
            links[i], links[j] = links[j], links[i]
            save_json(SETTINGS_FILE, self.settings)
            show_toast(self, "Reordered")

    def _zap_clear(self, host):
        rules = self.settings.get("element_hide_rules", [])
        # keep the built-in wildcard / default rules, drop this host's zapped ones
        self.settings["element_hide_rules"] = [r for r in rules if r.get("domain") != host]
        save_json(SETTINGS_FILE, self.settings)
        self._apply_privacy()
        self._refresh_current()
        show_toast(self, "Un-hid elements on %s" % host)

    def enter_unhide_mode(self, view=None):
        view = view or self.current_view()
        if not view:
            return
        host = view.url().host().replace("www.", "")
        sels = [r.get("selector") for r in self.settings.get("element_hide_rules", [])
                if r.get("domain") == host and r.get("selector")]
        if not sels:
            show_toast(self, "Nothing hidden on this site")
            return
        view.page().runJavaScript(UNHIDE_SCRIPT.replace("__SELS__", json.dumps(sels)))

    def _unhide_one(self, view, selector):
        host = view.url().host().replace("www.", "")
        try:
            view.page().runJavaScript("try{document.title=window.__wbOrigTitle||document.title;}catch(e){}")
        except Exception:
            pass
        rules = self.settings.get("element_hide_rules", [])
        self.settings["element_hide_rules"] = [
            r for r in rules if not (r.get("domain") == host and r.get("selector") == selector)]
        save_json(SETTINGS_FILE, self.settings)
        self._apply_privacy()
        view.reload()                      # show the result: only that one returns
        show_toast(self, "Un-hid one element on %s" % host)

    def _zap_add(self, view, selector):
        host = view.url().host().replace("www.", "")
        # restore the page title the zapper temporarily overwrote
        try:
            view.page().runJavaScript("try{document.title=window.__wbOrigTitle||document.title;}catch(e){}")
        except Exception:
            pass
        selector = (selector or "").strip()
        if not host or not selector:
            return
        rules = self.settings.setdefault("element_hide_rules", [])
        if not any(r.get("domain") == host and r.get("selector") == selector for r in rules):
            rules.append({"domain": host, "selector": selector})
            save_json(SETTINGS_FILE, self.settings)
            self._apply_privacy()              # persist: hides on every reload
        show_toast(self, "Element hidden on %s" % host)

    def on_icon_changed(self, view, icon):
        # Remember the page's favicon and recompose (favicon + function dot).
        view._favicon = icon
        if self.tabs.indexOf(view) >= 0:
            self._compose_tab_icon(view)

    # ------------------------------------------ saved custom page sizes ----
    #  A MANUAL, permanent zoom override per active profile + domain/page.
    #  Set from the "Custom size..." popup (main menu / tab right-click);
    #  always wins over the normal zoom below. Removed only by hand - see
    #  ZoomSizeDialog / ZoomSizeManagerDialog.
    def _zoom_store(self):
        return self.settings.setdefault("page_zoom_overrides", {})

    def _zoom_bucket(self, pid=None):
        store = self._zoom_store()
        return store.setdefault(pid or self.active_id, {"by_host": {}, "by_url": {}})

    def _saved_zoom_for(self, qurl, pid=None):
        """The manual override for this URL, if any: the exact page first,
        else its whole domain. None if nothing has been saved."""
        bucket = self._zoom_bucket(pid)
        u = qurl.toString()
        if u in bucket["by_url"]:
            return bucket["by_url"][u]
        host = clean_host(qurl.host())
        if host and host in bucket["by_host"]:
            return bucket["by_host"][host]
        return None

    def _set_zoom_override(self, view, value, per_page):
        qurl = view.url()
        host = clean_host(qurl.host())
        if not host:
            show_toast(self, "No page to save a size for here")
            return
        bucket = self._zoom_bucket()
        sub = "by_url" if per_page else "by_host"
        key = qurl.toString() if per_page else host
        bucket[sub][key] = round(float(value), 2)
        save_json(SETTINGS_FILE, self.settings)
        view.setZoomFactor(float(value))
        show_toast(self, "Saved %d%% for %s (%s)" % (
            int(round(value * 100)),
            "this page" if per_page else host,
            self._active_profile().get("name", "this profile")))

    def _clear_zoom_override(self, host_or_url, per_page, pid=None):
        bucket = self._zoom_bucket(pid)
        sub = "by_url" if per_page else "by_host"
        bucket[sub].pop(host_or_url, None)
        save_json(SETTINGS_FILE, self.settings)

    def _apply_saved_zoom(self, view):
        """Apply this page's saved custom size (if any) whenever a tab lands
        on a URL; otherwise fall back to low-vision / the normal default
        zoom, exactly like before this feature existed."""
        z = self._saved_zoom_for(view.url())
        view._zoom_override = z is not None
        if z is None:
            z = self._lv_zoom if self.settings.get("low_vision") \
                else float(self.settings.get("zoom", 1.0))
        try:
            view.setZoomFactor(float(z))
        except Exception:
            pass

    def _apply_saved_zoom_all_tabs(self):
        for i in range(self.tabs.count()):
            v = self.tabs.widget(i)
            if v:
                self._apply_saved_zoom(v)

    def open_zoom_size_dialog(self):
        view = self.current_view()
        if not view:
            return
        ZoomSizeDialog(self, view).exec()

    def open_zoom_size_manager(self):
        ZoomSizeManagerDialog(self).exec()

    def reset_zoom_current(self):
        """Ctrl+0 / 'Reset zoom': back to this page's saved custom size if
        it has one, otherwise the normal 100% default."""
        view = self.current_view()
        if not view:
            return
        z = self._saved_zoom_for(view.url())
        self.zoom_set(z if z is not None else 1.0)

    # ----------------------------------------------------- zoom / view ----
    def zoom_step(self, delta):
        view = self.current_view()
        if not view:
            return
        z = max(0.25, min(5.0, view.zoomFactor() + delta))
        view.setZoomFactor(z)
        self.settings["zoom"] = z
        self.status.showMessage("Zoom: {}%".format(int(z * 100)), 1500)

    def zoom_set(self, value):
        view = self.current_view()
        if view:
            view.setZoomFactor(value)
            self.settings["zoom"] = value
            self.status.showMessage("Zoom: {}%".format(int(value * 100)), 1500)

    def toggle_fullscreen(self):
        if self.isFullScreen():
            self.showNormal()
        else:
            self.showFullScreen()

    def on_fullscreen_request(self, request):
        request.accept()
        if request.toggleOn():
            self.showFullScreen()
        else:
            self.showNormal()

    def on_escape(self):
        if self.find_bar.isVisible():
            self.find_bar.hide_bar()
        elif self.isFullScreen():
            self.showNormal()
        else:
            view = self.current_view()
            if view:
                # A deliberate Stop must not trigger the "why isn't it loading?" pop-up.
                self._diag_suppress = time.time() + 2
                view.stop()

    # ----------------------------------------------------- downloads ----
    def _download_profile(self):
        """Which profile actually owns the download currently firing.

        eng.downloadRequested is wired from EVERY profile's QWebEngineProfile
        to this same on_download() slot (see the loop that creates engines).
        Using self._active_profile() there picks whichever profile tab
        happens to be focused in the UI *right now* - not necessarily the
        one the download actually came from (a background tab finishing a
        download, or the user switching profile tabs the instant one
        starts). That mismatch is why a download can silently land in the
        wrong profile's folder (falling back to the Windows Downloads
        default) even after you've set your own default.

        self.sender() is the actual QWebEngineProfile that emitted the
        signal, so match it back to its profile id instead of guessing.
        """
        src = self.sender()
        for pid, eng in self.engines.items():
            if eng is src:
                return self._profile_by_id(pid)
        return self._active_profile()   # fallback if sender() isn't available

    # ---- FIX: strip characters Windows forbids in filenames (':' from Google's
    #      "11:06 AM"-style export names being the one that actually bit us -
    #      see rev38 diagnostic log) before any download name is used ----
    @staticmethod
    def _sanitize_filename(name):
        if not name:
            return name
        # Windows-illegal: < > : " / \ | ? *  (also strip trailing dots/spaces,
        # which Windows silently drops and which can cause its own problems)
        cleaned = re.sub(r'[<>:"/\\|?*]', "-", name)
        cleaned = cleaned.rstrip(" .")
        return cleaned or "download"

    def on_download(self, download: QWebEngineDownloadRequest):
        # TEMPORARY DIAGNOSTIC (safe to remove later): proves the request
        # actually reached WhyBrowse's Python side at all, and with what
        # URL/name/mime-type Chromium thinks it has. If a download that
        # "does nothing" never even produces this log line, the problem is
        # upstream of this function (the web page / Chromium engine itself
        # never asked to download anything) rather than in this code.
        try:
            log_line("on_download() fired: url=%s  suggested_name=%s  mime=%s" % (
                download.url().toString(), download.downloadFileName(),
                download.mimeType()))
        except Exception as _e:
            log_line("on_download() fired but diagnostic logging failed: %s" % _e)
        try:
            # ---- A .torrent file arriving as a normal download (DEL 49) ----
            # Some sites serve the .torrent from an address that says nothing
            # ("/download.php?id=123"), so only the mime type / the filename
            # Chromium ends up with gives it away. Send it to the torrent
            # handling instead of the ordinary Downloads folder - which is the
            # whole point of having a torrent folder.
            try:
                _mime = (download.mimeType() or "").lower()
                _nm = (download.downloadFileName() or "").lower()
                if ((_mime in ("application/x-bittorrent", "application/x-torrent")
                     or _nm.endswith(".torrent"))
                        and self.settings.get("torrent_enabled", True)
                        and self.settings.get("torrent_mode", "ask") != "ignore"):
                    _u = download.url().toString()
                    download.cancel()
                    # Same reason as in acceptNavigationRequest: answer
                    # Chromium first, ask the user afterwards.
                    QTimer.singleShot(0, lambda u=_u: self.handle_torrent_link(
                        u, source="a .torrent file from this page",
                        as_torrent=True))
                    return
            except Exception as _te:
                log_line("torrent download hook failed: %s" % _te)
            suggested = download.downloadFileName()
            # FIX: Google Sheets/Docs export filenames often embed a clock time
            # like "11:06 AM", and ':' (plus < > " / \ | ? *) is illegal in
            # Windows filenames. Chromium happily finishes the network transfer
            # (100% received) and only then fails to create the file on disk,
            # surfacing as a silent-looking "Download failed" with reason
            # FileFailed / "General file operation failure" - confirmed via the
            # rev38 diagnostic log. Replace illegal characters up front so the
            # file can actually be created.
            suggested = self._sanitize_filename(suggested)
            prof = self._download_profile()
            default_dir = prof.get("save_dir") or os.path.join(os.path.expanduser("~"), "Downloads")
            if not os.path.isdir(default_dir):
                default_dir = os.path.expanduser("~")

            # One-shot: a specific folder was picked via the right-click "Save link
            # to..." menu (see _save_link_to / _save_link_to_chosen) - use it
            # straight away, no pop-up, then forget it again.
            forced_dir = getattr(self, "_next_download_dir", None)
            self._next_download_dir = None

            # One-shot: "Ask me where to save the next download" (or "Use the Save
            # pop-up..." on a specific link) was chosen - show the normal pop-up
            # for this one download even if Quick-download is on.
            force_popup = bool(getattr(self, "_force_download_popup", False))
            self._force_download_popup = False

            if forced_dir and os.path.isdir(forced_dir):
                name, staged = self._plan_download_name(forced_dir, suggested, prof)
                if name is None:
                    download.cancel()
                    return
                self._accept_download(download, forced_dir, name, staged)
                return

            if bool(prof.get("quick_download", False)) and not force_popup:
                name, staged = self._plan_download_name(default_dir, suggested, prof)
                if name is None:
                    download.cancel()
                    return
                self._accept_download(download, default_dir, name, staged)
                show_toast(self, "Quick-download → %s" % self._short_path(default_dir))
                return

            dlg = SaveLocationDialog(self, suggested, default_dir,
                                     prof.get("save_dirs", []))
            if dlg.exec() != QDialog.DialogCode.Accepted:
                download.cancel()
                return
            path = dlg.chosen_path()
            if not path:
                download.cancel()
                return
            directory = os.path.dirname(path)
            name = os.path.basename(path)
            # If the user ticked "Always download to this directory", remember
            # it as the profile's default AND turn Quick-download on, so this
            # pop-up stops appearing for future downloads. Just setting the
            # folder without also enabling Quick-download would still show
            # the pop-up next time, which defeats the point of "always".
            # The default (and this switch) can still be changed anytime in
            # Settings -> Downloads.
            if dlg.always_download():
                chosen = dlg.chosen_dir()
                if chosen and os.path.isdir(chosen):
                    prof["save_dir"] = chosen
                    prof["quick_download"] = True
                    save_json(SETTINGS_FILE, self.settings)
                    show_toast(self, "Always downloading here now - change in Settings")
            # The name may still clash with something already in the folder -
            # including a name the user typed by hand in the pop-up above.
            name, staged = self._plan_download_name(directory, name, prof)
            if name is None:
                download.cancel()
                return
            self._accept_download(download, directory, name, staged)
        except Exception as e:
            # TEMPORARY DIAGNOSTIC: without this, an exception anywhere above
            # could leave the QWebEngineDownloadRequest neither accepted nor
            # cancelled, which can look exactly like "nothing happens" with no
            # visible error. Log it AND cancel explicitly so Chromium's side
            # of the request is always resolved one way or the other.
            log_line("on_download() ERROR: %s\n%s" % (e, traceback.format_exc()))
            try:
                download.cancel()
            except Exception:
                pass

    def _accept_download(self, download, directory, name, staged=None):
        """Shared tail end of on_download: point the request at directory/name,
        accept it, and wire up the status-bar / toast feedback.

        `staged` (DEL 46) describes a file that was moved out of the way so this
        download could take its name:
            {"tmp": where it is now, "orig": where it was, "keep": bool}
        keep=True  it is a Backup<CODE>- copy the user asked to keep;
        keep=False it is a temporary hold for "overwrite, no backup" and is
                   deleted only once the download really lands.
        Either way, a download that fails or is cancelled puts the old file
        BACK - nothing is destroyed on the strength of a download that never
        arrived."""
        download.setDownloadDirectory(directory)
        download.setDownloadFileName(name)
        download.accept()
        self.status.showMessage("Downloading {}...".format(name))

        def on_state(_=None, d=download, n=name, st=staged):
            if d.state() == QWebEngineDownloadRequest.DownloadState.DownloadCompleted:
                self._settle_staged(st, ok=True)
                # TEMPORARY DIAGNOSTIC: confirm completion + how many bytes actually
                # landed on disk, so a "completed" that's really a 0-byte/truncated
                # file is distinguishable from a genuinely good save.
                try:
                    log_line("on_download: COMPLETED name=%s  bytes=%s/%s  path=%s" % (
                        n, d.receivedBytes(), d.totalBytes(),
                        os.path.join(d.downloadDirectory(), d.downloadFileName())))
                except Exception as _e:
                    log_line("on_download: COMPLETED (diag logging failed: %s)" % _e)
                self.status.showMessage("Saved: {}".format(n), 4000)
                show_toast(self, "Download complete")
            elif d.state() in (QWebEngineDownloadRequest.DownloadState.DownloadCancelled,
                               QWebEngineDownloadRequest.DownloadState.DownloadInterrupted):
                self._settle_staged(st, ok=False)
                # TEMPORARY DIAGNOSTIC: this is the actual "why" behind a failed
                # download - Qt gives both a machine-readable reason code and a
                # human-readable string. Without this we only ever saw "it failed",
                # never the network/disk/server-side reason.
                try:
                    log_line("on_download: FAILED name=%s  state=%s  reason_code=%s  reason=%s  bytes=%s/%s" % (
                        n, d.state(), d.interruptReason(), d.interruptReasonString(),
                        d.receivedBytes(), d.totalBytes()))
                except Exception as _e:
                    log_line("on_download: FAILED (diag logging failed: %s)" % _e)
                self.status.showMessage("Download failed: {}".format(n), 4000)
        download.stateChanged.connect(on_state)

    # ---- DEL 46: a download that clashes with a file you already have ------
    def _plan_download_name(self, directory, suggested, prof=None):
        """Decide what a download should be called when the name is taken.

        Returns (name, staged):
            name    what to save the file as
            staged  None, or the {"tmp","orig","keep"} record _accept_download
                    has to settle once the transfer ends
        Returns (None, None) if the user cancelled.

        Two clashes are recognised. An EXACT one (the name is taken), and a
        COPY one - "WhyBrowse (3).py" arriving in a folder that already holds
        "WhyBrowse.py". The second is why this exists: without it the browser
        just keeps stacking numbered copies, which is safe but is exactly the
        housekeeping the user asked to be rid of.
        """
        try:
            prof = prof or self._active_profile()
            base = strip_copy_suffix(suggested)
            exact = os.path.exists(os.path.join(directory, suggested))
            copy_clash = (base != suggested
                          and os.path.exists(os.path.join(directory, base)))
            if not exact and not copy_clash:
                return suggested, None            # nothing in the way

            # The clean name the new file would take over. For a copy clash
            # that is the un-suffixed name; otherwise the name itself.
            target = base if copy_clash else suggested
            suffix_name = self._unique_download_name(directory, suggested)

            policy = prof.get("dupe_policy", DUPE_ASK)
            if policy not in (DUPE_BACKUP, DUPE_SUFFIX, DUPE_REPLACE):
                dlg = DuplicateDownloadDialog(self, directory, suggested,
                                              target, suffix_name)
                if dlg.exec() != QDialog.DialogCode.Accepted:
                    return None, None
                choice = dlg.choice()
                if dlg.always():
                    prof["dupe_policy"] = choice
                    save_json(SETTINGS_FILE, self.settings)
                    show_toast(self, "Same-name downloads: %s (change in Settings)"
                               % dict(DUPE_CHOICES).get(choice, choice))
            else:
                choice = policy

            if choice == DUPE_SUFFIX:
                return suffix_name, None

            victim = os.path.join(directory, target)
            if not os.path.exists(victim):
                return target, None               # vanished under us - just take it

            if choice == DUPE_BACKUP:
                newp = backup_rename(victim)
                if not newp:
                    # Could not protect the old file, so do NOT overwrite it.
                    # Fall back to the safe answer rather than the asked-for one.
                    show_toast(self, "Could not back the old file up - saved as a "
                                     "numbered copy instead")
                    return suffix_name, None
                show_toast(self, "Old file kept as %s" % os.path.basename(newp), 2500)
                return target, {"tmp": newp, "orig": victim, "keep": True}

            # DUPE_REPLACE: move it aside now, delete it only when the download
            # has actually completed (see _settle_staged).
            tmp = victim + ".whybrowse-old"
            n = 1
            while os.path.exists(tmp):
                n += 1
                tmp = "%s.whybrowse-old%d" % (victim, n)
            os.replace(victim, tmp)
            return target, {"tmp": tmp, "orig": victim, "keep": False}
        except Exception as e:
            log_line("_plan_download_name failed for %s in %s: %s\n%s"
                     % (suggested, directory, e, traceback.format_exc()))
            # Never let this stop a download: fall back to the old behaviour.
            try:
                return self._unique_download_name(directory, suggested), None
            except Exception:
                return suggested, None

    def _settle_staged(self, staged, ok):
        """Finish what _plan_download_name started once the transfer has ended.

        ok=True  the new file landed: drop the temporary hold (a real
                 Backup<CODE>- copy is kept - that is the whole point of it).
        ok=False the download failed or was cancelled: put the old file back,
                 so a clash choice can never cost you a file you had."""
        if not staged:
            return
        # stateChanged can fire more than once for the same request; settling
        # twice would either delete a restored file or restore over a good one.
        if staged.get("_done"):
            return
        staged["_done"] = True
        tmp, orig, keep = staged.get("tmp"), staged.get("orig"), staged.get("keep")
        try:
            if ok:
                if not keep and tmp and os.path.exists(tmp):
                    os.remove(tmp)
                return
            if not (tmp and os.path.exists(tmp) and orig):
                return
            if os.path.exists(orig):
                # A failed download can still leave an empty shell behind at the
                # target name. An empty shell must not be allowed to block the
                # real file from coming home; anything with content, we leave.
                try:
                    if os.path.getsize(orig) > 0:
                        return
                    os.remove(orig)
                except Exception:
                    return
            os.replace(tmp, orig)
            log_line("download failed - restored %s from %s" % (orig, tmp))
            show_toast(self, "Download failed - your old file was put back")
        except Exception as e:
            log_line("_settle_staged(%s, ok=%s) failed: %s" % (staged, ok, e))

    def _unique_download_name(self, directory, name):
        """If `name` already exists in `directory`, append ' (2)', ' (3)', ...
        before the extension, so a silent Quick-download never overwrites an
        existing file behind the user's back."""
        try:
            if not os.path.exists(os.path.join(directory, name)):
                return name
            base, ext = os.path.splitext(name)
            n = 2
            while os.path.exists(os.path.join(directory, "%s (%d)%s" % (base, n, ext))):
                n += 1
            return "%s (%d)%s" % (base, n, ext)
        except Exception:
            return name

    def _short_path(self, path, maxlen=40):
        """Trim a long folder path for a one-line toast/menu label."""
        if not path or len(path) <= maxlen:
            return path
        return "…" + path[-(maxlen - 1):]

    # ---- right-click "Download to temp directory" / "next download" helpers ----
    def _save_link_to(self, url, directory):
        """Download `url` straight into `directory`, no pop-up, regardless of
        whether Quick-download is on or off (right-click → Download to temp
        directory)."""
        if not directory or not os.path.isdir(directory):
            show_toast(self, "That folder no longer exists")
            return
        self._next_download_dir = directory
        self._trigger_link_download(url)

    def _save_link_to_chosen(self, url):
        d = QFileDialog.getExistingDirectory(self, "Save link to folder",
                                             os.path.expanduser("~"))
        if d:
            self._save_link_to(url, d)

    def _save_link_via_popup(self, url):
        """Force the normal Save pop-up for this one link, even if Quick-
        download is on (e.g. to pick a different temp folder just this once)."""
        self._force_download_popup = True
        self._trigger_link_download(url)

    def _arm_force_download_popup(self):
        """'Ask me where to save the next download' - arms the pop-up for
        whichever download happens next (link click, JS-triggered save, ...),
        not just a specifically right-clicked link."""
        self._force_download_popup = True
        show_toast(self, "Next download will ask where to save")

    def _save_image_as(self, page):
        """'Save image as...' must ASK for a name and folder - otherwise it is
        just 'Save image'. Chromium's DownloadImageToDisk flows through
        on_download() like any download, which auto-saves silently whenever
        Quick-download is on. Arm the Save pop-up for exactly this one download
        so the name/folder is always asked, then trigger the image save."""
        self._force_download_popup = True
        try:
            page.triggerAction(QWebEnginePage.WebAction.DownloadImageToDisk)
        except Exception as e:
            self._force_download_popup = False
            log_line("save image as error: %s" % e)

    def _save_image_now(self, page):
        """'Save image' - the sibling of 'Save image as...'. Saves straight to
        the download folder under the image's OWN name, with no pop-up at all.

        It reuses the one-shot forced-folder path (_next_download_dir), which
        on_download() honours without ever showing the Save dialog, so the
        image just lands in the download folder. The same-name handling still
        runs, so the only thing that can still pop up is the genuine 'you
        already have a file with this name' choice - exactly as for any other
        quick download."""
        try:
            prof = self._active_profile()
            d = (prof.get("save_dir") if isinstance(prof, dict) else "") \
                or os.path.join(os.path.expanduser("~"), "Downloads")
            if not os.path.isdir(d):
                d = os.path.expanduser("~")
            self._next_download_dir = d
            page.triggerAction(QWebEnginePage.WebAction.DownloadImageToDisk)
        except Exception as e:
            self._next_download_dir = None
            log_line("save image (now) error: %s" % e)

    # ---- UPLOAD folders: per-site start folder + favourites -----------------
    #  Downloads all land in ONE place (profile save_dir). Uploads are the
    #  opposite: every site wants a different folder, and Chromium's picker only
    #  remembers the last one used anywhere. See WebPage.chooseFiles().
    def _upload_dir_for(self, host):
        return (self.settings.get("upload_dirs") or {}).get(
            clean_host(host) or "", "")

    def _upload_filter(self, mimes):
        """Turn the page's accept="" list into a file-dialog filter."""
        exts = [m for m in (mimes or []) if m.startswith(".")]
        if exts:
            return ("Accepted files (%s);;All files (*)"
                    % " ".join("*" + e for e in exts))
        return "All files (*)"

    def _choose_upload_files(self, page, mode, oldFiles, mimes):
        """The upload file picker, opened in THIS SITE'S folder.

        Returns the list of chosen paths ([] = cancelled), which is what
        QWebEnginePage.chooseFiles must hand back to Chromium."""
        try:
            host = clean_host(page.url().host())
        except Exception:
            host = ""

        # ---- Bulk upload queue (DEL 21J) --------------------------------
        # A run is in progress: answer the page straight from the queue and
        # never show a dialog. This is the part that removes the real tedium
        # (finding the folder and the next picture, every single time).
        try:
            mname = mode.name
        except Exception:
            mname = str(mode)
        q = getattr(self, "_upload_queue", None)
        if q and "Save" not in mname and "UploadFolder" not in mname:
            if self._bulk_host and host and self._bulk_host != host:
                pass                        # a different site: leave it alone
            elif "Multiple" in mname:
                # The input takes several at once - hand over the whole rest.
                files = list(q)
                self._upload_queue = []
                self._bulk_done(len(files), all_at_once=True)
                return files
            else:
                path = q.pop(0)
                self._bulk_sent += 1
                self._update_upload_marker()
                if q:
                    delay = int(self.settings.get("bulk_advance_delay", 2500) or 2500)
                    QTimer.singleShot(delay, self._bulk_advance)
                else:
                    self._bulk_done(self._bulk_sent)
                return [path]

        dirs = self.settings.setdefault("upload_dirs", {})
        favs = self.settings.setdefault("upload_favs", [])
        site_dir = dirs.get(host) or ""
        ask = self.settings.get("upload_ask", "unset")

        # Offer the favourites popup when the site has no folder of its own
        # (or always, if you set it that way). With nothing to offer at all we
        # skip straight to the picker rather than showing an empty box.
        show = (ask == "always") or (ask == "unset" and not site_dir)
        if show and (favs or site_dir):
            dlg = UploadFolderDialog(self, host, site_dir, favs)
            if dlg.exec() != QDialog.DialogCode.Accepted:
                return []                       # cancelled the whole upload
            self.settings["upload_favs"] = dlg.favourites()
            if dlg.chosen_dir:
                site_dir = dlg.chosen_dir
                if dlg.remember and host:
                    dirs[host] = site_dir
            save_json(SETTINGS_FILE, self.settings)

        start = self._upload_start_dir(host, site_dir)

        # (mode was already matched by NAME above, so this keeps working
        # across Qt versions.)
        flt = self._upload_filter(mimes)
        if "UploadFolder" in mname:
            kind, title = "dir", "Folder to upload"
        elif "Multiple" in mname:
            kind, title = "multi", "Select files to upload"
        elif "Save" in mname:
            kind, title = "save", "Save as"
        else:
            kind, title = "one", "Select a file to upload"

        if self.settings.get("upload_picker", "own") == "windows":
            if kind == "dir":
                d = QFileDialog.getExistingDirectory(self, title, start)
                files = [d] if d else []
            elif kind == "multi":
                files, _ = QFileDialog.getOpenFileNames(self, title, start, flt)
            elif kind == "save":
                p, _ = QFileDialog.getSaveFileName(self, title, start, flt)
                files = [p] if p else []
            else:
                p, _ = QFileDialog.getOpenFileName(self, title, start, flt)
                files = [p] if p else []
        else:
            recent = self.settings.setdefault("upload_recent", [])
            favs = self.settings.setdefault("upload_favs", [])   # the pop-up may have replaced the list
            files = pick_upload_files(self, kind, title, start, flt,
                                      recent, site_dir, favs)
            save_json(SETTINGS_FILE, self.settings)     # pins / removals persist even on Cancel

        self._upload_remember(host, files)
        return files

    def _upload_start_dir(self, host, site_dir):
        """Where the upload picker opens: the folder last used on THIS site if
        that was within UPLOAD_RESUME_SECONDS (so picture 2..7 of an advert open
        next to picture 1), else the site's own folder, else the last folder
        used anywhere, else the home folder."""
        cands = []
        # DEL 59: by default the picker opens in the PROFILE'S OWN default folder
        # (e.g. C:\0---Temp) - small, so it opens at once. The old "site's last
        # folder" rule is the other choice in Settings -> Uploads.
        if self.settings.get("upload_start", "profile") == "profile":
            try:
                pd = (self._active_profile() or {}).get("save_dir") or ""
            except Exception:
                pd = ""
            if pd and os.path.isdir(pd):
                return pd
        rec = (self.settings.get("upload_site_last") or {}).get(host) or {}
        try:
            if rec.get("dir") and time.time() - float(rec.get("t", 0)) < UPLOAD_RESUME_SECONDS:
                cands.append(rec["dir"])
        except Exception:
            pass
        cands += [site_dir, self.settings.get("upload_last")]
        for c in cands:
            if c and os.path.isdir(c):
                return c
        return os.path.expanduser("~")

    def _upload_remember(self, host, files):
        """Remember where a pick ended up: the global fallback, this site's last
        folder, and the recent-folders list shown in the picker's left column."""
        if not files:
            return
        first = files[0]
        base = first if os.path.isdir(first) else os.path.dirname(first)
        if not base:
            return
        base = os.path.normpath(base)
        self.settings["upload_last"] = base
        if host:
            self.settings.setdefault("upload_site_last", {})[host] = {
                "dir": base, "t": time.time()}
        recent = [r for r in (self.settings.get("upload_recent") or [])
                  if os.path.normcase(os.path.normpath(r)) != os.path.normcase(base)]
        self.settings["upload_recent"] = ([base] + recent)[:UPLOAD_RECENT_MAX]
        save_json(SETTINGS_FILE, self.settings)

    def _set_upload_dir(self, host):
        """Set / change the folder this site's upload picker starts in."""
        host = clean_host(host) or host
        dirs = self.settings.setdefault("upload_dirs", {})
        favs = self.settings.setdefault("upload_favs", [])
        dlg = UploadFolderDialog(self, host, dirs.get(host, ""), favs,
                                 for_site_setup=True)
        if dlg.exec() != QDialog.DialogCode.Accepted:
            return
        self.settings["upload_favs"] = dlg.favourites()
        if dlg.chosen_dir:
            dirs[host] = dlg.chosen_dir
            show_toast(self, "Uploads on %s start in %s"
                       % (host, self._short_path(dlg.chosen_dir)))
        save_json(SETTINGS_FILE, self.settings)

    def _clear_upload_dir(self, host):
        host = clean_host(host) or host
        (self.settings.get("upload_dirs") or {}).pop(host, None)
        save_json(SETTINGS_FILE, self.settings)
        show_toast(self, "Upload folder cleared for %s" % host)

    # ---- generic "temp directory" exception (works even with no right-
    #      clicked link, e.g. before pressing a page's own download button) ----
    def _arm_next_download_dir(self, directory):
        """One-off folder override for whichever download happens next, without
        touching the profile's normal default folder or its Quick-download
        setting. This is the no-link counterpart to _save_link_to: instead of
        acting on a specific URL right away, it just remembers the folder and
        waits for on_download() to pick it up once, then forgets it again."""
        if not directory or not os.path.isdir(directory):
            show_toast(self, "That folder no longer exists")
            return
        self._next_download_dir = directory
        show_toast(self, "Next download \u2192 %s" % self._short_path(directory))

    def _arm_next_download_dir_chosen(self):
        d = QFileDialog.getExistingDirectory(self, "Temp folder for the next download",
                                             os.path.expanduser("~"))
        if d:
            self._arm_next_download_dir(d)

    def _add_temp_download_menu(self, m, link=None):
        """Add the '\U0001F4E5 Download to temp directory' submenu - the right-click
        way to send ONE download to an exception folder without touching the
        profile's normal default (that default lives in Settings -> Downloads,
        or is set from the Save pop-up's "Always download to this directory").

        With `link` set (right-clicked directly on a link), each entry
        downloads THAT link immediately. With `link` left as None (right-
        clicked elsewhere on the page, e.g. just before pressing a page's own
        download button), each entry instead arms the same folder for
        whichever download happens next.

        Offers the profile's normal default as a one-click option, then up
        to 20 favorite folders (added/edited in Settings -> active profile ->
        "Often-used save folders"), a Browse... for a one-off folder that
        isn't worth saving as a favorite, and a way to force the full Save
        pop-up just this once.
        """
        prof = self._active_profile()
        default_dir = prof.get("save_dir") or os.path.join(
            os.path.expanduser("~"), "Downloads")
        often = prof.get("save_dirs", [])[:20]   # hard cap: up to 20 favorites

        temp_menu = m.addMenu("\U0001F4E5  Download to temp directory")
        temp_menu.setStyleSheet(self._menu_style(1))

        def _action_for(directory):
            if link:
                return lambda u=link, d=directory: self._save_link_to(u, d)
            return lambda d=directory: self._arm_next_download_dir(d)

        temp_menu.addAction("\u26A1  Quick: %s" % self._short_path(default_dir),
                            _action_for(default_dir))
        if often:
            temp_menu.addSeparator()
            for entry in often:
                temp_menu.addAction(entry.get("name", entry.get("path", "?")),
                                    _action_for(entry.get("path")))
        else:
            temp_menu.addSeparator()
            hint = temp_menu.addAction(
                "Tip: add up to 20 favorites in Settings \u2192 active profile")
            hint.setEnabled(False)
        temp_menu.addSeparator()
        if link:
            temp_menu.addAction("\U0001F4C1  Browse for a temp folder...",
                                lambda u=link: self._save_link_to_chosen(u))
            temp_menu.addSeparator()
            temp_menu.addAction("\U0001F5D4  Use the Save pop-up (pick folder there)...",
                                lambda u=link: self._save_link_via_popup(u))
        else:
            temp_menu.addAction("\U0001F4C1  Browse for a temp folder...",
                                self._arm_next_download_dir_chosen)
            temp_menu.addSeparator()
            temp_menu.addAction("\U0001F5D4  Ask me where to save the next download",
                                self._arm_force_download_popup)
        return temp_menu

    def _trigger_link_download(self, url):
        """Ask the current page's engine to download `url`, exactly as if the
        user had picked 'Save link as' from the native context menu. The
        resulting download still flows through on_download() like any other."""
        view = self.current_view()
        if not view:
            return
        try:
            view.page().download(QUrl(url))
        except Exception as e:
            log_line("save-link-to download error: %s" % e)

    # ----------------------------------------------------- bookmarks ----
    def _bm_new_folder_in_bar(self):
        name, ok = QInputDialog.getText(self, "New folder", "Folder name (on the bar):")
        if ok and name.strip():
            self.bookmarks.setdefault("bar", []).append({"title": name.strip(), "folder": []})
            self._save_bm()
            self.build_bookmarks_bar()
            show_toast(self, "Folder created")

    def _bookmark_page_to_folder(self):
        view = self.current_view()
        if not view:
            return
        url = view.url().toString()
        if not url.startswith("http"):
            show_toast(self, "Nothing to bookmark here")
            return
        m = QMenu(self)
        m.setStyleSheet(self._menu_style())
        bar_sub = self._link_folder_picker(url, self.bookmarks.setdefault("bar", []), 1)
        bar_sub.setTitle("📁  Bookmarks Toolbar")
        m.addMenu(bar_sub)
        menu_sub = self._link_folder_picker(url, self.bookmarks.setdefault("menu", []), 1)
        menu_sub.setTitle("📁  Bookmarks Menu")
        m.addMenu(menu_sub)
        m.exec(QCursor.pos())

    def add_bookmark(self):
        view = self.current_view()
        if not view:
            return
        url = view.url().toString()
        title = view.title() or url
        if not url.startswith("http"):
            show_toast(self, "Nothing to bookmark here")
            return

        # ---- find the existing location (bar root, bar folder, menu root, menu folder) ----
        bar_flat  = bookmark_flatten(self.bookmarks.get("bar",  []))
        menu_flat = bookmark_flatten(self.bookmarks.get("menu", []))
        all_flat  = bar_flat + menu_flat

        existing_titles = [x["title"] for x in all_flat if x["url"] == url]

        if existing_titles:
            mode = self.settings.get("bookmark_duplicate_mode", "ask")

            if mode == "deny":
                self.status.showMessage("Already bookmarked", 2000)
                return

            if mode == "allow":
                # fall through to the append below
                pass

            else:  # mode == "ask"  (default)
                loc = existing_titles[0]          # first / most relevant match
                # Show a modal dialog with three choices
                dlg = _BookmarkDuplicateDialog(self, title, url, loc)
                choice = dlg.exec_choice()        # "duplicate" | "move" | "cancel"
                if choice == "cancel":
                    return
                if choice == "move":
                    # Remove existing occurrence(s) and add fresh to bar root
                    self._bm_remove_url_all(url)
                    self.bookmarks.setdefault("bar", []).append({"title": title, "url": url})
                    self._save_bm()
                    self.build_bookmarks_bar()
                    show_toast(self, "Bookmark moved to bar")
                    return
                # "duplicate" – fall through to the normal append

        # Star-added bookmarks go on the bar so they are immediately visible.
        self.bookmarks.setdefault("bar", []).append({"title": title, "url": url})
        self._save_bm()
        self.build_bookmarks_bar()
        show_toast(self, "Bookmark added")

    def _bm_remove_url_all(self, url):
        """Remove every bookmark node with the given URL from bar and menu."""
        def _remove(lst):
            to_del = [n for n in lst if n.get("url") == url]
            for n in to_del:
                lst.remove(n)
            for n in lst:
                if "folder" in n:
                    _remove(n["folder"])
        _remove(self.bookmarks.setdefault("bar",  []))
        _remove(self.bookmarks.setdefault("menu", []))

    def show_bookmarks_menu(self):
        """The toolbar 🔖 button: Bookmark this page, Bookmarks ▸ and History ▸
        in one drop-down (☆ and 🕘 used to be buttons of their own)."""
        menu = QMenu(self)
        menu.setStyleSheet(self._menu_style())
        # Deferred a tick: add_bookmark may open a dialog, and a modal opened
        # straight from a menu over the web view can fail to take focus.
        menu.addAction("☆  Bookmark this page",
                       lambda: QTimer.singleShot(0, self.add_bookmark))
        menu.addSeparator()
        bm_sub = menu.addMenu("🔖  Bookmarks")
        bm_sub.setStyleSheet(self._menu_style(1))
        self._fill_bookmarks_menu(bm_sub)
        menu.addAction("📱  Phone sync (Issu's WhyBrowse app)...", lambda: QTimer.singleShot(0, self.open_phone_sync))
        h_sub = menu.addMenu("🕘  History")
        h_sub.setStyleSheet(self._menu_style(1))
        self._fill_history_menu(h_sub)
        menu.exec(self._menu_pos(self.btn_bm))

    def _fill_bookmarks_menu(self, menu):
        menu.addAction("⚙  Manage bookmarks...", self.manage_bookmarks)
        others = [p for p in self.settings.get("profiles", []) if p.get("id") != self.active_id]
        if others:
            vw = menu.addMenu("👁  View other profiles' bookmarks")
            vw.setStyleSheet(self._menu_style(1))
            for p in others:
                sub = self._folder_menu(self._profile_bookmarks_nodes(p))
                sub.setTitle("👤  %s" % p.get("name", "?"))
                vw.addMenu(sub)
            allnodes = self._all_other_bookmarks_deduped(others)
            if allnodes:
                s2 = self._folder_menu(allnodes)
                s2.setTitle("🌐  All profiles · %d links (no duplicates)" % len(allnodes))
                vw.addMenu(s2)
            imp = menu.addMenu("👥  Import from another profile (copy)")
            imp.setStyleSheet(self._menu_style(1))
            for p in others:
                imp.addAction("%s  %s" % (p.get("badge", "?"), p.get("name", "?")),
                              lambda _=False, pid=p["id"]: self.import_bookmarks_from_profile(pid))
        menu.addSeparator()
        bardata = self.bookmarks.get("bar", [])
        menudata = self.bookmarks.get("menu", [])
        if not bardata and not menudata:
            a = menu.addAction("(no bookmarks yet)")
            a.setEnabled(False)
        if bardata:
            sub = self._folder_menu(bardata)
            sub.setTitle("📁  Bookmarks Toolbar")
            menu.addMenu(sub)
            if menudata:
                menu.addSeparator()
        # Render the menu tree inline (folders become submenus)
        for n in menudata[:400]:
            if "folder" in n:
                sub = self._folder_menu(n.get("folder", []))
                sub.setTitle("📁  " + (n.get("title") or "Folder")[:40])
                menu.addMenu(sub)
            elif n.get("url"):
                a = menu.addAction((n.get("title") or n["url"])[:60])
                a.triggered.connect(lambda _=False, u=n["url"]: self._open_in_current(u))

    def manage_bookmarks(self):
        BookmarkManagerDialog(self).exec()

    def _profile_bookmarks_nodes(self, prof, include_bar=True):
        """Another profile's bookmark nodes (bar shown as a labelled folder)."""
        bm = normalize_bookmarks(load_json(self._bookmarks_file(prof), []))
        nodes = []
        if include_bar and bm.get("bar"):
            nodes.append({"title": "Bookmarks bar (%s)" % prof.get("name", ""),
                          "folder": bm["bar"]})
        nodes.extend(bm.get("menu", []))
        return nodes

    def _all_other_bookmarks_deduped(self, others):
        seen, out = set(), []
        for p in others:
            bm = normalize_bookmarks(load_json(self._bookmarks_file(p), []))
            for n in (bookmark_flatten(bm.get("bar", [])) + bookmark_flatten(bm.get("menu", []))):
                u = n.get("url")
                if u and u not in seen:
                    seen.add(u)
                    out.append({"title": n.get("title") or u, "url": u})
        return out

    def _other_profiles(self):
        return [p for p in self.settings.get("profiles", [])
                if p.get("id") != self.active_id and p.get("enabled", True)]

    #  NOTE: Tookmarks is PER PROFILE - the choice lives on the ACTIVE profile
    #  (prof["tookmarks_*"]), so profile 2 mirroring profile 1 does NOT make
    #  profile 1 mirror profile 2. Each profile decides its own (or none).
    def _tookmarks_source_profile(self):
        """The ONE other profile the ACTIVE profile mirrors (or None). If the
        chosen source is gone/invalid, fall back to the first other profile."""
        pid = self._active_profile().get("tookmarks_source")
        prof = self._profile_by_id(pid) if pid else None
        if not prof or prof.get("id") == self.active_id or not prof.get("enabled", True):
            others = self._other_profiles()
            prof = others[0] if others else None
        return prof

    def _tookmarks_nodes(self):
        """Live (read-only) bookmark tree of the ONE chosen source profile, for the
        bar's 'Tookmarks' folder. One profile only - pick it in Menu -> Tookmarks."""
        prof = self._tookmarks_source_profile()
        return self._profile_bookmarks_nodes(prof) if prof else []

    def _set_tookmarks_source(self, pid):
        """Choose which profile THIS profile's Tookmarks mirrors (per profile)."""
        ap = self._active_profile()
        ap["tookmarks_source"] = pid
        ap["tookmarks_enabled"] = True                 # picking one shows it
        save_json(SETTINGS_FILE, self.settings)
        self.build_bookmarks_bar()
        prof = self._profile_by_id(pid)
        show_toast(self, "Tookmarks now mirrors %s"
                   % (prof.get("name", "?") if prof else pid))

    def _toggle_tookmarks(self, on):
        self._active_profile()["tookmarks_enabled"] = bool(on)
        save_json(SETTINGS_FILE, self.settings)
        self.build_bookmarks_bar()
        show_toast(self, "Tookmarks folder: %s" % ("ON" if on else "OFF"))

    def copy_all_other_bookmarks(self):
        """Copymarks: physically copy EVERY other profile's bookmarks into this
        profile (each under its own 'Copymarks: <name>' folder). Asks first."""
        others = self._other_profiles()
        if not others:
            show_toast(self, "No other profiles to copy from")
            return 0
        ans = QMessageBox.question(
            self, "Copymarks",
            "Physically COPY all bookmarks from your other profiles into THIS profile?\n\n"
            "Tookmarks already shows them live without copying. Copying duplicates them here "
            "(useful as a backup before you clean up elsewhere) but can get messy.\n\nContinue?",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)
        if ans != QMessageBox.StandardButton.Yes:
            return 0
        total = 0
        for p in others:
            src_bm = normalize_bookmarks(load_json(self._bookmarks_file(p), []))
            nodes = list(src_bm.get("bar", [])) + list(src_bm.get("menu", []))
            if not nodes:
                continue
            folder = {"title": "Copymarks: %s" % p.get("name", "profile"),
                      "folder": json.loads(json.dumps(nodes))}      # deep copy
            self.bookmarks.setdefault("menu", []).append(folder)
            total += len(bookmark_flatten(nodes))
        if total:
            self._save_bm()
            self.build_bookmarks_bar()
            show_toast(self, "Copied %d bookmarks into this profile" % total)
        else:
            show_toast(self, "Other profiles have no bookmarks")
        return total

    def import_bookmarks_from_profile(self, pid):
        """Copy another profile's bookmarks into this profile, under a folder
        'From <name>' in the Bookmarks Menu (so nothing is overwritten)."""
        src = self._profile_by_id(pid)
        src_bm = normalize_bookmarks(load_json(self._bookmarks_file(src), []))
        nodes = list(src_bm.get("bar", [])) + list(src_bm.get("menu", []))
        if not nodes:
            show_toast(self, "“%s” has no bookmarks" % src.get("name", "?"))
            return
        folder = {"title": "From %s" % src.get("name", "profile"),
                  "folder": json.loads(json.dumps(nodes))}      # deep copy
        self.bookmarks.setdefault("menu", []).append(folder)
        self._save_bm()
        self.build_bookmarks_bar()
        show_toast(self, "Imported %d bookmarks from %s"
                   % (len(bookmark_flatten(nodes)), src.get("name", "?")))

    # ---- Domains you keep OUT of history and suggestions (DEL 45d) --------
    #
    #  Asked for after typing "i" in a small box and being handed a column of
    #  links from an evening's browsing. Three ways out were on the table: a
    #  minimum number of letters before anything is suggested (that exists too,
    #  see _gate_suggestions), switching the whole memory off, or THIS - naming
    #  the domains that are never remembered while everything else still is.
    #  His reasoning for preferring it, and it is right: a browser that
    #  remembers nothing looks like it is hiding something. One that simply
    #  never heard of one site looks like nothing at all.
    #
    #  It is not a "clear history" button and not private browsing. From the
    #  moment you set it, that domain is never written to history and never
    #  offered as a suggestion - and what is already stored is removed on the
    #  spot, because otherwise the very next thing you type hands it back.
    def _history_blocked(self):
        return [d for d in (self.settings.get("history_blocked_domains") or [])
                if isinstance(d, str) and d.strip()]

    def _is_history_blocked(self, url_or_host):
        h = clean_host(url_or_host)
        return bool(h) and any(self._host_matches(h, d)
                               for d in self._history_blocked())

    def _set_history_excluded(self, host, on):
        host = clean_host(host)
        if not host:
            show_toast(self, "No site here")
            return
        lst = self._history_blocked()
        if not on:
            self.settings["history_blocked_domains"] = [
                d for d in lst if not self._host_matches(host, d)]
            save_json(SETTINGS_FILE, self.settings)
            self._build_completer()
            show_toast(self, "%s is remembered again   (what was already "
                             "removed does not come back)" % host, 3200)
            return
        absorb_domain(lst, host)        # a whole domain folds in its sub-addresses
        self.settings["history_blocked_domains"] = lst
        # Purge what is already stored. A PROTECTED entry is left alone: you
        # marked it on purpose, and deleting it quietly from under a different
        # switch is not this feature's business - the toast says so.
        keep, gone, kept = [], 0, 0
        for h in self.history:
            if self._host_matches(clean_host(h.get("url", "")), host):
                if h.get("protected"):
                    keep.append(h)
                    kept += 1
                else:
                    gone += 1
            else:
                keep.append(h)
        self.history = keep
        self._save_hist()
        # ...and the lines you TYPED that name it. A search wording that never
        # mentions the site is not findable this way and stays - that is what
        # the per-line Remove in the small boxes' right-click list is for.
        th = self._typed_history()
        th2 = [x for x in th if host not in (x or "").lower()]
        dropped = len(th) - len(th2)
        self.settings["typed_history"] = th2
        save_json(SETTINGS_FILE, self.settings)
        self._build_completer()
        msg = "🙈  %s is out of history and suggestions" % host
        if gone or dropped:
            msg += "   ·  %d removed" % (gone + dropped)
        if kept:
            msg += "   ·  %d kept (🔒 protected)" % kept
        log_line("history-excluded %s (removed %d, kept %d, typed %d)"
                 % (host, gone, kept, dropped))
        show_toast(self, msg, 3600)

    def _build_suggestions_menu(self):
        """Address-bar right-click -> everything about what gets suggested:
        how soon, and which domains are never remembered at all."""
        m = QMenu("🙈  Suggestions & private domains", self)
        m.setStyleSheet(self._menu_style(1))
        n = self._suggest_min_chars()
        sub = m.addMenu("Start suggesting after…")
        sub.setStyleSheet(self._menu_style(2))
        for k in (1, 2, 3, 4, 5):
            a = sub.addAction(("●  " if k == n else "     ")
                              + ("1 letter" if k == 1 else "%d letters" % k))
            a.triggered.connect(lambda _=False, kk=k:
                                self._set_suggest_min_chars(kk))
        m.addSeparator()
        blocked = self._history_blocked()
        if not blocked:
            a = m.addAction("(no domain is kept out yet)")
            a.setEnabled(False)
        for d in sorted(blocked):
            row = m.addMenu("🙈  %s" % d)
            row.setStyleSheet(self._menu_style(2))
            row.addAction("↺  Remember %s again" % d,
                          lambda _=False, dd=d: self._set_history_excluded(dd, False))
        m.addSeparator()
        v = self.current_view()
        h0 = clean_host(v.url().host()) if v else ""
        if h0 and not self._is_history_blocked(h0):
            m.addAction("🙈  Keep %s out of history & suggestions" % h0,
                        lambda _=False, hh=h0: self._set_history_excluded(hh, True))
        for sc in (domain_scopes(h0)[1:] if h0 else []):
            if not self._is_history_blocked(sc):
                m.addAction("🙈  …or ALL of %s (every sub-address)" % sc,
                            lambda _=False, dd=sc: self._set_history_excluded(dd, True))
        return m

    def _set_suggest_min_chars(self, n):
        self.settings["suggest_min_chars"] = int(n)
        save_json(SETTINGS_FILE, self.settings)
        show_toast(self, "Suggestions start after %s"
                   % ("1 letter" if n == 1 else "%d letters" % n))

    # ----------------------------------------------------- history ----
    def _record_history(self, url, title):
        if not url or url.startswith("about:"):
            return
        if self._is_history_blocked(url):
            return                      # a domain you keep out - never stored
        if self.history and self.history[0].get("url") == url:
            return
        self.history.insert(0, {"url": url, "title": title or url,
                                "time": time.strftime("%Y-%m-%d %H:%M")})
        self.history = self.history[:3000]         # cap size
        # Save lazily (every entry is fine; small file)
        self._save_hist()

    def show_history_menu(self):
        menu = QMenu(self)
        menu.setStyleSheet(self._menu_style())
        self._fill_history_menu(menu)
        menu.exec(self._menu_pos(self.btn_bm))

    def _fill_history_menu(self, menu):
        menu.addAction("🛡  Manage / protect history...", self.show_history_dialog)
        act_clear = menu.addAction("\U0001F5D1  Clear history (keep protected)")
        act_clear.triggered.connect(self.clear_history)
        menu.addSeparator()
        if not self.history:
            a = menu.addAction("(no history yet)")
            a.setEnabled(False)
        for h in self.history[:25]:
            label = ("🔒 " if h.get("protected") else "") + \
                    "{}  -  {}".format(h.get("title", "")[:40], h.get("time", ""))
            a = menu.addAction(label)
            a.triggered.connect(lambda _=False, u=h.get("url"): self.add_tab(u))

    def clear_history(self):
        kept = [h for h in self.history if h.get("protected")]
        removed = len(self.history) - len(kept)
        self.history = kept
        self._save_hist()
        show_toast(self, "History cleared (%d removed, %d protected kept)"
                   % (removed, len(kept)))

    def show_history_dialog(self):
        HistoryDialog(self).exec()

    # ----------------------------------------------------- crash recovery ----
    def _start_crash_recovery(self):
        """Autosave everything typed into web fields, so a crash doesn't lose it.
        Last session's autosave survives ONE restart, then self-deletes ~1h later."""
        self._crash_file = os.path.join(DATA_DIR, "crash_recovery.json")
        self._crash_prev = os.path.join(DATA_DIR, "crash_recovery_prev.json")
        try:
            if os.path.isfile(self._crash_file):
                if os.path.isfile(self._crash_prev):
                    self._safe_remove(self._crash_prev)
                os.replace(self._crash_file, self._crash_prev)
            if os.path.isfile(self._crash_prev):
                QTimer.singleShot(3600 * 1000, lambda: self._safe_remove(self._crash_prev))
        except Exception as e:
            log_line("crash recovery init: {}".format(e))
        self._crash_timer = QTimer(self)
        self._crash_timer.timeout.connect(self._crash_capture)
        self._crash_timer.start(6000)          # every 6 seconds

    def _safe_remove(self, p):
        try:
            if p and os.path.isfile(p):
                os.remove(p)
        except Exception:
            pass

    def _crash_capture(self):
        js = ("(function(){var o=[];try{"
              "document.querySelectorAll('input,textarea').forEach(function(e){"
              "if(e.type==='password'||e.type==='hidden')return;var v=(e.value||'');"
              "if(v.trim().length>=3)o.push({n:(e.name||e.id||e.getAttribute('aria-label')||e.placeholder||'field'),v:v});});"
              "document.querySelectorAll('[contenteditable=true]').forEach(function(e){"
              "var t=(e.innerText||'');if(t.trim().length>=3)o.push({n:'text',v:t});});"
              "}catch(e){}return JSON.stringify(o);})()")
        # Capture EVERY tab (not just the active one), but skip sleeping tabs so
        # we don't wake them, and skip non-web pages.
        for i in range(self.tabs.count()):
            view = self.tabs.widget(i)
            if not view or getattr(view, "_asleep", False):
                continue
            url = view.url().toString()
            if not url.startswith("http"):
                continue
            try:
                view.page().runJavaScript(js, lambda res, u=url: self._crash_store(u, res))
            except Exception:
                pass

    def _crash_store(self, url, res):
        if not res or url.startswith("about:") or is_blank_page(url):
            return
        try:
            items = json.loads(res)
        except Exception:
            return
        if not items:
            return
        data = load_json(self._crash_file, {})
        if not isinstance(data, dict):
            data = {}
        data[url] = {"time": time.strftime("%Y-%m-%d %H:%M:%S"), "fields": items}
        if len(data) > 40:                     # keep the 40 most recent pages
            for k in list(data.keys())[:-40]:
                del data[k]
        save_json(self._crash_file, data)

    def show_crash_recovery(self):
        prev = load_json(getattr(self, "_crash_prev", ""), {})
        cur = load_json(getattr(self, "_crash_file", ""), {})
        import html as _html
        parts = ["<h2 style='color:#39c6da;'>Recover typed text</h2>"]
        if not prev and not cur:
            parts.append("<p>Nothing saved yet. Text you type into web pages is "
                         "auto-saved every few seconds, so it can be recovered after "
                         "a crash. Last session's text is kept for ~1 hour after a restart.</p>")
        for title, data in (("Previous session (before last restart)", prev),
                            ("Current session", cur)):
            if not data:
                continue
            parts.append("<h3 style='color:#39c6da;'>%s</h3>" % title)
            for url, rec in list(data.items())[::-1]:
                parts.append("<p style='margin:6px 0 0;'><b>%s</b> "
                             "<span style='color:#9aa6bf;'>%s</span></p>"
                             % (_html.escape(url[:90]), rec.get("time", "")))
                for f in rec.get("fields", []):
                    parts.append("<div style='margin-left:12px;'>"
                                 "<span style='color:#9aa6bf;'>%s:</span> %s</div>"
                                 % (_html.escape(str(f.get("n", "")))[:40],
                                    _html.escape(str(f.get("v", "")))[:4000]))
        dlg = QDialog(self)
        dlg.setWindowTitle(APP_NAME + " - Recover typed text")
        dlg.setModal(True)
        dlg.resize(680, 560)
        dlg.setStyleSheet(dialog_qss())
        apply_window_icon(dlg)
        lay = QVBoxLayout(dlg)
        tb = QTextBrowser()
        tb.setStyleSheet("background:%s; border:none; padding:10px;" % C_ADDR_BG)
        tb.setHtml("".join(parts))
        lay.addWidget(tb)
        btn = QPushButton("Close")
        btn.setStyleSheet("QPushButton{background:%s; color:%s; border:none; padding:6px 18px;"
                          " border-radius:6px;}QPushButton:hover{background:%s;}"
                          % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
        btn.clicked.connect(dlg.accept)
        lay.addWidget(btn, alignment=Qt.AlignmentFlag.AlignCenter)
        dlg.exec()

    # ----------------------------------------------------- main menu ----
    def show_main_menu(self):
        menu = QMenu(self)
        menu.setStyleSheet(self._menu_style())
        menu.addAction("➕  New tab", lambda: self.new_tab())
        a_split = menu.addAction("⊞  Split view (second page beside)")
        a_split.setCheckable(True)
        a_split.setChecked(self.second_pane.isVisible())
        a_split.triggered.connect(lambda _v: self.toggle_split_view())
        pop_menu2 = menu.addMenu("🪟  Pop out this tab to a floating window")
        pop_menu2.setStyleSheet(self._menu_style(1))
        pop_menu2.addAction("📌  Always on top",
                            lambda: self._pop_out_tab(self.current_view(), True))
        pop_menu2.addAction("🪟  Normal window (can go behind others)",
                            lambda: self._pop_out_tab(self.current_view(), False))
        menu.addSeparator()
        menu.addAction("➕  Zoom in", lambda: self.zoom_step(+0.1))
        menu.addAction("➖  Zoom out", lambda: self.zoom_step(-0.1))
        menu.addAction("↺  Reset zoom", lambda: self.reset_zoom_current())
        menu.addAction("🔍  Set custom size for this page...", self.open_zoom_size_dialog)
        menu.addAction("📋  Manage custom page sizes...", self.open_zoom_size_manager)
        a_lv = menu.addAction("🔎  Low-vision mode (big text)")
        a_lv.setCheckable(True)
        a_lv.setChecked(bool(self.settings.get("low_vision")))
        a_lv.triggered.connect(lambda v: self._toggle_low_vision(v))
        menu.addSeparator()

        # ---- Two clean-mode switches + a Features submenu (see/pause each one) ----
        a_clean = menu.addAction("🧹  Clean mode - ALL profiles")
        a_clean.setCheckable(True)
        a_clean.setChecked(bool(self.settings.get("clean_mode")))
        a_clean.triggered.connect(lambda v: self._toggle_setting("clean_mode", v))

        a_clean_p = menu.addAction("🧹  Clean mode - THIS profile (%s)"
                                   % self._active_profile().get("name", "?"))
        a_clean_p.setCheckable(True)
        a_clean_p.setChecked(bool(self._active_profile().get("clean")))
        a_clean_p.triggered.connect(lambda v: self._toggle_profile_clean(v))

        feat = menu.addMenu("🎛  Features  (between Clean and Max)")
        feat.setStyleSheet(self._menu_style(1))
        self._add_feature_toggles(feat)

        a_bb = menu.addAction("🔖  Show bookmarks bar")
        a_bb.setCheckable(True)
        a_bb.setChecked(bool(self.settings.get("show_bookmarks_bar", True)))
        a_bb.triggered.connect(lambda v: self.toggle_bookmarks_bar(v))

        # ---- Tab layout: top (horizontal) vs left (vertical) + width + titles ----
        pos = self.settings.get("tab_position", "top")
        ch = int(self.settings.get("tab_chars", 15) or 15)
        cur_px = int(self.settings.get("tab_width_px", 0) or 0)
        # Human-readable summary of the active width setting
        if cur_px > 0:
            width_desc = "%d px" % cur_px
        else:
            width_desc = "%d chars" % ch
        tlm = menu.addMenu("🗂  Tabs & bookmarks layout  (tabs: %s)"
                           % ("left" if pos == "left" else "top"))
        tlm.setStyleSheet(self._menu_style(1))
        a_top = tlm.addAction(("● " if pos != "left" else "    ") + "Tabs on top (horizontal)")
        a_top.triggered.connect(lambda: self._set_tab_position("top"))
        a_left = tlm.addAction(("● " if pos == "left" else "    ") + "Tabs on the left (vertical)")
        a_left.triggered.connect(lambda: self._set_tab_position("left"))
        tlm.addSeparator()
        wsub = tlm.addMenu("Left-tab width  (%s)" % width_desc)
        wsub.setStyleSheet(self._menu_style(2))
        for n in (8, 10, 12, 15, 18, 22, 28):
            a = wsub.addAction(("● " if (n == ch and cur_px == 0) else "    ") +
                               "%d characters" % n)
            a.triggered.connect(lambda _=False, c=n: self._set_tab_chars(c))
        wsub.addSeparator()
        a_px = wsub.addAction("📐  Custom width in pixels…")
        a_px.triggered.connect(self._set_tab_width_px_dialog)
        if cur_px > 0:
            a_reset = wsub.addAction("↺  Reset to character-based width")
            a_reset.triggered.connect(lambda: self._set_tab_chars(ch))
        a_fw = tlm.addAction("Show only the first word of a page's title")
        a_fw.setCheckable(True)
        a_fw.setChecked(bool(self.settings.get("tab_first_word_only")))
        a_fw.triggered.connect(lambda v: self._toggle_first_word(v))
        tlm.addSeparator()
        bpos = self.settings.get("bookmarks_position", "top")
        bsub = tlm.addMenu("Bookmarks bar position  (%s)" % ("right" if bpos == "right" else "top"))
        bsub.setStyleSheet(self._menu_style(2))
        a_bt = bsub.addAction(("● " if bpos != "right" else "    ") + "Top (horizontal row)")
        a_bt.triggered.connect(lambda: self._set_bookmarks_position("top"))
        a_br = bsub.addAction(("● " if bpos == "right" else "    ") + "Right side (vertical)")
        a_br.triggered.connect(lambda: self._set_bookmarks_position("right"))

        menu.addSeparator()
        # ---- Bookmarks + History as submenus (also live here, not just buttons) ----
        bm_sub = menu.addMenu("🔖  Bookmarks")
        bm_sub.setStyleSheet(self._menu_style(1))
        bm_sub.addAction("☆  Bookmark this page", self.add_bookmark)
        bm_sub.addAction("⚙  Manage bookmarks...", self.manage_bookmarks)
        bm_sub.addAction("📱  Phone sync (Issu's WhyBrowse app)...", self.open_phone_sync)
        others = [p for p in self.settings.get("profiles", []) if p.get("id") != self.active_id]
        if others:
            # View (read-only) - open another profile's bookmarks without importing.
            vw = bm_sub.addMenu("👁  View other profiles' bookmarks")
            vw.setStyleSheet(self._menu_style(2))
            for p in others:
                sub = self._folder_menu(self._profile_bookmarks_nodes(p))
                sub.setTitle("👤  %s" % p.get("name", "?"))
                vw.addMenu(sub)
            allnodes = self._all_other_bookmarks_deduped(others)
            if allnodes:
                s2 = self._folder_menu(allnodes)
                s2.setTitle("🌐  All profiles · %d links (no duplicates)" % len(allnodes))
                vw.addMenu(s2)
            # Import (copies into a "From <name>" folder).
            imp = bm_sub.addMenu("👥  Import from another profile (copy)")
            imp.setStyleSheet(self._menu_style(2))
            for p in others:
                imp.addAction("%s  %s" % (p.get("badge", "?"), p.get("name", "?")),
                              lambda _=False, pid=p["id"]: self.import_bookmarks_from_profile(pid))
        bm_sub.addSeparator()
        if self.bookmarks.get("bar"):
            s = self._folder_menu(self.bookmarks["bar"], 2)
            s.setTitle("📁  Bookmarks Toolbar")
            bm_sub.addMenu(s)
        for n in self.bookmarks.get("menu", [])[:200]:
            if "folder" in n:
                s = self._folder_menu(n.get("folder", []), 2)
                s.setTitle("📁  " + (n.get("title") or "Folder")[:40])
                bm_sub.addMenu(s)
            elif n.get("url"):
                a = bm_sub.addAction((n.get("title") or n["url"])[:60])
                a.triggered.connect(lambda _=False, u=n["url"]: self._open_in_current(u))

        # ---- Tookmarks: mirror ONE other profile's bookmarks (live, read-only) ----
        tk = menu.addMenu("👻  Tookmarks  (mirror another profile's bookmarks)")
        tk.setStyleSheet(self._menu_style(1))
        a_tk = tk.addAction("Show the Tookmarks folder in the bar (this profile)")
        a_tk.setCheckable(True)
        a_tk.setChecked(bool(self._active_profile().get("tookmarks_enabled")))
        a_tk.triggered.connect(lambda v: self._toggle_tookmarks(v))
        tk.addSeparator()
        t_others = self._other_profiles()
        if t_others:
            cap = tk.addAction("Mirror which profile (for %s):"
                               % self._active_profile().get("name", "?"))
            cap.setEnabled(False)
            cur_src = self._active_profile().get("tookmarks_source")
            active_src = self._tookmarks_source_profile()
            active_pid = active_src.get("id") if active_src else None
            for p in t_others:
                mark = "● " if (p["id"] == cur_src or
                                (cur_src is None and p["id"] == active_pid)) else "    "
                a = tk.addAction(mark + "%s  %s" % (p.get("badge", "?"), p.get("name", "?")))
                a.triggered.connect(lambda _=False, pid=p["id"]: self._set_tookmarks_source(pid))
        else:
            n = tk.addAction("(no other profiles to mirror)")
            n.setEnabled(False)

        # ---- Favourites: one global starred list, visible in every profile ----
        self._build_favourites_menu(menu)

        h_sub = menu.addMenu("🕘  History")
        h_sub.setStyleSheet(self._menu_style(1))
        h_sub.addAction("🛡  Manage / protect history...", self.show_history_dialog)
        h_sub.addAction("🗑  Clear history (keep protected)", self.clear_history)
        h_sub.addAction("💾  Recover typed text...", self.show_crash_recovery)
        h_sub.addAction("✉  Recover message drafts...", self.show_drafts)
        h_sub.addSeparator()
        for h in self.history[:25]:
            a = h_sub.addAction(("🔒 " if h.get("protected") else "") +
                                "{}  -  {}".format(h.get("title", "")[:40], h.get("time", "")))
            a.triggered.connect(lambda _=False, u=h.get("url"): self.add_tab(u))

        menu.addSeparator()
        # ---- Update Scanner (watch pages for changes) ----
        wmenu = menu.addMenu("🔭  Watch for changes")
        wmenu.setStyleSheet(self._menu_style(1))
        wmenu.addAction("🔭  Watch this page", self.watch_current_page)
        _cur_url = self.current_view().url().toString() if self.current_view() else ""
        if any(w.get("url") == _cur_url for w in self.settings.get("page_watches", [])):
            wmenu.addAction("🔄  Check this page now", self.check_current_page_now)
        if self.settings.get("page_watches"):
            wmenu.addAction("🔄  Check ALL watched pages now", self._check_all_watches_now)
        changed = self._changed_watch_count()
        total = len(self.settings.get("page_watches", []))
        lbl = "🗂  Watched pages..."
        if changed:
            lbl = "🗂  Watched pages...  (%d changed)" % changed
        elif total:
            lbl = "🗂  Watched pages...  (%d)" % total
        wmenu.addAction(lbl, self.open_watch_manager)

        _dl_n = self.media_active_count()
        menu.addAction("⬇  Download video / audio..." +
                       ("  (%d going)" % _dl_n if _dl_n else ""),
                       lambda: self.open_media_downloader())
        _tor_n = len([x for x in (self.torrent_engine(create=False).rows()
                                  if self.torrent_engine(create=False) else [])
                      if not x.get("done")])
        menu.addAction("🧲  Torrents / magnet links..."
                       + ("   (%d running)" % _tor_n if _tor_n else ""),
                       self.open_torrent_manager)
        menu.addAction("📝  Saved words / snippets...", self.manage_snippets)
        menu.addAction("❓  Why isn't this page loading?", lambda: self.diagnose_loading())

        # ---- Tab sleeping: how long a background tab may sit idle before it
        #      sleeps. Auto-sleep itself is on for everything (rev87); the tab
        #      right-click menu is where you opt one OUT. This is just the timing.
        cur_sl = int(self.settings.get("tab_autosleep_min", 15) or 15)
        slm = menu.addMenu("💤  Auto-sleep delay  (%d min)" % cur_sl)
        slm.setStyleSheet(self._menu_style(1))
        for mins, txt in ((5, "After 5 minutes"), (15, "After 15 minutes"),
                          (30, "After 30 minutes"), (60, "After 1 hour")):
            a = slm.addAction(("● " if mins == cur_sl else "    ") + txt)
            a.triggered.connect(lambda _=False, m=mins: self._set_autosleep_delay(m))

        # ---- Auto-refresh: minimum time between reloads for AUTO-REFRESH tabs
        #      (you opt tabs / domains in via the tab right-click menu - this is
        #      just the timing, so switching back and forth doesn't reload every time).
        cur_ar = int(self.settings.get("tab_autorefresh_min", 5) or 5)
        arm = menu.addMenu("🔄  Auto-refresh delay  (%d min)" % cur_ar)
        arm.setStyleSheet(self._menu_style(1))
        for mins, txt in ((1, "After 1 minute"), (5, "After 5 minutes"),
                          (15, "After 15 minutes"), (30, "After 30 minutes")):
            a = arm.addAction(("● " if mins == cur_ar else "    ") + txt)
            a.triggered.connect(lambda _=False, m=mins: self._set_autorefresh_delay(m))

        menu.addSeparator()
        # ---- Password vault ----
        vmenu = menu.addMenu("🔑  Passwords")
        vmenu.setStyleSheet(self._menu_style(1))
        vmenu.addAction(("🔓  Lock vault" if self._vault_unlocked else "🔒  Unlock vault"),
                        self.toggle_vault)
        vmenu.addAction("🗂  Passwords & autofill...", self.show_vault_dialog)
        vmenu.addAction("💾  Save login for this site", self.save_login_from_page)
        a_pin = vmenu.addAction("Extra security: require a PIN")
        a_pin.setCheckable(True)
        a_pin.setChecked(bool(self.settings.get("vault_pin_enabled", True)))
        a_pin.triggered.connect(lambda v: self._toggle_vault_pin(v))
        a_afl = vmenu.addAction("Auto-fill saved logins")
        a_afl.setCheckable(True)
        a_afl.setChecked(bool(self.settings.get("vault_autofill", True)))
        a_afl.triggered.connect(lambda v: self._toggle_setting("vault_autofill", v))
        a_asv = vmenu.addAction("Auto-save logins when I sign in")
        a_asv.setCheckable(True)
        a_asv.setChecked(bool(self.settings.get("vault_autosave", True)))
        a_asv.triggered.connect(lambda v: self._toggle_setting("vault_autosave", v))

        # Auto-lock: re-lock the vault automatically a while after unlocking.
        cur_al = int(self.settings.get("vault_autolock", 0) or 0)
        alm = vmenu.addMenu("🔐  Auto-lock  (%s)" % self._autolock_label(cur_al))
        alm.setStyleSheet(self._menu_style(2))
        for secs, txt in ((0, "Off (stay unlocked)"),
                          (15, "15 seconds (just fill & lock)"),
                          (60, "1 minute"),
                          (300, "5 minutes")):
            a = alm.addAction(("● " if secs == cur_al else "    ") + txt)
            a.triggered.connect(lambda _=False, s=secs: self._set_autolock(s))
        vmenu.addSeparator()
        a_kbd = vmenu.addAction("⌨  On-screen keyboard (type with the mouse)")
        a_kbd.setCheckable(True)
        a_kbd.setChecked(bool(self._osk and self._osk.isVisible()))
        a_kbd.triggered.connect(lambda _v: self.toggle_keyboard())

        # ---- User add-ons (.js/.css from the userscripts folder) ----
        amenu = menu.addMenu("🧩  User add-ons")
        amenu.setStyleSheet(self._menu_style(1))
        amenu.addAction("📂  Open add-ons folder", self._open_userscripts_folder)
        amenu.addAction("🔄  Reload add-ons", self._reload_userscripts)
        amenu.addSeparator()
        if not self._userscripts:
            n = amenu.addAction("(drop .js/.css files in the folder)")
            n.setEnabled(False)
        else:
            disabled = set(self.settings.get("userscripts_disabled", []))
            for us in self._userscripts:
                where = (" · " + ", ".join(us["hosts"])) if us["hosts"] else " · all sites"
                a = amenu.addAction(us["name"] + where)
                a.setCheckable(True)
                a.setChecked(us["name"] not in disabled)
                a.triggered.connect(lambda _v, nm=us["name"]: self._toggle_userscript(nm))

        menu.addAction("🔍  Find a feature or setting...  (Ctrl+Shift+F)",
                       self.open_feature_search)
        menu.addAction("⚙  Settings...", self.open_settings)
        menu.addAction("💾  Backup & Restore...", self.open_backup)
        menu.addAction("🧳  Move to another computer...",
                       self.open_move)
        menu.addAction("⬇  Import bookmarks from Firefox", self.import_firefox_bookmarks)
        menu.addAction("🔑  Bring a Google sign-in over from Firefox…",
                       self.import_google_login)
        menu.addSeparator()
        menu.addAction("🖨  Print / Save page as PDF…  (Ctrl+P)",
                       self.print_page_to_pdf)
        menu.addAction("⌂  Set current page as home", self.set_home_to_current)
        menu.addAction("☰  Toggle full screen (F11)", self.toggle_fullscreen)
        menu.addAction(
            "🌐  Open this page in my system browser",
            lambda: self._open_in_system_browser(
                self.current_view().url().toString() if self.current_view() else ""))
        menu.addSeparator()
        menu.addAction("📊  Profiles overview / stats...", self.open_profiles_overview)
        menu.addAction("🐞  Report a bug / log this... (Ctrl+Shift+D)",
                       self.open_bug_report)
        menu.addSeparator()
        menu.addAction("ℹ  About " + APP_NAME, self.show_about)
        menu.addAction("🌐  Browser engine version...", self.show_engine_info)
        menu.addAction("❓  Help", self.show_help)
        menu.exec(self._menu_pos(self.btn_menu))

    FEATURE_TOGGLES = (
        ("adblock_enabled",            "🛡  Ad blocker", True),
        ("hide_search_ads",            "🚯  Hide search-engine ads", True),
        ("https_upgrade",              "🔒  Open links over HTTPS", True),
        ("block_third_party_cookies",  "🍪  Block third-party cookies", True),
        ("hide_nag_banners",           "🚫  Hide cookie banners & nag bars", True),
        ("auto_accept_cookies",        "✅  Auto-accept cookie pop-ups", True),
        ("disable_passkeys",           "🔑  Disable passkeys (use passwords)", True),
        ("fix_google_login",           "🔧  Fix Google sign-in box", True),
        ("freeze_animations",          "❄  Stop animations & movement", True),
        ("freeze_js_animations",       "🧊  Stop canvas/JS anims EVERYWHERE (breaks YouTube/Google)", False),
    )

    def _add_feature_toggles(self, menu):
        """Add the global feature on/off checkboxes to a menu (reused by ☰ and
        the page right-click menu)."""
        clean_on = self._clean_active()
        if clean_on:
            info = menu.addAction("Clean mode is ON - turn it off to use these")
            info.setEnabled(False)
            menu.addSeparator()
        for key, label, default in self.FEATURE_TOGGLES:
            a = menu.addAction(label)
            a.setCheckable(True)
            a.setChecked(bool(self.settings.get(key, default)))
            a.setEnabled(not clean_on)
            a.triggered.connect(lambda v, k=key: self._toggle_setting(k, v))

    def _toggle_setting(self, key, value):
        self.settings[key] = bool(value)
        save_json(SETTINGS_FILE, self.settings)
        self._apply_privacy()
        self._refresh_current()
        show_toast(self, "{}: {}".format(key.replace("_", " ").title(),
                                         "ON" if value else "OFF"))

    def _apply_low_vision(self):
        """Apply the current low-vision size (or normal size) to every tab."""
        on = bool(self.settings.get("low_vision"))
        minf = self._lv_minfont if on else 0
        zoom = self._lv_zoom if on else float(self.settings.get("zoom", 1.0))
        for i in range(self.tabs.count()):
            v = self.tabs.widget(i)
            if v:
                try:
                    v.settings().setFontSize(
                        QWebEngineSettings.FontSize.MinimumFontSize, int(minf))
                except Exception:
                    pass
                v.setZoomFactor(float(zoom))
        self._paint_lv_button()

    def _paint_lv_button(self):
        if not hasattr(self, "btn_lv"):
            return
        if self.settings.get("low_vision"):
            self.btn_lv.setStyleSheet(
                "QPushButton{background:%s; color:%s; border:none; padding:4px 8px; "
                "border-radius:6px; font-size:13pt;}" % (C_ACCENT, C_ACCENT_FG))
        else:
            self.btn_lv.setStyleSheet(self._css_navbtn())

    def _lv_button_click(self):
        """🔎 button: ask to CONFIRM before turning low-vision ON (it re-flows
        every open tab, so an accidental click is jarring). Turning OFF is
        instant. A 'Don't ask again' box disables the prompt for good; it can
        be re-enabled from the button's right-click menu."""
        turning_on = not self.settings.get("low_vision")
        if turning_on and self.settings.get("low_vision_ask", True):
            box = QMessageBox(self)
            box.setWindowTitle(APP_NAME + " - Low-vision mode")
            box.setIcon(QMessageBox.Icon.Question)
            box.setText("Turn ON low-vision mode?")
            box.setInformativeText(
                "Every open tab is enlarged to %.1fx zoom with a %dpx minimum "
                "font size.\n\nScroll the 🔎 button to fine-tune the size, or "
                "click it again to turn low-vision off."
                % (self._lv_zoom, self._lv_minfont))
            cb = QCheckBox("Don't ask me again")
            box.setCheckBox(cb)
            box.setStandardButtons(
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)
            box.setDefaultButton(QMessageBox.StandardButton.Yes)
            if box.exec() != QMessageBox.StandardButton.Yes:
                return
            if cb.isChecked():
                self.settings["low_vision_ask"] = False
                save_json(SETTINGS_FILE, self.settings)
        self._toggle_low_vision(turning_on)

    def _toggle_low_vision(self, value):
        self.settings["low_vision"] = bool(value)
        save_json(SETTINGS_FILE, self.settings)
        self._apply_low_vision()
        show_toast(self, "Low-vision: %s  (%.1fx, %dpx)"
                   % ("ON" if value else "OFF", self._lv_zoom, self._lv_minfont))

    def _lv_wheel(self, delta, shift):
        if not self.settings.get("low_vision"):      # scrolling turns it on
            self.settings["low_vision"] = True
            save_json(SETTINGS_FILE, self.settings)
        if shift:
            self._lv_minfont = max(8, min(60, self._lv_minfont + delta))
        else:
            self._lv_zoom = max(1.0, min(3.5, round(self._lv_zoom + delta * 0.1, 2)))
        self._apply_low_vision()
        self.status.showMessage("Low-vision: %.1fx zoom, %dpx min font"
                                % (self._lv_zoom, self._lv_minfont), 1500)

    def _lv_menu(self, pos):
        m = QMenu(self)
        m.setStyleSheet(self._menu_style())
        a_on = m.addAction("Low-vision mode")
        a_on.setCheckable(True)
        a_on.setChecked(bool(self.settings.get("low_vision")))
        a_on.triggered.connect(lambda v: self._toggle_low_vision(v))
        m.addSeparator()
        cur = m.addAction("Current size: %.1fx, %dpx" % (self._lv_zoom, self._lv_minfont))
        cur.setEnabled(False)
        m.addAction("💾  Save current size as my default", self._lv_save_default)
        m.addAction("↺  Reset to factory default (1.3x / 18px)", self._lv_factory)
        m.addSeparator()
        a_ask = m.addAction("Ask before turning ON")
        a_ask.setCheckable(True)
        a_ask.setChecked(bool(self.settings.get("low_vision_ask", True)))
        a_ask.triggered.connect(lambda v: self._lv_set_ask(v))
        m.addSeparator()
        fc = self.settings.get("forced_colors", {}) or {}
        fmenu = m.addMenu("🎨  Forced colours (high contrast)")
        fmenu.setStyleSheet(self._menu_style(1))
        a_fc = fmenu.addAction("Force my colours on every page")
        a_fc.setCheckable(True)
        a_fc.setChecked(bool(fc.get("enabled")))
        a_fc.triggered.connect(lambda v: self._set_forced("enabled", v))
        fmenu.addSeparator()
        fmenu.addAction("Background colour...", lambda: self._pick_forced("bg"))
        fmenu.addAction("Text colour...", lambda: self._pick_forced("fg"))
        fmenu.addAction("Link colour...", lambda: self._pick_forced("link"))
        m.exec(self.btn_lv.mapToGlobal(pos))

    def _set_forced(self, key, value):
        self.settings.setdefault("forced_colors", {})[key] = value
        save_json(SETTINGS_FILE, self.settings)
        self._apply_privacy()
        self._refresh_current()
        if key == "enabled":
            show_toast(self, "Forced colours: %s" % ("ON" if value else "OFF"))

    def _pick_forced(self, key):
        cur = (self.settings.get("forced_colors", {}) or {}).get(key, "#000000")
        col = QColorDialog.getColor(QColor(cur), self, "Forced colour")
        if col.isValid():
            self._set_forced(key, col.name())

    def _lv_set_ask(self, value):
        self.settings["low_vision_ask"] = bool(value)
        save_json(SETTINGS_FILE, self.settings)
        show_toast(self, "Confirm before low-vision: %s"
                   % ("ON" if value else "OFF"))

    def _lv_save_default(self):
        self.settings["low_vision_zoom"] = self._lv_zoom
        self.settings["low_vision_minfont"] = self._lv_minfont
        save_json(SETTINGS_FILE, self.settings)
        show_toast(self, "Saved %.1fx / %dpx as your default"
                   % (self._lv_zoom, self._lv_minfont))

    def _lv_factory(self):
        self._lv_zoom, self._lv_minfont = 1.3, 18
        self._apply_low_vision()
        show_toast(self, "Reset to factory default (1.3x / 18px)")

    def _toggle_profile_clean(self, value):
        self._active_profile()["clean"] = bool(value)
        save_json(SETTINGS_FILE, self.settings)
        self._apply_privacy()
        self._refresh_current()
        show_toast(self, "Clean mode (%s): %s" %
                   (self._active_profile().get("name", "?"), "ON" if value else "OFF"))

    # ----------------------------------------------------- page right-click ----
    def show_page_menu(self, view, globalpos):
        """The menu you get when you right-click a page.

        Nothing is added straight to the QMenu any more: _page_menu_entries()
        collects every entry that applies to THIS page as an (id, builder)
        pair, and render_page_menu() (DEL 43) lays them out following YOUR
        saved arrangement - your order, your own sub-menus, minus whatever you
        hid. With no saved arrangement the factory order is used, so it looks
        exactly as it always did until you rearrange it."""
        m = QMenu(self)
        m.setStyleSheet(self._menu_style())
        render_page_menu(m, self._page_menu_entries(view),
                         self.page_menu_layout(),
                         lambda depth: self._menu_style(min(depth, 2)))
        m.exec(globalpos)

    # ---- your own arrangement of that menu (DEL 43) ----
    def page_menu_layout(self):
        """Your saved arrangement of the page right-click menu (cached in
        memory; normalised on load so a missing/older file can never lose an
        entry)."""
        if getattr(self, "_page_menu_layout_cache", None) is None:
            self._page_menu_layout_cache = normalise_page_menu_layout(
                load_json(PAGE_MENU_FILE, None))
        return self._page_menu_layout_cache

    def save_page_menu_layout(self, layout):
        """Store a new arrangement (from the editor) and use it from now on."""
        self._page_menu_layout_cache = normalise_page_menu_layout(layout)
        save_json(PAGE_MENU_FILE, self._page_menu_layout_cache)

    def open_page_menu_layout(self):
        """Open the arrangement editor. Deferred by one event-loop tick for the
        same reason manage_snippets() does it: a modal dialog opened straight
        from a menu that was exec()'d over the web view can have its
        show/activate swallowed by the native surface on Windows."""
        def _open():
            dlg = PageMenuLayoutDialog(self)
            dlg.show()
            dlg.raise_()
            dlg.activateWindow()
            dlg.exec()
        QTimer.singleShot(0, _open)

    def _page_menu_entries(self, view):
        """Every entry the page menu could show RIGHT NOW, as (id, builder)
        pairs in factory order.

        builder(target_menu, depth) adds that ONE entry to whichever menu the
        arrangement puts it in (the top level, or a sub-menu you made). Entries
        that don't apply to this page - link actions with no link under the
        cursor, "un-hide" with nothing hidden - are
        simply never collected, so neither the arrangement nor the renderer has
        to know anything about the conditions."""
        page = view.page()
        WA = QWebEnginePage.WebAction
        out = []

        def entry(item_id, fn):
            out.append((item_id, fn))

        def sub_style(depth):
            """Stylesheet for a sub-menu created one level under `depth`."""
            return self._menu_style(min(depth + 1, 2))

        # ---- YouTube: quick on/off for the ad-block, so when YouTube's
        # anti-adblock wall blacks the player you can flip it off and watch ----
        try:
            _yh = (view.url().host() or "").replace("www.", "")
        except Exception:
            _yh = ""
        if _yh == "youtube.com" or _yh.endswith(".youtube.com"):
            def _b_youtube(t, d):
                a = t.addAction("▶  Block YouTube ads")
                a.setCheckable(True)
                a.setChecked(bool(self.settings.get("youtube_adblock", True)))
                a.triggered.connect(
                    lambda v: self._toggle_setting("youtube_adblock", v))
            entry("yt_adblock", _b_youtube)

        # ---- Everything that needs a link under the cursor ----
        link = ""
        try:
            req = view.lastContextMenuRequest()
            if req and not req.linkUrl().isEmpty():
                link = req.linkUrl().toString()
        except Exception:
            req = None
        if link:
            _ldom = clean_host(link)

            entry("link_open_stay", lambda t, d: t.addAction(
                "↗  Open link in new tab (stay here)",
                lambda: self.add_tab(link, switch=False, adjacent=True)))
            entry("link_open_go", lambda t, d: t.addAction(
                "➡  Open link in new tab and go there",
                lambda: self.add_tab(link, switch=True)))
            entry("link_open_temp", lambda t, d: t.addAction(
                "🕒  Open link in the TEMP tab  (reuses it)",
                lambda: self.open_in_temp(link)))
            entry("link_copy", lambda t, d: t.addAction(
                "⎘  Copy link",
                lambda: QApplication.clipboard().setText(link)))

            # ---- New-tab-by-default policy (DEL 42) ----
            def _b_links_new(t, d):
                a = t.addAction("🆕  Open links in a NEW tab by default")
                a.setCheckable(True)
                a.setChecked(bool(self.settings.get("links_open_new_tab", False)))
                a.triggered.connect(lambda v: self._set_links_open_new(v))
            entry("link_newtab_default", _b_links_new)

            if _ldom:
                def _b_same_tab(t, d):
                    a = t.addAction(
                        "↩  …except links to %s (open in SAME tab)" % _ldom)
                    a.setCheckable(True)
                    a.setChecked(_ldom in self._link_same_tab_domains())
                    a.setToolTip("A locked tab still forces a new tab, whatever "
                                 "this says.")
                    a.triggered.connect(
                        lambda _=False, dom=_ldom: self._toggle_link_same_tab(dom))
                entry("link_same_tab_domain", _b_same_tab)

            entry("link_bookmark_bar", lambda t, d: t.addAction(
                "☆  Bookmark this link (to bar)",
                lambda: self._bookmark_link(link)))
            entry("link_bookmark_unsorted", lambda t, d: t.addAction(
                "🆕  Bookmark this link → Unsorted",
                lambda: self._bookmark_to_unsorted(link)))

            def _b_bm_folder(t, d):
                fm = t.addMenu("📁  Bookmark link in folder...")
                fm.setStyleSheet(sub_style(d))
                bar_sub = self._link_folder_picker(
                    link, self.bookmarks.setdefault("bar", []), 2)
                bar_sub.setTitle("📁  Bookmarks Toolbar")
                fm.addMenu(bar_sub)
                menu_sub = self._link_folder_picker(
                    link, self.bookmarks.setdefault("menu", []), 2)
                menu_sub.setTitle("📁  Bookmarks Menu")
                fm.addMenu(menu_sub)
            entry("link_bookmark_folder", _b_bm_folder)

            if _ldom:
                def _b_hide_dom(t, d, host=_ldom):
                    t.addAction(
                        "🚫  Hide %s from search results" % host,
                        lambda _=False, dom=host: self._block_search_domain(dom))
                    # The same, aimed at the domain ABOVE it - one line for
                    # adress.hk-r.se, allaproffs.hk-r.se, hittat.hk-r.se...
                    for sc in domain_scopes(host)[1:]:
                        t.addAction(
                            "🚫  …or ALL of %s (every sub-address)" % sc,
                            lambda _=False, dom=sc: self._block_search_domain(dom))
                entry("link_hide_domain", _b_hide_dom)
                # Block where the link GOES without having to open it first -
                # the whole point being that you can already see it is junk.
                entry("link_block_domain", lambda t, d: t.addAction(
                    "⛔  BLOCK %s — never let it open again" % _ldom,
                    lambda _=False, dom=_ldom:
                        self.block_site(dom, why="link menu")))

        # ---- Everything that needs an IMAGE (or a video/audio) under the
        #      cursor (DEL 47) ------------------------------------------------
        #  WhyBrowse replaces Chromium's own context menu outright, and until
        #  now the replacement only ever asked "is there a LINK here?" - so
        #  right-clicking a picture offered nothing at all: no Copy image, no
        #  Save image as, no image address. Chromium still knows perfectly well
        #  what was clicked (lastContextMenuRequest carries mediaType/mediaUrl)
        #  and still has the actions; they simply were never asked for.
        media_url, media_type = "", None
        try:
            if req:
                media_type = req.mediaType()
                if not req.mediaUrl().isEmpty():
                    media_url = req.mediaUrl().toString()
        except Exception:
            pass
        _MT = QWebEngineContextMenuRequest.MediaType
        # A <canvas> has no URL of its own, but Chromium can still hand over
        # the pixels - so "Copy image" / "Save image as" work there too, while
        # the address/open-in-tab entries below simply do not appear.
        is_image = media_type in (_MT.MediaTypeImage, _MT.MediaTypeCanvas)
        is_av    = media_type in (_MT.MediaTypeVideo, _MT.MediaTypeAudio)

        if is_image:
            entry("img_copy", lambda t, d: t.addAction(
                "\U0001f5bc  Copy image",
                lambda: page.triggerAction(WA.CopyImageToClipboard)))
            entry("img_save_now", lambda t, d: t.addAction(
                "\U0001f4be  Save image",
                lambda: self._save_image_now(page)))
            entry("img_save", lambda t, d: t.addAction(
                "\U0001f4be  Save image as\u2026",
                lambda: self._save_image_as(page)))
            if media_url:
                entry("img_copy_address", lambda t, d: t.addAction(
                    "\u2398  Copy image address",
                    lambda: QApplication.clipboard().setText(media_url)))
                entry("img_open", lambda t, d: t.addAction(
                    "\u2197  Open image in a new tab",
                    lambda: self.add_tab(media_url, switch=True)))

        if is_av and media_url:
            _what = "video" if media_type == _MT.MediaTypeVideo else "audio"
            entry("media_copy_address", lambda t, d, w=_what: t.addAction(
                "\u2398  Copy %s address" % w,
                lambda: QApplication.clipboard().setText(media_url)))

        # ---- The engine's own edit actions (only when they are usable) ----
        for _eid, _wa in (("page_copy", WA.Copy),
                          ("page_paste", WA.Paste),
                          ("page_select_all", WA.SelectAll)):
            _a = page.action(_wa)
            if _a and _a.isEnabled():
                entry(_eid, lambda t, d, act=_a: t.addAction(act))

        # ---- Translate ----
        def _b_translate(t, d):
            tl = self.settings.get("translate_lang", "sv")
            tl_name = next((n for c, n in self._TRANSLATE_LANGS if c == tl), tl)
            trm = t.addMenu("🌍  Translate  (→ %s)" % tl_name)
            trm.setStyleSheet(sub_style(d))
            trm.addAction("🌐  Translate this page", self._translate_page)
            trm.addAction("🔤  Translate selected text", self._translate_selection)
            trm.addSeparator()
            llm = trm.addMenu("🗣  Target language")
            llm.setStyleSheet(self._menu_style(min(d + 2, 2)))
            for code, name in self._TRANSLATE_LANGS:
                a = llm.addAction(("● " if code == tl else "    ") + name)
                a.triggered.connect(
                    lambda _=False, c=code: self._set_translate_lang(c))
        entry("translate", _b_translate)

        # ---- Saved words / snippets (per domain / profile / all sites) ----
        sel = ""
        try:
            if req:
                sel = (req.selectedText() or "").strip()
        except Exception:
            pass

        entry("unlock_scroll", lambda t, d: t.addAction(
            "\U0001f513  Get scrolling back  (unlock this page)",
            lambda: self._unlock_scroll_now(view)))

        entry("copy_page_address", lambda t, d: t.addAction(
            "⎘  Copy this page's address",
            lambda: QApplication.clipboard().setText(view.url().toString())))

        _pg_url = view.url().toString()
        if _pg_url.startswith("http"):
            _pg_prof = self._active_profile()
            if not self._fav_has(_pg_url, _pg_prof.get("id") or ""):
                entry("fav_add", lambda t, d, u=_pg_url, ttl=view.title(),
                      pname=(_pg_prof.get("name") or "current"): t.addAction(
                          "⭐  Add this page to Favourites  (login: %s)" % pname,
                          lambda: self._fav_add(ttl, u)))
            entry("fav_add_login",
                  lambda t, d, u=_pg_url, ttl=view.title():
                  self._fav_login_menu(t, ttl, u,
                                       "⭐  Add to Favourites using login…"))

        # STARRED (⭐) snippets sit directly on the page menu as one-click
        # "📝 Insert: …" rows - as many as you starred, no "+N more". Every
        # snippet (starred or not) still lives one hop down in the
        # "📝 Saved words / snippets" sub-menu; un-starred ones ONLY there.
        _stars = self._snip_favs()[:12]
        if _stars:
            def _b_stars(t, d):
                for word in _stars:
                    lbl = word if len(word) <= 60 else word[:60] + "…"
                    t.addAction("📝  Insert:  %s" % lbl,
                                lambda _=False, w=word: self._type_into_focused(
                                    view, w, fallback=True))
            entry("snippet_stars", _b_stars)

        entry("snippets", lambda t, d: self._add_snippets_menu(t, view, sel))

        # Manually remember the value of the field you right-clicked, for
        # auto-fill next time (the opt-in alternative to AUTO-remember).
        entry("remember_field", lambda t, d: t.addAction(
            "💾  Remember this field's value here (auto-fill next time)",
            lambda: self._remember_field(view)))
        _fhost = clean_host(view.url().host())
        if _fhost in self._form_mem:
            entry("forget_fields", lambda t, d, h=_fhost: t.addAction(
                "🚫  Forget saved fields for %s" % h,
                lambda: self._forget_site_fields(h)))

        # The advert box that appears INSIDE the page (DEL 21L).
        entry("popup_kill", lambda t, d: t.addAction(
            "🗯  Kill a pop-up box on this page (click it)…",
            lambda: self.enter_popupkill_mode(view)))
        # For a MANDATORY box (1177's "Välj region") that blinks back after
        # remove/close: point at your choice once and it gets clicked for you.
        entry("autoclick", lambda t, d: t.addAction(
            "👆  Click a button for me every time (remember a choice)…",
            lambda: self.enter_autoclick_mode(view)))

        _khost = clean_host(view.url().host())
        _krules = self._popupkill_rules(_khost)
        if _krules:
            def _b_popup_rules(t, d):
                km = t.addMenu("🗯  Pop-up rules here (%d)" % len(_krules))
                km.setStyleSheet(sub_style(d))
                for r in _krules[:20]:
                    mode = {"remove": "removed", "close": "X clicked",
                            "autoclick": "auto-clicked"}.get(r.get("mode"),
                                                             "X clicked")
                    sub = km.addMenu("%s  · %s"
                                     % ((r.get("label") or r.get("sel"))[:34], mode))
                    sub.setStyleSheet(self._menu_style(min(d + 2, 2)))
                    sub.addAction("↺  Undo this rule",
                                  lambda _=False, h=_khost, s=r.get("sel"):
                                  self._popupkill_remove_one(h, s))
                km.addSeparator()
                km.addAction("↺  Undo ALL pop-up rules on this site",
                             lambda h=_khost: self._popupkill_clear(h))
            entry("popup_rules", _b_popup_rules)

        entry("freeze_element", lambda t, d: t.addAction(
            "🧊  Stop an element from moving (click)",
            lambda: self.enter_freezeel_mode(view)))
        entry("zap_element", lambda t, d: t.addAction(
            "✂  Hide an element (click to zap)",
            lambda: self.enter_zap_mode(view)))
        entry("sticky_section", lambda t, d: t.addAction(
            "📌  Freeze a section to the top",
            lambda: self.enter_sticky_mode(view)))

        host0 = view.url().host().replace("www.", "")

        # ---- BLOCK this site, on the menu itself (DEL 21I, rev92) ----------
        # The junk list could always do this; it just sat three sub-menus down
        # under Troubleshoot, behind a heading you only open when something is
        # BROKEN - which a pop-up farm working exactly as its owner intended is
        # not. One entry, one question, and the site is gone for good.
        if host0:
            entry("block_site", lambda t, d, h=host0: t.addAction(
                "⛔  BLOCK %s — never open it again" % h,
                lambda _=False, hh=h: self.block_site(hh, why="page menu")))

            # ---- Keep this domain out of history and suggestions (DEL 45d) --
            # Not "hide my tracks" - a browser that remembers nothing looks
            # like it is hiding something. This one simply never heard of this
            # one site, while everything else is remembered as usual.
            def _b_nohist(t, d, h=host0):
                a = t.addAction(
                    "🙈  Keep %s out of history & suggestions" % h)
                a.setCheckable(True)
                a.setChecked(self._is_history_blocked(h))
                a.setToolTip(
                    "Nothing from this site is written to history or offered "
                    "in the address boxes.\nWhat is already stored is removed "
                    "now - switching this off later does not bring it back.")
                a.triggered.connect(
                    lambda v, hh=h: self._set_history_excluded(hh, v))
                # ...and the domain above it, for a site that lives on many
                # sub-addresses (adress.hk-r.se, hittat.hk-r.se...).
                for sc in domain_scopes(h)[1:]:
                    if not self._is_history_blocked(sc):
                        t.addAction(
                            "🙈  …or ALL of %s out of history & suggestions" % sc,
                            lambda _=False, dd=sc:
                                self._set_history_excluded(dd, True))
            entry("no_history_domain", _b_nohist)

        if host0 and any(r.get("domain") == host0
                         for r in self.settings.get("freeze_rules", [])):
            entry("freeze_clear", lambda t, d, h=host0: t.addAction(
                "↺  Let elements move again on this site",
                lambda: self._freezeel_clear(h)))
        if host0 and any(r.get("domain") == host0
                         for r in self.settings.get("element_hide_rules", [])):
            entry("unhide_pick", lambda t, d: t.addAction(
                "👁  Show hidden, remove individually",
                lambda: self.enter_unhide_mode(view)))
            entry("unhide_all", lambda t, d, h=host0: t.addAction(
                "↺  Un-hide ALL elements on this site",
                lambda: self._zap_clear(h)))
        if host0 and any(r.get("domain") == host0
                         for r in self.settings.get("sticky_rules", [])):
            entry("sticky_clear", lambda t, d, h=host0: t.addAction(
                "↺  Un-freeze sections on this site",
                lambda: self._sticky_clear(h)))

        # Site macro: record clicks/inputs as selectors and replay them.
        def _b_macro(t, d):
            mac = t.addMenu("🎬  Site macro (remember my actions here)")
            mac.setStyleSheet(sub_style(d))
            info = mac.addAction("ⓘ  Experimental — see how it works")
            info.triggered.connect(self._macro_help)
            mac.addSeparator()
            if getattr(self, "_macro_recording", None):
                mac.addAction("⏹  Stop recording & save", self.stop_macro_record)
            else:
                mac.addAction("⏺  Start recording",
                              lambda: self.start_macro_record(view))
            existing = self._macro_for(host0)
            if existing and existing.get("steps"):
                mac.addAction("▶  Run macro now (%d steps)" % len(existing["steps"]),
                              lambda: self.run_macro(view))
                a_auto = mac.addAction("🔁  Auto-run on every visit")
                a_auto.setCheckable(True)
                a_auto.setChecked(bool(existing.get("auto")))
                a_auto.triggered.connect(
                    lambda _v, h=host0: self._toggle_macro_auto(h))
                mac.addAction("🗑  Delete this macro",
                              lambda h=host0: self._clear_macro(h))
        entry("site_macro", _b_macro)

        entry("watch_page", lambda t, d: t.addAction(
            "🔭  Watch this page for changes", self.watch_current_page))
        # Show "Check now" only when the page is already being watched
        _cur_url = view.url().toString()
        if any(w.get("url") == _cur_url
               for w in self.settings.get("page_watches", [])):
            entry("watch_check_now", lambda t, d: t.addAction(
                "🔄  Check this page for changes now", self.check_current_page_now))

        # ---- Favourite open-link shortcut (repeated, so it is never far) ----
        if link:
            entry("link_open_favourite_1", lambda t, d: t.addAction(
                *self._open_link_default_action(link)))

        # "Download to temp directory" - the one-click way to send THIS link
        # (or, with no link right-clicked, whichever download happens next)
        # to an exception folder without touching the profile's normal default.
        entry("temp_download", lambda t, d: self._add_temp_download_menu(t, link))
        # ---- Torrent links (DEL 49) ----
        # Only offered when the link really is one, so the menu never grows a
        # dead entry on an ordinary page link.
        if link and is_torrent_link(link):
            entry("torrent_link", lambda t, d, u=link: t.addAction(
                "🧲  Torrent this link…",
                lambda: self.handle_torrent_link(
                    u, source="the right-click menu")))
        entry("torrents_window", lambda t, d: t.addAction(
            "🧲  Torrents…", self.open_torrent_manager))
        if link:
            entry("download_media_link", lambda t, d: t.addAction(
                "⬇  Download video/audio from this LINK...",
                lambda u=link: self.open_media_downloader(u)))
        entry("download_media_page", lambda t, d: t.addAction(
            "⬇  Download video/audio from this page...",
            lambda: self.open_media_downloader()))

        entry("split_view", lambda t, d: t.addAction(
            "⊟  Close split view" if self.second_pane.isVisible()
            else "⊞  Split view (second page beside)", self.toggle_split_view))

        if link:
            entry("open_link_system", lambda t, d: t.addAction(
                "🌐  Open LINK in my system browser",
                lambda u=link: self._open_in_system_browser(u)))
        entry("view_source", lambda t, d: t.addAction(
            "🔍  View page source",
            lambda: self.add_tab("view-source:" + view.url().toString(),
                                 switch=True)))
        _sp = page.action(WA.SavePage)
        if _sp:
            _sp.setText("💾  Save page as...")
            entry("save_page", lambda t, d, act=_sp: t.addAction(act))
        entry("print_pdf", lambda t, d: t.addAction(
            "🖨  Print / Save as PDF…  (Ctrl+P)", self.print_page_to_pdf))

        if link:
            entry("link_open_favourite_2", lambda t, d: t.addAction(
                *self._open_link_default_action(link)))

        def _b_features(t, d):
            feat = t.addMenu("🎛  Features (quick toggle, all sites)")
            feat.setStyleSheet(sub_style(d))
            self._add_feature_toggles(feat)
        entry("features", _b_features)

        if host0:
            def _b_site(t, d, h=host0):
                site = t.addMenu("🌐  Exceptions for %s" % h)
                site.setStyleSheet(sub_style(d))
                self._add_site_overrides(site, h)
            entry("site_exceptions", _b_site)

        # ---- Troubleshoot: open in system browser + both diagnose tools ----
        def _b_trouble(t, d, host=host0):
            prob = t.addMenu("🔧  Troubleshoot this page")
            prob.setStyleSheet(sub_style(d))
            deep = self._menu_style(min(d + 2, 2))
            prob.addAction("🌐  Open in my system browser (always up to date)",
                           lambda: self._open_in_system_browser(
                               view.url().toString()))
            prob.addAction("❓  Why isn't this page loading?",
                           lambda v=view: self.diagnose_loading(v))
            if host:
                prob.addAction("🤖  Stuck on \"Verify you are human\" here — "
                               "let it through", self._challenge_help_current)
            prob.addAction("🕵  What this page sees about me (bot-check report)",
                           self._show_fingerprint_report)
            # ---- Popup guard + junk list (DEL 21I) ----
            if host:
                junk = prob.addMenu("🚫  Popups & junk sites")
                junk.setStyleSheet(deep)
                junk.addAction("🚫  JUNK SITE — block %s and close this tab" % host,
                               self._junk_add_current)
                junk.addSeparator()
                a_pb = junk.addAction("⛔  Let %s open no new tabs at all" % host)
                a_pb.setCheckable(True)
                a_pb.setChecked(self._popup_policy(host) == "block")
                a_pb.triggered.connect(self._toggle_popups_here)
                junk.addAction("🗂  Junk sites and popup rules...",
                               self.show_junk_manager)
                junk.addSeparator()
                a_plain = junk.addAction(
                    "🧹  Turn OFF ALL pop-up-block / element-hide rules, "
                    "everywhere (Plain mode)")
                a_plain.setCheckable(True)
                a_plain.setChecked(bool(self.settings.get("clean_mode")))
                a_plain.triggered.connect(
                    lambda v: self._toggle_setting("clean_mode", v))
            # ---- Auction clock (DEL 21G) ----
            if host:
                auc = prob.addMenu("⏱  Auction clock")
                auc.setStyleSheet(deep)
                auc.addAction("⏱  Turn it on/off for %s" % host,
                              self._toggle_auction_clock_here)
                auc.addAction("⏱  Bid margin: %d s (change...)"
                              % int(self.settings.get("auction_margin_s", 20) or 20),
                              self._set_auction_margin)
                auc.addAction("▶  Show it on this page now",
                              lambda v=view: self._force_auction_clock(v))
            relaxed = self.settings.get("challenge_relaxed_hosts") or []
            if relaxed:
                prob.addAction("↩  Restore normal blocking on %d relaxed site%s…"
                               % (len(relaxed), "" if len(relaxed) == 1 else "s"),
                               self._undo_challenge_relaxations)
            if host:
                diag = prob.addMenu("🔬  Find what's breaking (one feature at a time)")
                diag.setStyleSheet(deep)
                self._add_diagnose_menu(diag, host)
        entry("troubleshoot", _b_trouble)

        # The way back into the editor. It can be MOVED anywhere, but never
        # hidden - see PAGE_MENU_ANCHOR in DEL 43.
        entry("arrange_menu", lambda t, d: t.addAction(
            "⚙  Arrange this menu…", self.open_page_menu_layout))

        return out

    def _open_link_default_action(self, url):
        """Return (label, callable) for the user's preferred open-link action."""
        mode = self.settings.get("open_link_default", "new_tab_stay")
        if mode == "new_tab_go":
            return ("➡  Open link in new tab and go there",
                    lambda u=url: self.add_tab(u, switch=True))
        # default: new_tab_stay
        return ("↗  Open link in new tab (stay here)",
                lambda u=url: self.add_tab(u, switch=False, adjacent=True))

    # ---- Links-open-in-new-tab policy (DEL 42) ----
    def _link_same_tab_domains(self):
        return self.settings.setdefault("links_same_tab_domains", [])

    def _toggle_link_same_tab(self, domain):
        domain = clean_host(domain)
        if not domain:
            return
        lst = self._link_same_tab_domains()
        if domain in lst:
            lst.remove(domain)
            show_toast(self, "Links to %s open in a NEW tab" % domain)
        else:
            lst.append(domain)
            show_toast(self, "Links to %s open in the SAME tab" % domain)
        save_json(SETTINGS_FILE, self.settings)

    def _set_links_open_new(self, value):
        self.settings["links_open_new_tab"] = bool(value)
        save_json(SETTINGS_FILE, self.settings)
        show_toast(self, "Open links in a new tab by default: %s"
                   % ("ON" if value else "OFF"))

    def _add_site_overrides(self, menu, host):
        ov = (self.settings.get("site_overrides") or {}).get(host, {})
        for key, label, default in (
                ("scripts_enabled",           "📜  Run JavaScript here", True),
                ("freeze_js",                 "🧊  Stop canvas/JS animations here", False),
                ("block_third_party_cookies", "🍪  Block third-party cookies here", True),
                ("adblock_enabled",           "🛡  Ad blocker here", True),
                ("hide_nag_banners",          "🚫  Hide cookie/nag bars here", True),
                ("freeze_animations",         "❄  Freeze animations here", False),
                ("restore_scroll",            "📍  Remember scroll position here", False),
                ("force_js_scroll",           "🖱  Fix stuck mouse-wheel scrolling here", False),
                ("scroll_guard",              "🔓  Auto-release a stuck scrollbar here", True),
                ("keep_scroll",               "🔒  Keep my place while a page loads here", True),
                ("eager_lazy_images",         "🖼  Load lazy (data-src) images here", True)):
            cur = ov.get(key, self.settings.get(key, default))
            a = menu.addAction(label)
            a.setCheckable(True)
            a.setChecked(bool(cur))
            a.triggered.connect(lambda v, h=host, k=key: self._set_site_override(h, k, v))
        # Per-site scroll-speed MULTIPLIER - stacks on top of the global speed in
        # Settings → Performance, e.g. global 1.3x × 2.4x here = 3.12x on THIS
        # site only. "Off" removes the override and falls back to the global speed.
        cur_mult = float(ov.get("scroll_speed_mult", 1.0) or 1.0)
        mult_txt = ("%.2f" % cur_mult).rstrip("0").rstrip(".")
        ssm = menu.addMenu("🖱  Scroll speed here  (×%s)" % mult_txt)
        for mult, txt in ((1.0, "Off (use global speed)"), (1.1, "×1.1"), (1.5, "×1.5"),
                          (2.0, "×2.0"), (2.4, "×2.4"), (3.0, "×3.0"), (4.0, "×4.0"),
                          (5.0, "×5.0")):
            a = ssm.addAction(("● " if abs(mult - cur_mult) < 0.001 else "    ") + txt)
            a.triggered.connect(lambda _=False, h=host, m=mult: self._set_site_scroll_mult(h, m))
        # Per-site browser identity (DEL 53): for a site that behaves well in
        # Firefox but not here. Applies to this site only; reloads the page.
        cur_ua = (ov.get("user_agent") or "").strip()
        # DEL 58: with no choice of yours, an Amazon shop is on the engine identity.
        shown_ua = cur_ua or (self._site_ua_map().get(host.lower().replace("www.", ""), ""))
        uam = menu.addMenu("🧭  Browser identity here  (%s)" % site_ua_kind(shown_ua))
        chrome_ua = self._effective_user_agent(self._get_engine(self._valid_active_id()))
        presets = (("Automatic (same as every other site)", ""),
                   ("Firefox", firefox_user_agent()),
                   ("Chrome", chrome_ua),
                   ("Edge", chrome_ua + " Edg/%d.0.0.0" % self._ua_chrome_major()),
                   ("Engine default (what Amazon gets automatically)",
                    self._engine_default_ua()))
        for label, ua in presets:
            on = (ua == shown_ua) or (not ua and not shown_ua)
            a = uam.addAction(("● " if on else "    ") + label)
            a.triggered.connect(lambda _=False, h=host, u=ua: self._set_site_ua(h, u))
        uam.addSeparator()
        uam.addAction("✎  Custom user agent…",
                      lambda h=host, c=cur_ua: self._ask_site_ua(h, c))
        if ov:
            menu.addSeparator()
            menu.addAction("⨯  Clear exceptions for this site",
                           lambda h=host: self._clear_site_override(h))

    def _add_diagnose_menu(self, menu, host):
        """A focused 'bisect what's interfering with THIS page' menu. Each item
        turns ONE WhyBrowse feature off for this host and reloads, so you can see
        which one was breaking the page. (We can't open true parallel variants in
        separate tabs because per-site exceptions are shared per host + engine —
        so this is one-click-per-feature in place, same end result: find the culprit.)"""
        hint = menu.addAction("Click each in turn, watch the page, then Reset ↓")
        hint.setEnabled(False)
        menu.addSeparator()
        menu.addAction("🚫  Turn ALL WhyBrowse features OFF here & reload",
                       lambda h=host: self._diagnose_disable_all(h))
        menu.addSeparator()
        for key, label in (
                ("adblock_enabled",           "🛡  Reload with Ad blocker OFF here"),
                ("hide_nag_banners",          "🚫  Reload with nag/cookie hiding OFF here"),
                ("freeze_animations",         "❄  Reload with Freeze-animations OFF here"),
                ("freeze_js",                 "🧊  Reload with canvas/JS-freeze OFF here"),
                ("block_third_party_cookies", "🍪  Reload allowing 3rd-party cookies here"),
                ("keep_scroll",               "🔒  Reload with “keep my place” OFF here")):
            menu.addAction(label,
                           lambda h=host, k=key: self._set_site_override(h, k, False))
        if host == "youtube.com" or host.endswith(".youtube.com"):
            menu.addAction("▶  Reload with YouTube ad-block OFF here",
                           lambda: (self.settings.__setitem__("youtube_adblock", False),
                                    save_json(SETTINGS_FILE, self.settings),
                                    self._apply_privacy(), self._refresh_current(),
                                    show_toast(self, "YouTube ad-block OFF — reload")))
        menu.addSeparator()
        menu.addAction("↺  Reset this site (re-enable everything)",
                       lambda h=host: self._clear_site_override(h))

    def _diagnose_disable_all(self, host):
        """Turn every interfering feature OFF for this host at once (JS stays ON so
        the page still works). If the page is fixed, re-enable one at a time."""
        ov = self.settings.setdefault("site_overrides", {}).setdefault(host, {})
        ov["adblock_enabled"] = False
        ov["block_third_party_cookies"] = False
        ov["hide_nag_banners"] = False
        ov["freeze_animations"] = False
        ov["freeze_js"] = False
        ov["keep_scroll"] = False
        ov["scripts_enabled"] = True
        save_json(SETTINGS_FILE, self.settings)
        self._apply_privacy()
        self._refresh_current()
        show_toast(self, "All WhyBrowse features OFF for %s — reloading" % host)

    def _unlock_scroll_now(self, view=None):
        """Right-click -> "Get scrolling back": release the page's scroll lock
        this instant, no questions asked.

        The automatic guard (DEL 48) deliberately keeps its hands off while a
        visible full-screen overlay is up, because that is a real modal and the
        lock behind it is correct. This is the override for when you can see
        perfectly well that nothing is there - and it means never having to
        reload a page just to get the scrollbar back."""
        view = view or self.current_view()
        if not view:
            return

        def done(n):
            show_toast(self, "Scrolling released" if n
                       else "This page was not locked - nothing to release")
        try:
            view.page().runJavaScript(SCROLL_UNLOCK_NOW_JS, done)
        except Exception as e:
            log_line("unlock scroll failed: %s" % e)

    def _block_search_domain(self, domain):
        """Add a domain to the search-result block list (also in Settings)."""
        domain = clean_host(domain)
        lst = self.settings.setdefault("search_block_domains", [])
        # A whole domain (hk-r.se) swallows the narrower lines it covers; a
        # sub-address that a wider line already covers is not added twice.
        changed, swallowed = absorb_domain(lst, domain)
        if changed:
            save_json(SETTINGS_FILE, self.settings)
            self._apply_privacy()
            self._refresh_current()
        extra = ("   ·  %d narrower line%s folded in"
                 % (swallowed, "" if swallowed == 1 else "s")) if swallowed else ""
        if changed or not domain:
            show_toast(self, "Hiding %s (and everything under it) from search "
                             "results%s" % (domain, extra), 2800)
        else:
            show_toast(self, "%s is already hidden from search results" % domain)

    # ----------------------------------------------------- Update Scanner ----
    def watch_current_page(self):
        """Start watching the current tab's page for changes (asks for options)."""
        view = self.current_view()
        if not view:
            return
        url = view.url().toString()
        if not url.startswith("http"):
            show_toast(self, "Only web pages can be watched")
            return
        watches = self.settings.setdefault("page_watches", [])
        if any(w.get("url") == url for w in watches):
            show_toast(self, "Already watching this page")
            return
        opts = WatchOptionsDialog(self).get()       # interval / ignore-numbers / min-change
        if opts is None:
            return                                  # cancelled
        w = {"url": url, "title": view.title() or url, "last_checked": 0,
             "baseline": False, "changed": False, "error": ""}
        w.update(opts)
        watches.append(w)
        save_json(SETTINGS_FILE, self.settings)
        self._watcher.check(url)                     # grab the baseline right away
        show_toast(self, "Now watching this page (every %s)"
                   % self._interval_label(opts["interval_min"]))

    def check_current_page_now(self):
        """Manually trigger an immediate background check for the current page,
        if it is in the watch list. Shows a toast either way."""
        view = self.current_view()
        if not view:
            return
        url = view.url().toString()
        ws = self.settings.get("page_watches", [])
        w = next((x for x in ws if x.get("url") == url), None)
        if w is None:
            show_toast(self, "This page is not being watched — use 'Watch this page' first")
            return
        w["last_checked"] = int(time.time())
        self._watcher.check(url)
        show_toast(self, "Checking now…")

    def _check_all_watches_now(self):
        """Fire off an immediate background check for every watched page."""
        ws = self.settings.get("page_watches", [])
        if not ws:
            return
        now = int(time.time())
        count = 0
        for w in ws:
            if w.get("url"):
                w["last_checked"] = now
                self._watcher.check(w["url"])
                count += 1
        if count:
            show_toast(self, "Checking %d page%s…" % (count, "" if count == 1 else "s"))

    @staticmethod
    def _interval_label(mins):
        mins = int(mins)
        if mins % 1440 == 0 and mins >= 1440:
            d = mins // 1440
            return "%d day%s" % (d, "" if d == 1 else "s")
        if mins % 60 == 0 and mins >= 60:
            h = mins // 60
            return "%d hour%s" % (h, "" if h == 1 else "s")
        return "%d min" % mins

    def _watch_tick(self):
        now = int(time.time())
        for w in self.settings.get("page_watches", []):
            due = max(1, int(w.get("interval_min", 360))) * 60
            if now - int(w.get("last_checked", 0)) >= due:
                w["last_checked"] = now              # claim it so we don't re-dispatch
                self._watcher.check(w["url"])

    @staticmethod
    def _watch_normalize(text, ignore_numbers):
        if ignore_numbers:
            text = re.sub(r"\d+", "", text)          # ignore changing prices/counts/dates
            text = re.sub(r"\s+", " ", text).strip()
        return text

    @staticmethod
    def _diff_chars(a, b):
        """How many characters differ between two texts (insert+delete+replace)."""
        n = 0
        for tag, i1, i2, j1, j2 in difflib.SequenceMatcher(None, a, b,
                                                           autojunk=False).get_opcodes():
            if tag != "equal":
                n += max(i2 - i1, j2 - j1)
        return n

    def _on_watch_result(self, url, text, error):
        w = next((x for x in self.settings.get("page_watches", [])
                  if x.get("url") == url), None)
        if not w:
            return
        w["last_checked"] = int(time.time())
        if error:
            w["error"] = error
        else:
            w["error"] = ""
            new_cmp = self._watch_normalize(text, w.get("ignore_numbers", False))
            old_cmp = self._watch_cache.get(url)
            if old_cmp is not None and w.get("baseline"):
                diff = self._diff_chars(old_cmp, new_cmp)
                if diff >= max(1, int(w.get("min_change", 1))):
                    w["changed"] = True
                    show_toast(self, "🔭 Page changed (%d chars): %s"
                               % (diff, (w.get("title") or url)[:42]))
            w["baseline"] = True
            self._watch_cache[url] = new_cmp
            save_json(WATCH_CACHE_FILE, self._watch_cache)
        save_json(SETTINGS_FILE, self.settings)
        self._update_watch_badge()

    def _changed_watch_count(self):
        return sum(1 for w in self.settings.get("page_watches", []) if w.get("changed"))

    def _update_watch_badge(self):
        """Reflect the number of changed watched pages in the status bar."""
        n = self._changed_watch_count()
        if n:
            self.status.showMessage("🔭 %d watched page%s changed - see the menu"
                                    % (n, "" if n == 1 else "s"))
        # (the menu entry also shows the count)

    def open_watch_manager(self):
        WatchManagerDialog(self).exec()

    # ----------------------------------------------------- tab sleeping ----
    def _sleep_tab(self, view, auto=False):
        """Free a background tab's memory. It reloads fresh when refocused."""
        if view is None or view is self.current_view() or getattr(view, "_asleep", False):
            return
        url = view.url().toString()
        if not url.startswith("http"):
            return                                   # nothing worth sleeping
        try:
            # Discarded = the heaviest saving (drops the render process); Qt
            # reloads the page automatically when the tab becomes visible again.
            view.page().setLifecycleState(QWebEnginePage.LifecycleState.Discarded)
        except Exception:
            # Fallback: blank the page and remember the URL to reload on wake.
            view._sleep_url = url
            try:
                view.setUrl(QUrl("about:blank"))
            except Exception:
                return
        view._asleep = True
        self._refresh_tab_label(view)
        if not auto:
            show_toast(self, "Tab put to sleep 💤")

    def _wake_tab(self, view):
        if not getattr(view, "_asleep", False):
            return
        view._asleep = False
        su = getattr(view, "_sleep_url", None)
        if su:                                       # fallback path: reload the page
            view._sleep_url = None
            try:
                view.setUrl(QUrl(su))
            except Exception:
                pass
        else:
            # Lifecycle path. The ASSUMPTION used to be "becoming visible again
            # already triggers a fresh reload for a Discarded page" - measured
            # live, that does not reliably happen in this QTabWidget setup:
            # switching to a slept tab showed the exact same stale content with
            # nothing forcing new data in, until a manual Ctrl+R. So don't trust
            # it - restore Active, then explicitly reload ourselves. If Chromium
            # already reloaded on its own this is just one harmless extra
            # request; if it didn't (the actual bug), this is what makes the
            # "you're back" moment actually show anything new. This is also
            # what makes an Auto-refresh tab that ALSO has Auto-sleep on
            # actually refresh on return - previously the sleep branch took
            # priority in on_tab_changed and swallowed the one chance to reload.
            try:
                view.page().setLifecycleState(QWebEnginePage.LifecycleState.Active)
            except Exception:
                pass
            try:
                view.reload()
            except Exception:
                pass
        self._refresh_tab_label(view)

    # The only sites auto-sleep still steps around on its own (rev87). Everything
    # else - Google Docs/Sheets/Drive/Calendar included - sleeps, because those
    # are exactly where the memory sits and they all save as you go. What stays
    # here is what sleeping would actually COST you: pages whose whole job is to
    # keep receiving (chat/mail), an AI chat that may still be writing an answer
    # while you look at something else, and video you are part-way through, where
    # a reload puts you back at 00:00.
    # This list is a DEFAULT, not a wall (rev88): a "Sleep delay" you set for a
    # domain by hand beats it, so you can make any of these sleep after N minutes.
    _NEVER_SLEEP_HOSTS = (
        "mail.google.com", "meet.google.com", "web.whatsapp.com",
        "messenger.com", "messages.google.com",
        "claude.ai", "chatgpt.com", "chat.openai.com",
        "youtube.com", "youtu.be", "twitch.tv", "netflix.com", "vimeo.com",
        "svtplay.se", "tv4play.se", "spotify.com",
    )

    # Offered in the "Sleep delay" submenu. 0 = follow the general delay.
    SLEEP_DELAY_CHOICES = ((0, "Use the general delay"), (5, "5 minutes"),
                           (15, "15 minutes"), (30, "30 minutes"),
                           (60, "1 hour"), (120, "2 hours"), (240, "4 hours"))

    def _sleep_delay_min(self, view):
        """How long THIS tab may sit idle before it sleeps, in minutes. A number
        set on the tab wins, then one saved for its domain, then the general
        delay from Settings. Returns (minutes, explicit) - `explicit` says the
        number was chosen by hand, which is what lets it beat _NEVER_SLEEP_HOSTS."""
        gen = int(self.settings.get("tab_autosleep_min", 15) or 15)
        own = getattr(view, "_sleep_min", 0)
        if not own:
            try:
                own = self._domain_rule(clean_host(view.url().host()), "sleepmin")
            except Exception:
                own = 0
        try:
            own = int(own or 0)
        except Exception:
            own = 0
        return (own, True) if own > 0 else (gen, False)

    def _is_no_sleep(self, view):
        """Has this tab been opted OUT of auto-sleep - by hand on the tab itself,
        or by a saved rule for its domain? This is the ONE switch since rev87
        (it replaces the old opt-in "Auto-sleep" plus its "Keep awake" opposite,
        which between them needed two boxes to say one thing)."""
        if getattr(view, "_no_sleep", False):
            return True
        try:
            host = clean_host(view.url().host())
        except Exception:
            return False
        return bool(self._domain_rule(host, "nosleep"))

    def _wants_autosleep(self, view, explicit_delay=None):
        """Whether this tab is eligible for auto-sleep. Since rev87 auto-sleep is
        the DEFAULT: every idle background tab qualifies unless it is opted out
        with "Not auto-sleep", is making sound right now, or is one of the few
        built-in exceptions above. Pass explicit_delay=True when the caller has
        already worked out that this tab has a hand-set Sleep delay."""
        if self._is_no_sleep(view):
            return False
        if not self.settings.get("auto_sleep_all", True):
            return False
        if explicit_delay is None:
            explicit_delay = self._sleep_delay_min(view)[1]
        # Pinned tabs sleep too by default now - sleeping keeps the URL and
        # reloads it on return, so a pinned page comes back as itself. Settings
        # -> Performance can exempt every pinned tab again in one tick.
        if getattr(view, "_pinned", False) and not explicit_delay and \
                not self.settings.get("sleep_pinned_too", True):
            return False
        # Never pull the rug from under something that is actually playing:
        # asked live, so a PAUSED YouTube tab is still allowed to sleep while
        # the one you left running is not. This one is NOT overridable - a
        # number you typed weeks ago must not cut off sound playing right now.
        try:
            if view.page().recentlyAudible():
                return False
        except Exception:
            pass
        # A Sleep delay you set for this domain by hand beats the built-in list
        # (rev88) - otherwise those sites could never be made to sleep at all,
        # since rev87 left only an opt-OUT and no way back in.
        if explicit_delay:
            return True
        host = clean_host(view.url().host())
        h = (host or "").replace("www.", "")
        if any(h == d or h.endswith("." + d) for d in self._NEVER_SLEEP_HOSTS):
            return False
        return True

    def _sleepable_views(self):
        """Every view auto-sleep is allowed to touch. Not just the tab bar: with
        "keep other profiles' tabs loaded" on (the default) every profile you
        visit leaves its tabs FULLY loaded in live_views, and those were never
        walked here - so five visited profiles held every one of their pages in
        memory for the rest of the session, immune to the very feature meant to
        stop that. They are background tabs by definition, so they sleep on the
        same idle clock as any other."""
        views = [self.tabs.widget(i) for i in range(self.tabs.count())]
        for kept in (self.live_views or {}).values():
            views.extend(kept or [])
        return [v for v in views if v is not None]

    def _sleep_tick(self):
        """Runs once a minute. The idle delay is worked out PER TAB (rev88), so a
        site you gave its own Sleep delay - claude.ai while it writes an answer,
        say - waits its own number of minutes while everything else waits the
        general one."""
        now = time.time()
        cur = self.current_view()
        for v in self._sleepable_views():
            if v is cur or getattr(v, "_asleep", False):
                continue
            mins, explicit = self._sleep_delay_min(v)
            if not self._wants_autosleep(v, explicit_delay=explicit):
                continue
            la = getattr(v, "_last_active", None)
            if la is None:
                v._last_active = now                 # start this tab's idle clock
            elif la <= now - mins * 60:
                self._sleep_tab(v, auto=True)

    def _set_no_sleep(self, view, value):
        """Tick/untick "Not auto-sleep" for ONE tab."""
        view._no_sleep = bool(value)
        if value and getattr(view, "_asleep", False):
            self._wake_tab(view)                     # it must not stay asleep
        self._refresh_tab_label(view)
        show_toast(self, "Not auto-sleep: %s" % ("ON" if value else "OFF"))

    def _set_tab_sleepmin(self, view, mins):
        """This tab's own idle delay, in minutes. 0 = follow the general one."""
        view._sleep_min = int(mins or 0)
        view._last_active = time.time()              # a new delay starts now
        self._refresh_tab_label(view)
        show_toast(self, "Sleep delay for this tab: %s"
                   % ("%d min" % mins if mins else "the general delay"))

    def _set_autosleep_delay(self, mins):
        self.settings["tab_autosleep_min"] = int(mins)
        save_json(SETTINGS_FILE, self.settings)
        show_toast(self, "Auto-sleep delay: %d min" % mins)

    def _set_autorefresh_delay(self, mins):
        self.settings["tab_autorefresh_min"] = int(mins)
        save_json(SETTINGS_FILE, self.settings)
        show_toast(self, "Auto-refresh delay: %d min" % mins)

    def _set_site_override(self, host, key, value):
        self.settings.setdefault("site_overrides", {}).setdefault(host, {})[key] = bool(value)
        save_json(SETTINGS_FILE, self.settings)
        self._apply_privacy()
        self._refresh_current()                  # reload re-applies JS state for the host
        name = {"scripts_enabled": "JavaScript",
                "keep_scroll": "Keep my place",
                "freeze_js": "Stop canvas/JS animations"}.get(key, key.replace("_", " ").title())
        show_toast(self, "%s here: %s" % (name, "ON" if value else "OFF"))

    def _set_site_ua(self, host, ua):
        """Give one site its own browser identity ("" = back to automatic)."""
        overrides = self.settings.setdefault("site_overrides", {})
        ov = overrides.setdefault(host, {})
        ua = (ua or "").strip()
        if ua:
            ov["user_agent"] = ua
        else:
            ov.pop("user_agent", None)
            if not ov:
                overrides.pop(host, None)
        save_json(SETTINGS_FILE, self.settings)
        self._apply_privacy()
        self._refresh_current()
        show_toast(self, "%s now sees %s" % (host, site_ua_kind(ua)))

    def _ask_site_ua(self, host, current):
        text, ok = QInputDialog.getText(
            self, APP_NAME, "User agent that %s should see\n"
            "(empty = automatic):" % host, text=current)
        if ok:
            self._set_site_ua(host, text)

    def _clear_site_override(self, host):
        (self.settings.get("site_overrides") or {}).pop(host, None)
        save_json(SETTINGS_FILE, self.settings)
        self._apply_privacy()
        self._refresh_current()
        show_toast(self, "Exceptions cleared for %s" % host)

    def _set_site_scroll_mult(self, host, mult):
        """Per-site scroll-speed multiplier, stacked on top of the global speed
        (Settings → Performance) only while the wheel is over this host. No
        reload needed - the wheel handler reads it live on every scroll."""
        mult = float(mult)
        overrides = self.settings.setdefault("site_overrides", {})
        ov = overrides.setdefault(host, {})
        if mult == 1.0:
            ov.pop("scroll_speed_mult", None)
            if not ov:
                overrides.pop(host, None)
        else:
            ov["scroll_speed_mult"] = mult
        save_json(SETTINGS_FILE, self.settings)
        txt = ("%.2f" % mult).rstrip("0").rstrip(".")
        show_toast(self, ("Scroll speed for %s: back to global default" % host)
                   if mult == 1.0 else ("Scroll speed for %s: ×%s" % (host, txt)))

    # ---------------------------------- stuck on "Verify you are human" ----------
    # Detects a human-verification wall (Cloudflare "Just a moment…" / Turnstile,
    # hCaptcha, reCAPTCHA, DataDome) and, the FIRST time a site shows one, turns
    # off the WhyBrowse features that are known to break such a check for that
    # site only, then reloads once. Without this you can sit on predb.me ticking
    # the box forever. It never solves or skips the challenge - it only stops us
    # standing in its way.
    # STRICT on purpose. An ordinary page that merely CONTAINS a captcha widget
    # (almost every login and contact form has an invisible reCAPTCHA) is NOT a
    # wall, and must never trigger the relaxation - the first version of this
    # matched .g-recaptcha / captcha iframes and duly switched the ad blocker and
    # third-party-cookie blocking off for boardgamegeek.com and dancovershop.se,
    # which is a privacy regression the user never asked for.
    #
    # A real wall is an INTERSTITIAL: it replaces the site with a nearly empty
    # holding page. So we require BOTH
    #   (a) hard evidence of an interstitial - a Cloudflare challenge container,
    #       or an unmistakable title, or the challenge wording, AND
    #   (b) the page being essentially empty (a real page that happens to say
    #       "verify you are human" somewhere is not a wall).
    CHALLENGE_DETECT_JS = """(function(){
      try{
        var body = (document.body ? document.body.innerText : '') || '';
        // (b) An interstitial holds almost no content. Bail out early on a
        //     normal, populated page whatever else it may contain.
        if(body.length > 1500) return false;
        var links = document.querySelectorAll('a[href]').length;
        if(links > 25) return false;              // a real site's navigation

        // (a) Cloudflare's own interstitial containers. NOTE: .cf-turnstile,
        //     .g-recaptcha and .h-captcha are deliberately NOT here - those are
        //     widgets that live inside ordinary forms.
        if(document.querySelector('#challenge-running,#cf-challenge-running,'+
            '#challenge-stage,#cf-please-wait,#cf-spinner-please-wait,'+
            '.cf-browser-verification,#challenge-error-title,'+
            '#trk_jschal_js,form#challenge-form[action*="__cf_chl"]'))
          return true;

        var t = (document.title || '').toLowerCase();
        if(t.indexOf('just a moment') >= 0
           || t.indexOf('attention required') >= 0
           || (t.indexOf('please wait') >= 0 && t.indexOf('cloudflare') >= 0))
          return true;

        var s = body.toLowerCase();
        if(s.indexOf('verify you are human') >= 0
           || s.indexOf('checking your browser') >= 0
           || s.indexOf('review the security of your connection') >= 0)
          return true;
      }catch(e){}
      return false;
    })();"""

    # Per-site exceptions applied when a human check is detected: key -> value.
    CHALLENGE_RELAX = {
        "adblock_enabled": False,            # a blocked beacon = silent failure
        "block_third_party_cookies": False,  # the widget's own cookie is 3rd-party
        "freeze_animations": False,          # frozen spinner never completes
        "hide_nag_banners": False,           # can hide the box you must tick
        "scripts_enabled": True,             # a challenge is pure JavaScript
    }

    def _challenge_relaxed(self, host):
        """True when every anti-challenge exception is already set for `host`."""
        ov = (self.settings.get("site_overrides") or {}).get(host, {})
        return all(ov.get(k) is v for k, v in self.CHALLENGE_RELAX.items())

    def _relax_for_challenge(self, host, reload_view=None, quiet=False):
        """Turn the challenge-breaking features off for THIS site and reload."""
        ov = self.settings.setdefault("site_overrides", {}).setdefault(host, {})
        ov.update(self.CHALLENGE_RELAX)
        # Remember that WE did this, so it can be undone in one click. Weakening
        # the ad blocker and cookie blocking on a site is not something to do
        # silently and irreversibly - especially since an over-eager detector
        # once applied it to ordinary sites.
        done = self.settings.setdefault("challenge_relaxed_hosts", [])
        if host not in done:
            done.append(host)
        save_json(SETTINGS_FILE, self.settings)
        self._apply_privacy()
        if not quiet:
            show_toast(self, "Human check on %s: ad-blocker, third-party-cookie "
                             "blocking and animation freeze turned off here — "
                             "reloading" % host, 6000)
        v = reload_view or self.current_view()
        if v:
            QTimer.singleShot(400, v.reload)

    def _maybe_challenge_help(self, view):
        """After a successful load, spot a 'Verify you are human' wall and relax
        this site's settings ONCE so the check can actually complete."""
        if not self.settings.get("challenge_auto_relax", True):
            return
        try:
            url = view.url().toString()
            host = clean_host(view.url().host())
        except Exception:
            return
        if not url.startswith("http") or not host:
            return
        if self._clean_active():
            return                              # clean mode blocks nothing already
        if host in getattr(self, "_chal_helped", set()):
            return                              # already handled this session
        if self._challenge_relaxed(host):
            return                              # nothing left to turn off

        def _done(found, h=host, v=view):
            if not found:
                return
            self._chal_helped.add(h)
            log_line("challenge wall detected on %s - relaxing site settings" % h)
            self._relax_for_challenge(h, reload_view=v)

        try:
            view.page().runJavaScript(self.CHALLENGE_DETECT_JS, _done)
        except Exception:
            pass

    # What a bot check actually sees. Guessing at why a "Verify you are human"
    # wall rejects you is hopeless; this reads the real values out of the page
    # so the mismatch (if any) is visible instead of theoretical.
    FINGERPRINT_PROBE_JS = """(function(){
      var r = {};
      try{ r.ua = navigator.userAgent || ''; }catch(e){ r.ua = '?'; }
      try{
        var m = /Chrome\\/(\\d+)/.exec(r.ua);
        r.uaMajor = m ? m[1] : '(none)';
      }catch(e){}
      try{
        var d = navigator.userAgentData;
        r.uadBrands = d && d.brands
          ? d.brands.map(function(b){ return b.brand + ' ' + b.version; }).join(', ')
          : '(not exposed)';
        r.uadMobile = d ? String(!!d.mobile) : '?';
        r.uadPlatform = d ? (d.platform || '?') : '?';
      }catch(e){ r.uadBrands = '(error)'; }
      try{ r.cookiesEnabled = String(navigator.cookieEnabled); }catch(e){}
      try{ r.canSetCookie = (function(){
        try{
          document.cookie = 'wbtest=1;path=/';
          var ok = document.cookie.indexOf('wbtest=') >= 0;
          document.cookie = 'wbtest=;path=/;expires=Thu, 01 Jan 1970 00:00:00 GMT';
          return String(ok);
        }catch(e){ return 'no'; }
      })(); }catch(e){}
      try{ r.languages = (navigator.languages || []).join(', '); }catch(e){}
      try{ r.platform = navigator.platform || '?'; }catch(e){}
      try{ r.hardwareConcurrency = String(navigator.hardwareConcurrency); }catch(e){}
      try{ r.deviceMemory = String(navigator.deviceMemory); }catch(e){}
      try{ r.webdriver = String(navigator.webdriver); }catch(e){}
      try{ r.pdfViewer = String(navigator.pdfViewerEnabled); }catch(e){}
      try{ r.plugins = String((navigator.plugins || []).length); }catch(e){}
      try{ r.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone; }catch(e){}
      try{ r.screen = screen.width + 'x' + screen.height + ' @' +
                      window.devicePixelRatio + 'x'; }catch(e){}
      try{
        var c = document.createElement('canvas');
        var gl = c.getContext('webgl') || c.getContext('experimental-webgl');
        if(!gl){ r.webgl = '(no WebGL - a strong bot signal)'; }
        else{
          var dbg = gl.getExtension('WEBGL_debug_renderer_info');
          r.webgl = dbg ? (gl.getParameter(dbg.UNMASKED_VENDOR_WEBGL) + ' / ' +
                           gl.getParameter(dbg.UNMASKED_RENDERER_WEBGL))
                        : 'available (renderer hidden)';
        }
      }catch(e){ r.webgl = '(error)'; }
      return r;
    })();"""

    def _show_fingerprint_report(self):
        """Show what the current page can see about this browser, and flag the
        things a human-verification check is known to reject us for."""
        view = self.current_view()
        if not view:
            return

        def _got(r):
            r = r or {}
            real = self._engine_chrome_major()
            claimed = str(r.get("uaMajor") or "?")
            brands = r.get("uadBrands") or "(not exposed)"

            warn = []
            if real and claimed.isdigit() and int(claimed) != real:
                warn.append("The user-agent claims Chrome %s but this engine "
                            "really is Chromium %d. A bot check feature-detects "
                            "the engine and compares — a mismatch is a hard "
                            "fail. Fix: Settings → Privacy & blocking → user "
                            "agent → Automatic (or clear a custom one)."
                            % (claimed, real))
            if claimed.isdigit() and brands and brands[0].isalpha():
                if claimed not in brands and "not exposed" not in brands:
                    warn.append("navigator.userAgentData (%s) disagrees with the "
                                "user-agent string (Chrome %s)." % (brands, claimed))
            if str(r.get("canSetCookie", "")).lower() not in ("true", "yes"):
                warn.append("This page cannot set a cookie. A verification "
                            "check cannot remember that you passed it, so it "
                            "will ask again forever.")
            if str(r.get("webdriver", "")).lower() == "true":
                warn.append("navigator.webdriver is true — the page is told "
                            "outright that this is an automated browser.")
            if "no WebGL" in str(r.get("webgl", "")):
                warn.append("WebGL is unavailable; many checks treat that as a "
                            "headless/bot signal.")

            latest = 0
            try:
                latest = int(self.settings.get("cached_chrome_major") or 0)
            except Exception:
                latest = 0
            if real and latest and latest - real > UA_BUMP_GAP:
                warn.append("This engine (Chromium %d) is a long way behind "
                            "current Chrome (%d). Update it: Menu → Browser "
                            "engine version." % (real, latest))

            rows = [
                ("User-agent", r.get("ua", "?")),
                ("Claims Chrome major", claimed),
                ("Engine really is", "Chromium %d" % real if real else "unknown"),
                ("Latest stable Chrome", str(latest) if latest else "(not checked yet)"),
                ("Client hints (brands)", brands),
                ("Client hints platform", r.get("uadPlatform", "?")),
                ("Cookies enabled", r.get("cookiesEnabled", "?")),
                ("Can set a cookie here", r.get("canSetCookie", "?")),
                ("navigator.webdriver", r.get("webdriver", "?")),
                ("WebGL renderer", r.get("webgl", "?")),
                ("PDF viewer enabled", r.get("pdfViewer", "?")),
                ("Plugins", r.get("plugins", "?")),
                ("Languages", r.get("languages", "?")),
                ("Platform", r.get("platform", "?")),
                ("CPU cores / memory", "%s / %s GB" % (r.get("hardwareConcurrency", "?"),
                                                       r.get("deviceMemory", "?"))),
                ("Screen", r.get("screen", "?")),
                ("Time zone", r.get("timezone", "?")),
            ]

            dlg = QDialog(self)
            dlg.setWindowTitle(APP_NAME + " - What this page sees about me")
            dlg.setModal(False)
            dlg.resize(760, 560)
            dlg.setStyleSheet(dialog_qss())
            apply_window_icon(dlg)
            QShortcut(QKeySequence("Esc"), dlg, dlg.close)
            lay = QVBoxLayout(dlg)

            if warn:
                head = QLabel("⚠  Likely reason a human check rejects you here:")
                head.setStyleSheet("font-weight:bold; color:%s;" % C_ACCENT)
                lay.addWidget(head)
                for w in warn:
                    lab = QLabel("•  " + w)
                    lab.setWordWrap(True)
                    lay.addWidget(lab)
            else:
                ok = QLabel("✓  Nothing here looks obviously wrong. If a check "
                            "still rejects you, it is judging something this "
                            "browser cannot change from inside the page (see "
                            "Help) — use 🌐 Open in my system browser.")
                ok.setWordWrap(True)
                lay.addWidget(ok)

            txt = QPlainTextEdit()
            txt.setReadOnly(True)
            txt.setPlainText("\n".join("%-24s %s" % (k + ":", v) for k, v in rows))
            lay.addWidget(txt, 1)

            row = QHBoxLayout()
            btn_copy = QPushButton("⎘  Copy")
            btn_copy.setStyleSheet(self._css_navbtn())
            btn_copy.clicked.connect(
                lambda: (QApplication.clipboard().setText(txt.toPlainText()),
                         show_toast(self, "Copied")))
            row.addWidget(btn_copy)
            row.addStretch(1)
            btn_close = QPushButton("Close")
            btn_close.setStyleSheet(self._css_accentbtn())
            btn_close.clicked.connect(dlg.close)
            row.addWidget(btn_close)
            lay.addLayout(row)
            dlg.show()

        try:
            view.page().runJavaScript(self.FINGERPRINT_PROBE_JS, _got)
        except Exception:
            show_toast(self, "Could not read this page")

    def _undo_challenge_relaxations(self):
        """Put back the ad blocker / cookie blocking on every site where the
        human-check helper turned them off. One click, because an automatic
        privacy relaxation must always be reversible."""
        hosts = list(self.settings.get("challenge_relaxed_hosts", []))
        if not hosts:
            show_toast(self, "No sites have been relaxed for a human check")
            return
        if QMessageBox.question(
                self, APP_NAME,
                "Restore normal blocking on these %d site%s?\n\n%s\n\n"
                "The ad blocker and third-party-cookie blocking will be switched "
                "back on for them." % (len(hosts), "" if len(hosts) == 1 else "s",
                                       "\n".join("  • " + h for h in hosts)),
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
                QMessageBox.StandardButton.Yes) != QMessageBox.StandardButton.Yes:
            return
        ovs = self.settings.get("site_overrides") or {}
        for h in hosts:
            ov = ovs.get(h)
            if not ov:
                continue
            for k, v in self.CHALLENGE_RELAX.items():
                if ov.get(k) is v:
                    ov.pop(k, None)          # only remove what WE set
            if not ov:
                ovs.pop(h, None)             # nothing left: drop the entry
        self.settings["challenge_relaxed_hosts"] = []
        self._chal_helped = set()
        save_json(SETTINGS_FILE, self.settings)
        self._apply_privacy()
        self._refresh_current()
        show_toast(self, "Normal blocking restored on %d site%s"
                   % (len(hosts), "" if len(hosts) == 1 else "s"), 4000)

    def _challenge_help_current(self):
        """Manual version of the above, from the tab menu."""
        v = self.current_view()
        if not v:
            return
        host = clean_host(v.url().host())
        if not host:
            return
        self._chal_helped.add(host)
        self._relax_for_challenge(host, reload_view=v)

    # ---------------------------------- "why isn't this loading?" diagnostics ----
    def _active_blockers(self, host):
        """List WhyBrowse features CURRENTLY active for `host` that can stop a page
        from loading/rendering. Each item carries the per-site override `key` and
        the `fix` value that turns the blocking OFF for this site."""
        host = (host or "").lower().replace("www.", "")
        out = []
        if self._clean_active():
            return out                       # clean mode = nothing is being blocked
        ov = (self.settings.get("site_overrides") or {}).get(host, {})

        def eff(key, default):
            return ov.get(key, self.settings.get(key, default))

        # JavaScript off is the single biggest "page won't load" cause.
        if ov.get("scripts_enabled", True) is False:
            out.append({"key": "scripts_enabled", "fix": True,
                        "label": "JavaScript is OFF here",
                        "why": "most sites need JavaScript to show anything"})
        if eff("adblock_enabled", True):
            out.append({"key": "adblock_enabled", "fix": False,
                        "label": "Ad / tracker blocker",
                        "why": "can block a script or CDN the site needs"})
        if eff("block_third_party_cookies", True):
            out.append({"key": "block_third_party_cookies", "fix": False,
                        "label": "Block third-party cookies",
                        "why": "can break logins, embeds and single-sign-on"})
        if eff("freeze_js", False):
            out.append({"key": "freeze_js", "fix": False,
                        "label": "Stop canvas / JS animations",
                        "why": "can blank sites that lazy-load (e.g. YouTube/Google)"})
        return out

    def _maybe_https_fallback(self, view):
        """An http:// address we upgraded to https:// reported a load failure.
        Chromium cries failure far too often (a superseded navigation, an
        aborted sub-resource, a late redirect), so - exactly like
        _maybe_diagnose_failure - wait, then ASK THE PAGE whether it has any
        content, and fall back to plain http ONLY when it genuinely has none.
        The host is then remembered in https_exceptions so it is never upgraded
        again, and http-only sites keep working."""
        try:
            u = view.url()
            if u.scheme() != "https":
                return
            host = (u.host() or "").lower()
            bare = host[4:] if host.startswith("www.") else host
            pend = getattr(self, "_https_pending", None) or {}
            if bare not in pend:
                return
            https_url = u.toString()

            def _judge(score, v=view, b=bare, hu=https_url):
                p = getattr(self, "_https_pending", None) or {}
                orig = p.get(b)
                if not orig or v.url().toString() != hu:
                    return                       # moved on since
                if score and score >= 40:
                    p.pop(b, None)               # https really works - keep it
                    return
                p.pop(b, None)
                exc = self.settings.setdefault("https_exceptions", [])
                if b not in [h.lower() for h in exc]:
                    exc.append(b)
                    save_json(SETTINGS_FILE, self.settings)
                log_line("https upgrade failed for %s - falling back to http" % b)
                v.setUrl(QUrl(orig))

            def _later(v=view, hu=https_url):
                if v.url().toString() != hu or getattr(v, "_is_loading", False):
                    return                       # a new load started -> not it
                try:
                    v.page().runJavaScript(PAGE_CONTENT_PROBE_JS, _judge)
                except Exception:
                    _judge(0)
            QTimer.singleShot(1200, _later)
        except Exception as e:
            log_line("https fallback error: %s" % e)

    def _maybe_diagnose_failure(self, view):
        """Called when a page reports it failed to load. Pops the diagnostic ONLY
        when there's something WhyBrowse can actually turn off; otherwise it just
        notes (in the status bar) that it's likely the site/connection. Heavily
        guarded so a user-stop or a fresh navigation doesn't trigger it."""
        if not self.settings.get("load_diag_auto", True):
            return
        if view is not self.current_view():
            return
        url = view.url().toString()
        if not url.startswith("http"):
            return
        if time.time() < getattr(self, "_diag_suppress", 0):
            return                            # user just pressed Stop
        last_url, last_t = getattr(view, "_diag_last", ("", 0))
        if last_url == url and (time.time() - last_t) < 8:
            return                            # don't repeat for the same page

        seq = getattr(self, "_load_seq", 0)

        def _later(v=view, u=url, seq=seq):
            if v is not self.current_view() or getattr(v, "_is_loading", False):
                return                        # a new load started -> not a real failure
            if v.url().toString() != u:
                return                        # moved on
            if getattr(self, "_load_seq", 0) != seq:
                return                        # some load started since -> stale
            # Chromium reports loadFinished(ok=False) far more often than a page
            # actually fails: a superseded navigation, an aborted sub-resource or
            # a redirect that arrives a moment later all raise it, and the page
            # then renders perfectly a few hundredths of a second afterwards.
            # That produced a "didn't load" pop-up over a page that was fine.
            # So don't trust the flag - ASK THE PAGE whether it has any content,
            # and only complain when it genuinely has none.
            def _judge(score, v=v, u=u):
                if score and score >= 40:
                    return                    # the page is really there - stay quiet
                if v is not self.current_view() or v.url().toString() != u:
                    return
                host = clean_host(v.url().host())
                if not self._active_blockers(host):
                    self.status.showMessage(
                        "This page didn't load — the site or your connection may be "
                        "down (no WhyBrowse setting is blocking it).", 9000)
                    return
                v._diag_last = (u, time.time())
                self.diagnose_loading(v, auto=True)

            try:
                v.page().runJavaScript(PAGE_CONTENT_PROBE_JS, _judge)
            except Exception:
                _judge(0)
        # 1.2s, not 450ms: slow sites finish painting well after the failed
        # signal, and a pop-up that beats the page onto the screen is worse than
        # a diagnosis that arrives a second late.
        QTimer.singleShot(1200, _later)

    def diagnose_loading(self, view=None, auto=False):
        """Show what (if anything) WhyBrowse is blocking on this site, with one
        click to turn the chosen items off for THIS site and reload."""
        view = view or self.current_view()
        if not view:
            return
        host = clean_host(view.url().host())
        blockers = self._active_blockers(host)

        dlg = QDialog(self)
        dlg.setWindowTitle(APP_NAME + " - Why isn't this page loading?")
        dlg.setModal(False)
        dlg.setStyleSheet(dialog_qss())
        apply_window_icon(dlg)
        QShortcut(QKeySequence("Esc"), dlg, dlg.close)
        lay = QVBoxLayout(dlg)
        lay.setSpacing(8)

        title = QLabel("⚠  This page didn't load fully" if auto
                       else "❓  Why isn't this page loading?")
        title.setStyleSheet("font-size:13pt; font-weight:bold; color:%s;" % C_ACCENT)
        lay.addWidget(title)
        lay.addWidget(QLabel("Site:  %s" % (host or "(unknown)")))

        checks = []
        if not blockers:
            msg = QLabel(
                "WhyBrowse is NOT blocking anything on this site, so a feature of "
                "WhyBrowse is unlikely to be the cause.\n\n"
                "The page most likely failed because of the site itself or your internet "
                "connection (offline / DNS). Try Reload, or open it in your system browser "
                "to compare.")
            msg.setWordWrap(True)
            lay.addWidget(msg)
        else:
            intro = QLabel(
                "These WhyBrowse features are ON for this site and can stop a page from "
                "loading. The ticked ones will be turned OFF for THIS site only, then the "
                "page reloads. Untick anything you want to keep:")
            intro.setWordWrap(True)
            lay.addWidget(intro)
            for b in blockers:
                cb = QCheckBox("%s  —  %s" % (b["label"], b["why"]))
                cb.setChecked(True)
                cb._spec = b
                lay.addWidget(cb)
                checks.append(cb)

            apply_btn = QPushButton("✔  Turn the ticked ones OFF here & reload")
            apply_btn.setStyleSheet("QPushButton{background:%s; color:%s; border:none; "
                                    "padding:6px 14px; border-radius:6px;}"
                                    "QPushButton:hover{background:%s;}"
                                    % (C_ACCENT, C_ACCENT_FG, C_ACCENT_HOV))

            def _apply():
                so = self.settings.setdefault("site_overrides", {}).setdefault(host, {})
                n = 0
                for cb in checks:
                    if cb.isChecked():
                        so[cb._spec["key"]] = cb._spec["fix"]
                        n += 1
                save_json(SETTINGS_FILE, self.settings)
                self._apply_privacy()
                self._apply_js_for_host(view.page(), host)   # JS toggle needs re-apply
                view.reload()
                dlg.close()
                show_toast(self, "Turned off %d setting(s) for %s — reloading" % (n, host))
            apply_btn.clicked.connect(_apply)
            lay.addWidget(apply_btn)

        # ---- Always-available fallbacks ----
        row = QHBoxLayout()
        b_reload = QPushButton("↻  Reload as-is")
        b_reload.clicked.connect(lambda: (view.reload(), dlg.close()))
        b_sys = QPushButton("🌐  Open in my system browser")
        b_sys.clicked.connect(lambda: self._open_in_system_browser(view.url().toString()))
        b_close = QPushButton("Close")
        b_close.clicked.connect(dlg.close)
        row.addWidget(b_reload)
        row.addWidget(b_sys)
        row.addStretch(1)
        row.addWidget(b_close)
        lay.addLayout(row)

        cb_auto = QCheckBox("Pop this up automatically when a page fails to load")
        cb_auto.setChecked(bool(self.settings.get("load_diag_auto", True)))

        def _set_auto(v):
            self.settings["load_diag_auto"] = bool(v)
            save_json(SETTINGS_FILE, self.settings)
        cb_auto.toggled.connect(_set_auto)
        cb_auto.setStyleSheet("font-size:8pt; color:%s;" % dim_fg())
        lay.addWidget(cb_auto)

        dlg.show()

    # ----------------------------------- saved words / snippets / vocabulary ----
    #  Words/phrases you save once and re-insert into web fields with the mouse.
    #  Three scopes: this DOMAIN (e.g. "Brädspel" on blocket.se), this PROFILE,
    #  or ALL SITES (program-wide, e.g. your name / address / e-mail).
    def _snip_store(self):
        return self.settings.setdefault(
            "snippets", {"global": [], "domains": {}, "profiles": {}})

    # ---- Favourite words: a flat, ordered list pinned to the TOP of the
    #      right-click "Saved words" menu (above the "This site" folder) so
    #      the words you reach for most are one click away, on every site. ----
    def _snip_favs(self):
        return self._snip_store().setdefault("fav", [])

    def _snip_fav_toggle(self, word):
        """Pin (or un-pin) a word as a favourite. Returns True if now pinned."""
        word = (word or "").strip()
        if not word:
            return False
        favs = self._snip_favs()
        if word in favs:
            favs.remove(word)
            pinned = False
        else:
            favs.append(word)
            pinned = True
        save_json(SETTINGS_FILE, self.settings)
        return pinned

    def _snip_fav_move(self, word, delta):
        """Re-order a favourite (delta -1 = up, +1 = down). Order = menu order."""
        favs = self._snip_favs()
        if word not in favs:
            return
        i = favs.index(word)
        j = max(0, min(len(favs) - 1, i + delta))
        if i != j:
            favs.insert(j, favs.pop(i))
            save_json(SETTINGS_FILE, self.settings)

    def _snips_for_domain(self, host):
        return self._snip_store()["domains"].get(clean_host(host), [])

    def _snips_for_profile(self):
        return self._snip_store()["profiles"].get(self.active_id, [])

    def _snips_global(self):
        return self._snip_store()["global"]

    def _snip_list(self, scope, host=""):
        store = self._snip_store()
        if scope == "domain":
            return store["domains"].setdefault(clean_host(host), [])
        if scope == "profile":
            return store["profiles"].setdefault(self.active_id, [])
        return store["global"]

    def _scope_label(self, scope, host=""):
        return {"domain": clean_host(host) or "this site",
                "profile": self._active_profile().get("name", "this profile"),
                "global": "all sites"}.get(scope, scope)

    def _snip_append(self, scope, host, text):
        """Add one word to a scope (no save / no toast). Returns True if added."""
        text = (text or "").strip()
        if not text:
            return False
        lst = self._snip_list(scope, host)
        if text in lst:
            return False
        lst.append(text)
        return True

    def _snip_add(self, scope, host, text):
        if self._snip_append(scope, host, text):
            save_json(SETTINGS_FILE, self.settings)
            show_toast(self, 'Saved "%s" for %s'
                       % (text.strip()[:24], self._scope_label(scope, host)))
        else:
            show_toast(self, "Already saved (or empty)")

    def _snip_add_many(self, scope, host, text, split=True):
        """Add one OR several words at once. With `split`, commas separate words
        (so 'brädspel, sällskapsspel, playstation' becomes three)."""
        if split:
            parts = [p.strip() for p in (text or "").split(",")]
        else:
            parts = [(text or "").strip()]
        n = sum(1 for p in parts if self._snip_append(scope, host, p))
        if n:
            save_json(SETTINGS_FILE, self.settings)
            show_toast(self, "Saved %d word%s for %s"
                       % (n, "" if n == 1 else "s", self._scope_label(scope, host)))
        else:
            show_toast(self, "Nothing new to save")

    def _snip_remove(self, scope, host, text):
        lst = self._snip_list(scope, host)
        if text in lst:
            lst.remove(text)
            save_json(SETTINGS_FILE, self.settings)

    def _snip_rename(self, scope, host, old, new):
        """Rename a saved word in place (used by the manager's Edit button).
        `scope` is 'global', 'profile_<pid>' or 'domain'. The star follows the
        word if it was pinned."""
        store = self._snip_store()
        if scope == "global":
            lst = store["global"]
        elif scope.startswith("profile_"):
            lst = store["profiles"].get(scope.split("_", 1)[1], [])
        elif scope == "domain":
            lst = store["domains"].get(clean_host(host), [])
        else:
            return
        if old in lst:
            i = lst.index(old)
            if new in lst:                 # target already present -> just drop old
                lst.pop(i)
            else:
                lst[i] = new
        favs = self._snip_favs()           # keep the ⭐ on the renamed word
        if old in favs:
            j = favs.index(old)
            if new in favs:
                favs.pop(j)
            else:
                favs[j] = new
        save_json(SETTINGS_FILE, self.settings)

    def _ask_words(self, title, label):
        """Prompt for one or more words + a 'comma-separate' checkbox.
        Returns (text, split) or None if cancelled."""
        dlg = QDialog(self)
        dlg.setWindowTitle(title)
        dlg.setStyleSheet(dialog_qss())
        apply_window_icon(dlg)
        QShortcut(QKeySequence("Esc"), dlg, dlg.reject)
        lay = QVBoxLayout(dlg)
        lab = QLabel(label)
        lab.setWordWrap(True)
        lay.addWidget(lab)
        le = QLineEdit()
        le.setMinimumWidth(360)
        le.returnPressed.connect(dlg.accept)
        lay.addWidget(le)
        cb = QCheckBox("Comma-separate into several words  (a, b, c → 3 words)")
        # OFF by default so a phrase that contains a comma (e.g. "Lyrics by X,
        # everything else by Y") is saved as ONE snippet. Remembers your last
        # choice, so the Blocket "brädspel, sällskapsspel" splitter is one tick
        # away and stays on once you use it.
        cb.setChecked(bool(self.settings.get("snip_comma_split", False)))
        lay.addWidget(cb)
        row = QHBoxLayout()
        row.addStretch(1)
        cancel = QPushButton("Cancel")
        cancel.clicked.connect(dlg.reject)
        ok = QPushButton("Save")
        ok.clicked.connect(dlg.accept)
        row.addWidget(cancel)
        row.addWidget(ok)
        lay.addLayout(row)
        le.setFocus()
        if dlg.exec() and le.text().strip():
            split = cb.isChecked()
            self.settings["snip_comma_split"] = split
            save_json(SETTINGS_FILE, self.settings)
            return le.text(), split
        return None

    def _snip_prompt(self, scope, host):
        label = ("Save word(s) for %s:" % self._scope_label(scope, host))
        res = self._ask_words("Save snippet", label)
        if res:
            text, split = res
            self._snip_add_many(scope, host, text, split)

    def _snippets_button_menu(self):
        """The toolbar 📝 button. A pop-up menu that puts the words for the
        ACTIVE PAGE and the words for ALL SITES right at the top - click one and
        it drops straight into the focused field - followed by 'Save a new word…'
        and 'Manage saved words…'. It reads the very same store as the page
        right-click menu's 'Saved words / snippets', so both stay in step."""
        view = self.current_view()
        host = ""
        if view is not None:
            try:
                host = view.url().host().replace("www.", "")
            except Exception:
                host = ""
        favs = list(self._snip_favs())

        m = QMenu(self)
        m.setStyleSheet(self._menu_style(1))

        def add_group(title, words):
            hdr = m.addAction(title)
            hdr.setEnabled(False)                    # a plain, non-clickable header
            if not words:
                a = m.addAction("      (none saved yet)")
                a.setEnabled(False)
                return
            for w in words:
                label = ("  ⭐  " + w[:56]) if w in favs else ("      " + w[:56])
                a = m.addAction(label)
                if view is not None:
                    a.triggered.connect(
                        lambda _=False, t=w, v=view:
                        self._type_into_focused(v, t, fallback=True))
                else:
                    a.setEnabled(False)

        # ---- 1) the two groups the user wants to see first ----
        add_group("🌐  This page  (%s)" % (clean_host(host) or "no page"),
                  self._snips_for_domain(host) if host else [])
        # 'This profile' only appears when it actually holds words, so the common
        # (empty) case stays uncluttered - its words are never lost, they still
        # show here the moment there are any, and always on the page menu.
        prof_words = self._snips_for_profile()
        if prof_words:
            m.addSeparator()
            add_group("👤  This profile  (%s)"
                      % self._active_profile().get("name", "?"), prof_words)
        m.addSeparator()
        add_group("✳  All sites", self._snips_global())

        # ---- 2) save / manage ----
        m.addSeparator()
        newm = m.addMenu("💾  Save a new word…")
        newm.setStyleSheet(self._menu_style(2))
        if host:
            newm.addAction("…for THIS PAGE  (%s)" % (clean_host(host) or "?"),
                           lambda _=False, h=host: self._snip_prompt("domain", h))
        newm.addAction("…for THIS PROFILE", lambda: self._snip_prompt("profile", ""))
        newm.addAction("…for ALL SITES", lambda: self._snip_prompt("global", ""))
        m.addAction("⚙  Manage saved words…", self.manage_snippets)

        m.exec(self._menu_pos(self.btn_snippets))

    def _add_snippets_menu(self, parent_menu, view, sel):
        """Build the '📝 Saved words' slide-out for the page right-click menu."""
        host = view.url().host().replace("www.", "")
        snm = parent_menu.addMenu("📝  Saved words / snippets")
        snm.setStyleSheet(self._menu_style(1))

        # Every saved word lives here, grouped by scope. STARRED words are
        # marked with ⭐ and ALSO appear as one-click rows on the page menu
        # above; un-starred words live only here. (Star / reorder them in
        # "⚙ Manage saved words…".)
        favs = list(self._snip_favs())

        def add_group(title, words, scope, h=""):
            if not words:
                return False
            sub = snm.addMenu(title)
            sub.setStyleSheet(self._menu_style(2))
            for w in words:
                label = ("⭐  " + w[:58]) if w in favs else w[:60]
                a = sub.addAction(label)
                a.triggered.connect(
                    lambda _=False, t=w: self._type_into_focused(view, t, fallback=True))
            return True

        any_words = False
        any_words |= add_group("🌐  This site  (%s)" % (clean_host(host) or "?"),
                               self._snips_for_domain(host), "domain", host)
        any_words |= add_group("👤  This profile  (%s)"
                               % self._active_profile().get("name", "?"),
                               self._snips_for_profile(), "profile")
        any_words |= add_group("✳  All sites", self._snips_global(), "global")

        # Convenience: surface non-secret vault autofill (never the password).
        if self._vault_unlocked and self._vault:
            af = self._vault.get("autofill", {}) or {}
            items = [(k, af.get(k)) for k in ("email", "name", "address", "phone")
                     if af.get(k)]
            if items:
                sub = snm.addMenu("🪪  My details (vault)")
                sub.setStyleSheet(self._menu_style(2))
                for k, v in items:
                    a = sub.addAction("%s:  %s" % (k.title(), v[:30]))
                    a.triggered.connect(
                        lambda _=False, t=v: self._type_into_focused(view, t, fallback=True))
                any_words = True

        if not any_words:
            a = snm.addAction("(no saved words yet — select text, then Save below)")
            a.setEnabled(False)

        snm.addSeparator()
        # Save the SELECTED text directly (three one-hover choices = fewest clicks).
        if sel:
            short = sel if len(sel) <= 24 else sel[:24] + "…"
            snm.addAction('💾  Save "%s" for THIS SITE' % short,
                          lambda _=False, t=sel, h=host: self._snip_add("domain", h, t))
            snm.addAction('💾  Save "%s" for THIS PROFILE' % short,
                          lambda _=False, t=sel: self._snip_add("profile", "", t))
            snm.addAction('💾  Save "%s" for ALL SITES' % short,
                          lambda _=False, t=sel: self._snip_add("global", "", t))
        else:
            newm = snm.addMenu("💾  Save a new word...")
            newm.setStyleSheet(self._menu_style(2))
            newm.addAction("…for THIS SITE", lambda _=False, h=host: self._snip_prompt("domain", h))
            newm.addAction("…for THIS PROFILE", lambda: self._snip_prompt("profile", ""))
            newm.addAction("…for ALL SITES", lambda: self._snip_prompt("global", ""))
        snm.addSeparator()
        snm.addAction("⚙  Manage saved words...", self.manage_snippets)

    def manage_snippets(self):
        # Opening a modal QDialog synchronously inside the triggered-slot of an
        # action from a menu that was just exec()'d over a QWebEngineView can
        # get its show/activate swallowed by the view's native surface on
        # Windows -- the dialog exists but never actually paints/focuses, so
        # the click looks like it did nothing. Deferring one event-loop tick
        # lets the right-click menu fully unwind first, and forcing
        # show/raise/activate before exec() is the standard belt-and-braces
        # fix for that class of bug.
        def _open():
            dlg = SnippetManagerDialog(self)
            dlg.show()
            dlg.raise_()
            dlg.activateWindow()
            dlg.exec()
        QTimer.singleShot(0, _open)

# *************** DEL 52 - FILE SETS (named groups of files for uploads) *****************
    #  Like saved words / snippets, but for FILES. A set is {"name", "files": [paths]}
    #  stored in settings["file_sets"]. Picking one ARMS the bulk-upload queue
    #  (DEL 21J) for ANY site: the next file dialog the page opens is answered with
    #  the set's files instead of showing the dialog. Several-file inputs get the
    #  whole set in one go, which is how chat sites take attachments.
    #  ToDo: per-site default set; drag-out of a set onto a page.
    def _fs_sets(self):
        return self.settings.setdefault("file_sets", [])

    def _fs_save(self):
        save_json(SETTINGS_FILE, self.settings)

    def _fs_find(self, name):
        for s in self._fs_sets():
            if s.get("name") == name:
                return s
        return None

    def _fs_pick_files(self, parent, title):
        start = self.settings.get("fileset_last") or ""
        if not start or not os.path.isdir(start):
            start = os.path.expanduser("~")
        files, _ = QFileDialog.getOpenFileNames(parent, title, start, "All files (*.*)")
        if not files:
            return []
        self.settings["fileset_last"] = os.path.dirname(files[0])
        return [os.path.normpath(f) for f in files]

    def _fs_add_set(self, name, files):
        old = self._fs_find(name)
        if old is not None:
            if QMessageBox.question(
                    self, "File sets",
                    "A set called “%s” already exists.\nReplace its files?" % name
            ) != QMessageBox.StandardButton.Yes:
                return
            old["files"] = list(files)
        else:
            self._fs_sets().append({"name": name, "files": list(files)})
        self._fs_save()
        show_toast(self, "📎  Saved “%s” (%d file%s)"
                   % (name, len(files), "" if len(files) == 1 else "s"))

    def _fs_save_new_prompt(self):
        def _go():
            name, ok = QInputDialog.getText(
                self, "New file set",
                "Name of the set  (e.g. Instruction - Paperdoll):")
            name = (name or "").strip()
            if not ok or not name:
                return
            files = self._fs_pick_files(self, "Pick the files for “%s”" % name)
            if files:
                self._fs_add_set(name, files)
        QTimer.singleShot(0, _go)

    def _fs_existing(self, name):
        """(files that exist, number missing) for a set."""
        s = self._fs_find(name) or {}
        allf = s.get("files", [])
        ok = [f for f in allf if os.path.isfile(f)]
        return ok, len(allf) - len(ok)

    def _fs_use(self, name):
        files, gone = self._fs_existing(name)
        if not files:
            QMessageBox.warning(
                self, "File sets",
                "None of the files in “%s” exist any more.\n"
                "Open ⚙ Manage file sets to fix the list." % name)
            return
        self._upload_queue = list(files)
        self._bulk_total = len(files)
        self._bulk_sent = 0
        self._bulk_host = ""                    # empty = any site
        self._update_upload_marker()
        show_toast(self, "📎  “%s” ready (%d file%s%s) — now press the site's "
                   "attach button" % (name, len(files), "" if len(files) == 1 else "s",
                                      ", %d missing" % gone if gone else ""), 4200)

    def _fs_open_panel(self, name):
        """Open the small always-on-top DRAG panel for a set (one at a time)."""
        files, _gone = self._fs_existing(name)
        if not files:
            QMessageBox.warning(
                self, "File sets",
                "None of the files in “%s” exist any more.\n"
                "Open ⚙ Manage file sets to fix the list." % name)
            return
        old = getattr(self, "_fs_panel", None)
        if old is not None:
            try:
                old.close()
            except Exception:
                pass
        p = FileSetDragPanel(self, name)
        self._fs_panel = p
        p.move(self.btn_filesets.mapToGlobal(QPoint(0, self.btn_filesets.height() + 6)))
        p.show()
        p.raise_()

    def _fs_copy(self, name):
        files, gone = self._fs_existing(name)
        if not files:
            show_toast(self, "No files to copy")
            return
        md = QMimeData()
        md.setUrls([QUrl.fromLocalFile(f) for f in files])
        QApplication.clipboard().setMimeData(md)
        show_toast(self, "📋  %d file%s copied — press Ctrl+V in the page's message box"
                   % (len(files), "" if len(files) == 1 else "s"), 3500)

    def _filesets_button_menu(self):
        sets = self._fs_sets()
        m = QMenu(self)
        m.setStyleSheet(self._menu_style(1))
        hdr = m.addAction("📎  Pick a set: a panel opens to drag its files onto the page")
        hdr.setEnabled(False)
        if not sets:
            m.addAction("      (no file sets yet)").setEnabled(False)
        for s in sets:
            n = len(s.get("files", []))
            _ok, gone = self._fs_existing(s.get("name"))
            a = m.addAction("      %s   (%d file%s%s)"
                            % (s.get("name", "?")[:50], n, "" if n == 1 else "s",
                               ", ⚠ %d missing" % gone if gone else ""))
            a.triggered.connect(
                lambda _=False, nm=s.get("name"): QTimer.singleShot(0, lambda: self._fs_open_panel(nm)))
        m.addSeparator()
        if sets:
            cm = m.addMenu("📋  Copy a set to the clipboard (then Ctrl+V)")
            cm.setStyleSheet(self._menu_style(2))
            for s in sets:
                cm.addAction(s.get("name", "?")[:50],
                             lambda _=False, nm=s.get("name"): self._fs_copy(nm))
        m.addAction("💾  Save a new file set…", self._fs_save_new_prompt)
        m.addAction("⚙  Manage file sets…", self.manage_filesets)
        if getattr(self, "_upload_queue", None):
            m.addSeparator()
            m.addAction("🛑  Cancel the armed upload", self._bulk_stop)
        m.exec(self._menu_pos(self.btn_filesets))

    def manage_filesets(self):
        # Deferred a tick for the same reason as manage_snippets().
        def _open():
            dlg = FileSetManagerDialog(self)
            dlg.show()
            dlg.raise_()
            dlg.activateWindow()
            dlg.exec()
        QTimer.singleShot(0, _open)

    def _bookmark_link(self, url):
        if not url:
            return
        self.bookmarks.setdefault("bar", []).append({"title": url[:40], "url": url})
        self._save_bm()
        self.build_bookmarks_bar()
        show_toast(self, "Link bookmarked")

    def _bookmark_to_unsorted(self, url, title=None):
        if not url:
            return
        menu = self.bookmarks.setdefault("menu", [])
        uns = next((n for n in menu if n.get("title") == "Unsorted" and "folder" in n), None)
        if not uns:
            uns = {"title": "Unsorted", "folder": []}
            menu.insert(0, uns)
        uns["folder"].append({"title": title or url[:40], "url": url})
        self._save_bm()
        self.build_bookmarks_bar()
        show_toast(self, "Bookmarked to Unsorted")

    def _link_folder_picker(self, link, nodes, depth=1):
        """A menu that lets you drop a link into this folder or any subfolder."""
        m = QMenu(self)
        m.setStyleSheet(self._menu_style(depth))
        a = m.addAction("➕  Add to this folder")
        a.triggered.connect(lambda _=False, lst=nodes: self._add_link_to(lst, link))
        subs = [n for n in nodes if "folder" in n]
        if subs:
            m.addSeparator()
        for n in subs:
            sub = self._link_folder_picker(link, n.get("folder", []), depth + 1)
            sub.setTitle("📁  " + (n.get("title") or "Folder")[:30])
            m.addMenu(sub)
        return m

    def _add_link_to(self, folder_list, link):
        title, ok = QInputDialog.getText(self, "Bookmark link", "Name:", text=link[:50])
        if not ok:
            return
        folder_list.append({"title": (title.strip() or link[:40]), "url": link})
        self._save_bm()
        self.build_bookmarks_bar()
        show_toast(self, "Link bookmarked")

    # ----------------------------------------------------- profiles: UI ----
    def _update_profile_badge(self):
        prof = self._active_profile()
        col = prof.get("color", C_ACCENT)
        self.btn_profile.setText(str(prof.get("badge", "?"))[:1] or "?")
        self.btn_profile.setStyleSheet(
            "QPushButton{background:%s; color:%s; border:none; border-radius:15px; "
            "font-weight:bold; font-size:12pt;}QPushButton:hover{border:2px solid %s;}"
            % (col, contrast_fg(col), C_ACCENT))
        self.btn_profile.setToolTip("Profile: %s  (click to switch / manage)"
                                    % prof.get("name", "?"))
        self.setWindowTitle("%s - %s" % (prof.get("name", APP_NAME), APP_NAME))
        self._update_profile_tag()

    def _update_profile_tag(self):
        """The login/name tag between the badge and the address bar (no number)."""
        if not hasattr(self, "btn_profiletag"):
            return
        prof = self._active_profile()
        if not prof.get("show_tag", True):
            self.btn_profiletag.setVisible(False)
            return
        pc = prof.get("color", C_ACCENT)
        label = prof.get("bar_label") or prof.get("name", "")
        login = prof.get("login") or prof.get("name", "")
        self.btn_profiletag.setVisible(bool(label))
        self.btn_profiletag.setText(" %s " % label)
        self.btn_profiletag.setToolTip(
            "Click to type \"%s\" into the field you last clicked" % login)
        self.btn_profiletag.setStyleSheet(
            "QPushButton{background:%s; color:%s; border:none; border-radius:5px; "
            "font-weight:bold; font-size:9pt; padding:3px 10px; margin:0 4px;}"
            "QPushButton:hover{background:%s;}"
            % (pc, contrast_fg(pc), shade(pc, 25)))

    def eventFilter(self, obj, event):
        et = event.type()
        # Custom mouse-wheel scroll speed/length. Only kicks in when the user set a
        # non-default speed; otherwise native scrolling is left completely untouched. We
        # scroll the page via JS by a scaled amount (QtWebEngine eats wheel events,
        # so this is the reliable way). Inner scrollers (Sheets grid) keep native.
        if et == QEvent.Type.Wheel:
            try:
                factor = float(self.settings.get("scroll_speed", 1.0) or 1.0)
                v = self.current_view()
                # Per-site "Fix stuck scrolling here" override (right-click page →
                # Exceptions). Some pages (e.g. Tradera invoices) have an inner
                # scrollable panel whose mouse-wheel Chromium fails to deliver; when
                # forced, we take the wheel and scroll the element under the cursor
                # via SCROLL_BY_JS (which walks to the nearest real scroller), at
                # native distance (factor 1.0) if no custom speed is set.
                # Per-site scroll-speed MULTIPLIER (same menu, "Scroll speed here")
                # stacks on top of the global Settings → Performance speed - e.g.
                # global 1.3x × this site's 2.4x = 3.12x, ONLY on this site. It
                # applies even when the global speed is left at native (1.0x), so
                # a single page can be sped up without touching every other tab.
                forced = False
                site_mult = 1.0
                if v:
                    try:
                        _ov = (self.settings.get("site_overrides") or {}).get(
                            clean_host(v.url().host()), {})
                        forced = bool(_ov.get("force_js_scroll"))
                        site_mult = float(_ov.get("scroll_speed_mult", 1.0) or 1.0)
                    except Exception:
                        forced = False
                        site_mult = 1.0
                if (factor != 1.0 or forced or site_mult != 1.0):
                    eff = (factor if factor != 1.0 else 1.0) * site_mult
                    # React when the wheel happens anywhere over the CURRENT web view
                    # (its render widget), not only when obj is exactly focusProxy —
                    # on some pages the event goes to a different child widget.
                    if v and self._wheel_over_view(obj, v) \
                            and not self._native_scroll_host(v):
                        dy = event.angleDelta().y()
                        dx = event.angleDelta().x()
                        if dy or dx:
                            py = -(dy / 120.0) * 100 * eff
                            px = -(dx / 120.0) * 100 * eff
                            try:
                                p = event.position()
                                cx, cy = int(p.x()), int(p.y())
                            except Exception:
                                cx, cy = 0, 0
                            v.page().runJavaScript(
                                SCROLL_BY_JS % (cx, cy, int(px), int(py)))
                            return True             # consume the native wheel
            except Exception:
                pass
        # Ctrl+F routing (app-wide): pass through to the page on sites with their
        # own find (Sheets/Docs), otherwise open WhyBrowse's find bar.
        if et == QEvent.Type.KeyPress:
            try:
                if (event.key() == Qt.Key.Key_F
                        and event.modifiers() == Qt.KeyboardModifier.ControlModifier):
                    if self._ctrl_f_should_pass_through():
                        return False        # let Chromium/Sheets handle Ctrl+F
                    self.find_bar.open_bar()
                    return True
                # Esc (app-wide, replaces the old QShortcut): close our find bar /
                # leave full screen / stop loading — but on sites with their own
                # find (Sheets/Docs), when there's nothing of OURS to escape, let
                # Esc reach the PAGE so its find box closes (the old shortcut ate
                # it). Guarded so modal dialogs & other windows keep their own Esc.
                if (event.key() == Qt.Key.Key_Escape
                        and event.modifiers() == Qt.KeyboardModifier.NoModifier
                        and QApplication.activeModalWidget() is None
                        and QApplication.activeWindow() in (self, None)):
                    if (not self.find_bar.isVisible() and not self.isFullScreen()
                            and self._ctrl_f_should_pass_through()):
                        return False        # let Sheets/Docs close their own find
                    self.on_escape()
                    return True
            except Exception:
                pass
        # Up / Down in the two small address boxes walks the shared list of what
        # you have TYPED there (DEL 45c). The address completer owns the arrows
        # while its popup is open, so we only take them when it is not showing.
        if et == QEvent.Type.KeyPress and obj in (getattr(self, "quick", None),
                                                  getattr(self, "opentab", None)):
            try:
                k = event.key()
                if (k in (Qt.Key.Key_Up, Qt.Key.Key_Down)
                        and event.modifiers() == Qt.KeyboardModifier.NoModifier):
                    comp = getattr(self, "_completer", None)
                    pop = comp.popup() if comp is not None else None
                    if not (pop is not None and pop.isVisible()):
                        if self._typed_walk(obj, 1 if k == Qt.Key.Key_Up else -1):
                            return True
            except Exception:
                pass
        if obj is getattr(self, "btn_profile", None):
            if et == QEvent.Type.Enter:
                self._profile_hover.start()
            elif et == QEvent.Type.Leave:
                self._profile_hover.stop()
        return super().eventFilter(obj, event)

    # Canvas-grid web apps that manage their OWN wheel scrolling (the scroll-speed
    # override's JS scroll is unreliable there + fought with the cell jump). Let the
    # native wheel through on these so their scrolling always works.
    _NATIVE_SCROLL_HOSTS = ("docs.google.com", "sheets.google.com",
                            "slides.google.com", "drive.google.com")

    def _native_scroll_host(self, view):
        try:
            u = view.url()
            # The built-in PDF viewer (pdfium) manages its OWN wheel scrolling and
            # our JS scroll can't reach it, so a custom scroll-speed would eat the
            # wheel and the PDF wouldn't move (the two-scrollbar PDFs). Always let
            # the native wheel through when a .pdf is being viewed directly.
            if u.path().lower().endswith(".pdf"):
                return True
            host = clean_host(u.host())
            return any(host == d or host.endswith("." + d)
                       for d in self._NATIVE_SCROLL_HOSTS)
        except Exception:
            return False

    def _wheel_over_view(self, obj, view):
        """True if a wheel event's target `obj` belongs to `view` (the web view or
        any of its child render widgets). Walks the parent chain a few levels."""
        try:
            w = obj
            for _ in range(8):
                if w is None:
                    return False
                if w is view:
                    return True
                w = w.parent()
        except Exception:
            pass
        return False

    def _ctrl_f_should_pass_through(self):
        """True on sites that own Ctrl+F (Google Sheets/Docs/Notion/…): let the key
        reach the page instead of opening our find bar — no synthetic key needed."""
        try:
            v = self.current_view()
            if not v:
                return False
            host = v.url().host().lower()
            if host.startswith("www."):
                host = host[4:]
            for dom in self.settings.get("native_find_domains", []):
                dom = dom.strip().lower()
                if dom and (host == dom or host.endswith("." + dom)):
                    return True
        except Exception:
            pass
        return False

    def _hover_full_menu(self):
        """Hover the badge circle -> the full profile menu (everything)."""
        if self.btn_profile.underMouse():
            self._popup_hover_menu(self._build_profile_menu(), self.btn_profile)

    def _popup_hover_menu(self, menu, anchor=None, gpos=None, region=None):
        """Show a hover menu WITHOUT blocking, and auto-close it once the mouse
        leaves both the trigger area and the menu (no click needed to dismiss).
        Trigger is either a widget `anchor` or a global QRect `region`."""
        old = getattr(self, "_hover_menu", None)
        if old is not None:
            try:
                old.close()
            except Exception:
                pass
        self._hover_menu = menu
        self._hover_anchor = anchor
        self._hover_region = region
        menu.popup(gpos or self._menu_pos(anchor))
        self._hover_watch.start()

    def _check_hover_menu(self):
        m = getattr(self, "_hover_menu", None)
        if m is None or not m.isVisible():
            self._hover_watch.stop()
            return
        gp = QCursor.pos()
        anchor = getattr(self, "_hover_anchor", None)
        region = getattr(self, "_hover_region", None)
        over_trigger = bool(anchor and anchor.rect().contains(anchor.mapFromGlobal(gp))) \
            or bool(region and region.contains(gp))
        if not (over_trigger or m.geometry().contains(gp)):
            m.close()
            self._hover_watch.stop()

    def _hover_tab_quicklinks(self, idx):
        """Hover a tab -> its saved quick links (only if it has any)."""
        view = self.tabs.widget(idx)
        if not view or not self._quicklinks_for(view.url().host()):
            return
        bar = self.tabs.tabBar()
        r = bar.tabRect(idx)
        gpos = bar.mapToGlobal(r.topRight() if self.settings.get("tab_position") == "left"
                               else r.bottomLeft())
        region = QRect(bar.mapToGlobal(r.topLeft()), r.size())
        self._popup_hover_menu(self._build_quicklinks_menu(view), gpos=gpos, region=region)

    def _click_profile_circle(self):
        """Left-click the badge circle -> quick switch to another profile."""
        self._profile_hover.stop()
        old = getattr(self, "_hover_menu", None)
        if old is not None:
            try:
                old.close()
            except Exception:
                pass
        menu = QMenu(self)
        menu.setStyleSheet(self._menu_style())
        for p in self.settings.get("profiles", []):
            if not p.get("enabled", True):
                continue
            a = menu.addAction("%s  %s" % (p.get("badge", "?"), p.get("name", "?")))
            a.setEnabled(p["id"] != self.active_id)
            a.triggered.connect(lambda _=False, pid=p["id"]: self.switch_profile(pid))
        menu.exec(self._menu_pos(self.btn_profile))

    def _switch_profile_index(self, i):
        profs = [p for p in self.settings.get("profiles", []) if p.get("enabled", True)]
        if 0 <= i < len(profs):
            self.switch_profile(profs[i]["id"])

    def show_profile_menu(self):
        self._build_profile_menu().exec(self._menu_pos(self.btn_profile))

    def _build_profile_menu(self):
        menu = QMenu(self)
        menu.setStyleSheet(self._menu_style())
        menu.addAction("👤  Profiles").setEnabled(False)
        menu.addSeparator()
        for p in self.settings.get("profiles", []):
            mark = "● " if p["id"] == self.active_id else "   "
            paused = "  (paused)" if not p.get("enabled", True) else ""
            a = menu.addAction("%s%s [%s]%s" % (mark, p.get("name", "?"),
                                                p.get("badge", "?"), paused))
            if p["id"] == self.active_id or not p.get("enabled", True):
                a.setEnabled(p.get("enabled", True))
            a.triggered.connect(lambda _=False, pid=p["id"]: self.switch_profile(pid))
        menu.addSeparator()
        a_def = menu.addAction("🎯  Always start with this profile")
        a_def.setCheckable(True)
        a_def.setChecked(self.settings.get("default_profile") == self.active_id)
        a_def.triggered.connect(
            lambda v: self._set_default_profile(self.active_id if v else None))
        menu.addSeparator()
        # ---- The generated 99 Favourites profile (DEL 21H) ----
        a_fav = menu.addAction("⭐  Show the “99 Favourites” profile")
        a_fav.setCheckable(True)
        a_fav.setChecked(bool(self.settings.get("fav_profile_enabled", True)))
        a_fav.setToolTip("A profile whose bookmarks ARE your starred list. Each "
                         "link still opens with the account it was saved under.")
        a_fav.triggered.connect(self._toggle_fav_profile)
        menu.addSeparator()
        menu.addAction("➕  New profile...", self.new_profile)
        menu.addAction("✎  Edit this profile...", lambda: self.edit_profile(self.active_id))
        cur = self._active_profile()
        if cur.get("enabled", True):
            menu.addAction("⏸  Pause this profile", lambda: self.set_profile_enabled(self.active_id, False))
        menu.addAction("🗑  Delete this profile...", lambda: self.delete_profile(self.active_id))
        # ---- DEL 55 - RESTART: things that stopped half-way ----
        # One place for "this was interrupted, start it again". Only torrents
        # for now; add further restartable things below the same header.
        menu.addSeparator()
        menu.addAction("🔄  Restart").setEnabled(False)
        n_t = self._torrents_to_restart()
        if n_t:
            menu.addAction("🧲  Restart %d unfinished torrent%s" % (n_t, "" if n_t == 1 else "s"),
                           self._restart_torrents)
            menu.addAction("🧲  Forget the stopped torrents (keep their files)",
                           self._forget_waiting_torrents)
        else:
            menu.addAction("🧲  Torrents: nothing to restart").setEnabled(False)
        return menu

    # *************** DEL 55 - RESTART UNFINISHED TORRENTS (profile circle) *****************
    def _torrents_to_restart(self):
        """Number of unfinished torrents that are remembered but not running (or
        paused). Cheap: reads the small torrents.json when no engine exists yet."""
        try:
            eng = self.torrent_engine(create=False)
            if eng is None:
                return len([r for r in TorrentEngine.saved_items() if not r.get("done")])
            return eng.restart_count()
        except Exception as e:
            log_line("restart count failed: %s" % e)
            return 0

    def _restart_torrents(self):
        eng = self.torrent_engine()
        started, problems = eng.restart_all()
        if started:
            show_toast(self, "🧲  Restarted %d torrent%s" % (started, "" if started == 1 else "s"), 2500)
        if problems:
            QMessageBox.warning(self, "Restart torrents",
                                "These could not be started (they stay in the list, so you "
                                "can try again, for example when the drive is plugged in):\n\n"
                                + "\n\n".join(problems[:8]))
        self.open_torrent_manager()

    def _forget_waiting_torrents(self):
        eng = self.torrent_engine()
        n = len(eng.waiting)
        if n == 0:
            show_toast(self, "Nothing to forget (paused torrents are in the Torrents window)")
            return
        q = QMessageBox.question(
            self, "Forget stopped torrents",
            "Forget %d stopped torrent%s?\n\nThe files already downloaded stay on disk; "
            "only the entry in WhyBrowse's list is removed." % (n, "" if n == 1 else "s"),
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            QMessageBox.StandardButton.No)
        if q == QMessageBox.StandardButton.Yes:
            eng.forget_waiting()
            show_toast(self, "Forgot %d stopped torrent%s" % (n, "" if n == 1 else "s"))

    def _set_default_profile(self, pid):
        self.settings["default_profile"] = pid
        save_json(SETTINGS_FILE, self.settings)
        if pid:
            show_toast(self, "“%s” will start by default" %
                       self._profile_by_id(pid).get("name", "?"))
        else:
            show_toast(self, "Default startup profile cleared")

    def switch_profile(self, pid):
        if pid == self.active_id:
            return
        target = self._profile_by_id(pid)
        if not target.get("enabled", True):
            show_toast(self, "That profile is paused")
            return
        # ---- timing instrumentation --------------------------------------
        # A switch that takes many SECONDS while CPU sits at 0% is an I/O
        # stall somewhere, not slow computation — no amount of "just refresh"
        # fixes that, you have to find the stalling step. This breaks the
        # switch into named laps and logs any lap over 0.15s, so the next
        # slow switch tells you exactly which step it was in
        # Helpfiles/0---Empty/whybrowse_log.txt, instead of having to guess.
        # Overhead when everything is fast: a handful of perf_counter()
        # calls, immeasurably small. Safe to remove once the cause is found.
        _t0 = time.perf_counter()
        _lap_t = [_t0]

        def _lap(label):
            now = time.perf_counter()
            dt = now - _lap_t[0]
            if dt > 0.15:
                log_line("switch_profile SLOW STEP: %-32s %.2fs" % (label, dt))
            _lap_t[0] = now
        # --------------------------------------------------------------------
        self._log_activity(
            "profile-switch",
            detail="%s -> %s" % (self._active_profile().get("name", self.active_id),
                                 target.get("name", pid)))
        _lap("log-activity")
        # 1) save the current profile's tabs + data (+ vault, if unlocked)
        self._stash_current_tabs()
        _lap("stash-current-tabs")
        self._save_profile_data()
        _lap("save-profile-data (bookmarks+history to disk)")
        was_unlocked = self._vault_unlocked
        if was_unlocked:
            self._save_vault()
            _lap("save-vault")
        # 2) detach current tabs. If "keep alive" is on we KEEP the view widgets
        #    alive (removeTab does NOT destroy them) and stash them per profile, so
        #    returning to this profile shows the exact same pages with scroll/state
        #    intact — no reload. Otherwise we destroy them (old low-memory behaviour).
        keep_alive = bool(self.settings.get("keep_profile_tabs_alive", True))
        kept = []
        while self.tabs.count():
            w = self.tabs.widget(0)
            self.tabs.removeTab(0)
            if not w:
                continue
            if keep_alive and not getattr(w, "_ephemeral", False):
                try:                          # silence a backgrounded profile's
                    if w.page():              # media (e.g. YouTube) while hidden
                        w.page().setAudioMuted(True)
                except Exception:
                    pass
                kept.append(w)
            else:
                self._kill_view_media(w)
                w.deleteLater()
        if keep_alive:
            # Drop any previously-kept views for THIS profile we didn't re-show,
            # then store the fresh set.
            for old in self.live_views.get(self.active_id, []):
                if old not in kept:
                    try:
                        old.deleteLater()
                    except Exception:
                        pass
            self.live_views[self.active_id] = kept
        _lap("detach-tabs (%d kept alive)" % len(kept))
        # 3) activate the new profile
        self.active_id = pid
        self.settings["active_profile"] = pid
        self.engine = self._get_engine(pid)
        self.profile = self.engine
        _lap("get-engine (builds it, incl. cookie copy, on first use this session)")
        self._load_profile_data()
        _lap("load-profile-data (bookmarks+history from disk)")
        self._apply_privacy()          # apply this profile's clean state
        _lap("apply-privacy")
        self.build_bookmarks_bar()
        _lap("build-bookmarks-bar")
        self._update_profile_badge()
        self._build_completer()        # refresh suggestions for this profile
        _lap("update-badge+build-completer")
        # Carry the unlocked vault over to this profile (using the cached PIN).
        if was_unlocked:
            self._load_vault_for_active()
            _lap("load-vault-for-active")
        self._paint_vault_button()
        # 4) restore that profile's tabs. If we kept its views alive from a
        #    previous switch this session, just re-attach them (instant, no reload,
        #    scroll/state preserved). Otherwise recreate them from saved URLs.
        live = self.live_views.pop(pid, None) if keep_alive else None
        if live:
            for w in live:
                if w is None:
                    continue
                try:                          # un-mute now that it's foreground
                    if w.page():
                        w.page().setAudioMuted(False)
                except Exception:
                    pass
                self.tabs.addTab(w, "")
                self._refresh_tab_label(w)
        else:
            items = self.runtime_tabs.get(pid)
            if items is None:
                items = [x for x in (target.get("last_tabs") or []) if x]
            for it in items:
                if is_dead_restore_url(_saved_tab_url(it)):   # skip dead error pages
                    continue
                self._add_saved_tab(it)
        _lap("restore-tabs (%s)"
             % ("re-attached live views" if live else "recreated from saved URLs"))
        self._open_autostart_bookmarks()
        _lap("open-autostart-bookmarks")
        if self.tabs.count() == 0:
            self.new_tab(switch=False)
        # Which tab to land on:
        #   1) an explicit "always start on tab N" for this profile, if set
        #   2) otherwise, wherever we were last in this profile (this session
        #      first, falling back to what was saved from last time WhyBrowse ran)
        #   3) clamped to a valid index in case tabs shifted around
        fixed = target.get("fixed_start_tab")
        if isinstance(fixed, int) and 0 <= fixed < self.tabs.count():
            want_idx = fixed
        else:
            want_idx = self.runtime_tab_index.get(pid, target.get("last_active_tab_index", 0))
        if not isinstance(want_idx, int) or not (0 <= want_idx < self.tabs.count()):
            want_idx = 0
        prev_idx = self.tabs.currentIndex()
        self.tabs.setCurrentIndex(want_idx)
        if self.tabs.currentIndex() == prev_idx:
            # Qt's currentChanged signal (which on_tab_changed listens on) only
            # fires when the index actually CHANGES. Re-adding this profile's
            # tabs above already made the first one current (index 0) via Qt's
            # own addTab bookkeeping, so whenever the tab you're meant to land
            # on IS index 0 - the everyday case: your main/first tab in a
            # profile, or simply no saved "last active tab" - setCurrentIndex()
            # above is a silent no-op and on_tab_changed never runs. THIS is why
            # returning to a profile could leave an Auto-refresh (or a sleeping)
            # tab stale until a manual Ctrl+R: the "you're back" check simply
            # never fired. Call it directly so a profile switch always gets the
            # same treatment as clicking a different tab by hand.
            self.on_tab_changed(self.tabs.currentIndex())
        _lap("land-on-tab (on_tab_changed)")
        self._update_identity_tab_flag()       # re-evaluate for the new tab set
        save_json(SETTINGS_FILE, self.settings)
        _lap("save-settings-json")
        show_toast(self, "Profile: %s" % target.get("name", pid))
        _total = time.perf_counter() - _t0
        if _total > 3.0:
            log_line("switch_profile TOTAL: %.2fs — see the SLOW STEP line(s) "
                      "just above this for where it went" % _total)
            show_toast(self, "(Profile switch took %.0fs — slow step logged)"
                       % _total)

    def _stash_current_tabs(self):
        items = []
        for i in range(self.tabs.count()):
            v = self.tabs.widget(i)
            if v and not getattr(v, "_ephemeral", False):   # quick-link sub-tabs aren't saved
                # Temp tabs are throw-away by definition; keeping them is opt-out.
                if (getattr(v, "_is_temp", False)
                        and not self.settings.get("temp_tab_restore", True)):
                    continue
                # A fallback-slept tab sits on about:blank - save its real URL.
                u = getattr(v, "_sleep_url", None) or v.url().toString()
                if (u and not u.startswith("about:") and not is_blank_page(u)
                        and not is_dead_restore_url(u)):   # never re-save dead error pages
                    items.append({"url": u, "lock": self._lock(v),
                                  "pinned": bool(getattr(v, "_pinned", False)),
                                  "temp": bool(getattr(v, "_is_temp", False)),
                                  "pin_url": getattr(v, "_pin_url", None),
                                  "autorefresh": bool(getattr(v, "_auto_refresh", False)),
                                  "nosleep": bool(getattr(v, "_no_sleep", False)),
                                  "sleepmin": int(getattr(v, "_sleep_min", 0) or 0),
                                  "container": getattr(v, "_container", None),
                                  "title": getattr(v, "_custom_title", None)})
        self.runtime_tabs[self.active_id] = items
        self._active_profile()["last_tabs"] = items
        # Remember which tab was focused, so switching back to this profile
        # later can return to where the user actually was, not just tab 0.
        cur_idx = self.tabs.currentIndex()
        self.runtime_tab_index[self.active_id] = cur_idx
        self._active_profile()["last_active_tab_index"] = cur_idx

    def _add_saved_tab(self, item):
        """Recreate a tab from a saved entry, restoring its lock level + pin."""
        if isinstance(item, dict):
            # A pinned tab restores to the page you CHOSE when you pinned it
            # (pin_url), not wherever it happened to drift to — so a pinned page
            # is always the one you picked, even after logout/login.
            pin_url = item.get("pin_url")
            load_url = (pin_url if (item.get("pinned") and pin_url)
                        else item.get("url"))
            # Restore a container tab onto its own cookie store (keeps its login).
            v = self.add_tab(load_url, switch=False,
                             container=item.get("container"))
            try:
                v.page().lock_level = int(item.get("lock", 0))
            except Exception:
                pass
            if item.get("pinned"):
                v._pinned = True
                v._pin_url = pin_url or item.get("url")
                try:
                    v.page().keep_pinned = True
                except Exception:
                    pass
            if item.get("temp"):
                self._mark_temp(v, True, quiet=True)
            if item.get("autorefresh"):
                v._auto_refresh = True
            # rev87: "nosleep" is the saved flag now. An old entry's
            # "autosleep" is deliberately NOT read - it meant the opposite,
            # and every tab starts sleeping-allowed after the turnaround.
            if item.get("nosleep"):
                v._no_sleep = True
            if item.get("sleepmin"):
                v._sleep_min = int(item["sleepmin"])
            if item.get("title"):
                v._custom_title = item["title"]
                # Remember the domain so the one-off name isn't dropped the
                # instant the restored tab finishes loading.
                v._custom_title_host = clean_host(QUrl(item.get("url", "")).host())
            self._refresh_tab_label(v)
            return v
        return self.add_tab(item, switch=False)   # old format: plain url string

    def new_profile(self):
        import uuid
        pid = "p" + uuid.uuid4().hex[:8]
        n = len(self.settings["profiles"]) + 1
        prof = {"id": pid, "name": "Profile %d" % n,
                "color": "#7c5cff", "badge": str(n)[-1], "enabled": True,
                "shared_bookmarks": False, "last_tabs": []}
        dlg = ProfileEditDialog(self, prof, is_new=True)
        if dlg.exec():
            self.settings["profiles"].append(dlg.result_profile())
            save_json(SETTINGS_FILE, self.settings)
            self.switch_profile(pid)

    def edit_profile(self, pid):
        prof = self._profile_by_id(pid)
        dlg = ProfileEditDialog(self, dict(prof), is_new=False)
        if dlg.exec():
            prof.update(dlg.result_profile())
            save_json(SETTINGS_FILE, self.settings)
            if prof.get("shared_bookmarks") is not None:
                self._load_profile_data()
            self.apply_theme()             # picks up per-profile bar colours
            self._update_profile_badge()
            show_toast(self, "Profile saved")

    def set_profile_enabled(self, pid, enabled):
        enabled_count = len([p for p in self.settings["profiles"] if p.get("enabled", True)])
        if not enabled and enabled_count <= 1:
            QMessageBox.information(self, "Profiles",
                                    "You can't pause the only active profile.")
            return
        self._profile_by_id(pid)["enabled"] = enabled
        save_json(SETTINGS_FILE, self.settings)
        if not enabled and pid == self.active_id:
            # switch to the first other enabled profile
            for p in self.settings["profiles"]:
                if p.get("enabled", True) and p["id"] != pid:
                    self.switch_profile(p["id"])
                    break
        show_toast(self, "Profile %s" % ("paused" if not enabled else "resumed"))

    def delete_profile(self, pid):
        if len(self.settings["profiles"]) <= 1:
            QMessageBox.information(self, "Profiles", "You can't delete the last profile.")
            return
        prof = self._profile_by_id(pid)
        # Profile 99 is generated, so "delete" here means "stop showing it" -
        # and it must NOT go through the delete-its-data path below (DEL 21H).
        if self._is_fav_profile(prof):
            ans = QMessageBox.question(
                self, "Favourites profile",
                "Remove the “99 Favourites” profile from the profile list?\n\n"
                "Your favourites themselves are NOT deleted - they stay in the\n"
                "⭐ Favourites button, Ctrl+Shift+B and the ☰ menu. You can bring\n"
                "the profile back from the profile menu at any time.",
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)
            if ans == QMessageBox.StandardButton.Yes:
                self._toggle_fav_profile(False)
            return
        ans = QMessageBox.question(
            self, "Delete profile",
            "Delete profile '%s' and all its data (cookies, logins, history)?\n"
            "This cannot be undone." % prof.get("name", pid),
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)
        if ans != QMessageBox.StandardButton.Yes:
            return
        # switch away first if it's the active one
        if pid == self.active_id:
            for p in self.settings["profiles"]:
                if p["id"] != pid and p.get("enabled", True):
                    self.switch_profile(p["id"])
                    break
            else:
                # no other enabled profile: enable the first other one
                other = next(p for p in self.settings["profiles"] if p["id"] != pid)
                other["enabled"] = True
                self.switch_profile(other["id"])
        # drop the engine + delete its folder (never the shared 'default' dirs)
        self.engines.pop(pid, None)
        self.runtime_tabs.pop(pid, None)
        for w in self.live_views.pop(pid, []):     # free any kept-alive views
            try:
                w.deleteLater()
            except Exception:
                pass
        self.settings["profiles"] = [p for p in self.settings["profiles"] if p["id"] != pid]
        if pid != "default":
            try:
                shutil.rmtree(os.path.join(PROFILES_DIR, pid), ignore_errors=True)
            except Exception as e:
                log_line("delete profile dir failed: {}".format(e))
        save_json(SETTINGS_FILE, self.settings)
        show_toast(self, "Profile deleted")

    def set_home_to_current(self):
        view = self.current_view()
        if view:
            self.settings["home_url"] = view.url().toString()
            save_json(SETTINGS_FILE, self._collect_settings())
            show_toast(self, "Home page updated")

    def show_about(self):
        AboutDialog(self).exec()

    def show_engine_info(self):
        """Show which Chromium engine is baked in, with a one-click pip update +
        a link to Chrome's release blog (works when running from the .py)."""
        chrome = qWebEngineChromiumVersion()
        patch = qWebEngineChromiumSecurityPatchVersion()
        qtwe = qWebEngineVersion()
        dlg = QDialog(self)
        dlg.setWindowTitle("Browser engine")
        dlg.setStyleSheet(dialog_qss())
        apply_window_icon(dlg)
        dlg.resize(640, 470)
        lay = QVBoxLayout(dlg)
        info = QLabel(
            "• Chromium base version:  %s\n"
            "• Security-patched up to:  %s\n"
            "• Qt WebEngine version:    %s" % (chrome, patch, qtwe))
        info.setWordWrap(True)
        info.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
        lay.addWidget(info)
        blog = QLabel('<a href="https://chromereleases.googleblog.com/">'
                      '🔗  Chrome release blog (see the latest Chromium version)</a>')
        blog.setOpenExternalLinks(True)
        lay.addWidget(blog)
        lay.addWidget(EngineUpdatePanel(dlg))       # shared: copyable cmd + .bat
        lay.addStretch(1)
        row = QHBoxLayout()
        row.addStretch(1)
        bclose = QPushButton("Close")
        bclose.clicked.connect(dlg.accept)
        row.addWidget(bclose)
        lay.addLayout(row)
        QShortcut(QKeySequence("Esc"), dlg, dlg.accept)
        self._eng_dialog = dlg
        dlg.exec()

    def show_help(self):
        HelpDialog(self).exec()

    # ----------------------------------------------------- helpers ----
    def _menu_bg(self, depth):
        """Background for a menu nesting level, derived from the ACTIVE theme
        (each level a touch more contrast). Follows Dark / Light / White."""
        base = C_BAR_BG
        try:
            h = base.lstrip("#")
            lum = 0.299 * int(h[0:2], 16) + 0.587 * int(h[2:4], 16) + 0.114 * int(h[4:6], 16)
        except Exception:
            lum = 30
        # On a dark theme each deeper level gets lighter; on a light theme darker.
        return shade(base, depth * 14 if lum < 128 else -depth * 12)

    def _menu_style(self, depth=0):
        return ("QMenu{background:%s; color:%s; border:1px solid %s;}"
                "QMenu::item{padding:6px 22px;}"
                "QMenu::item:selected{background:%s; color:%s;}"
                "QMenu::item:disabled{color:%s;}"
                % (self._menu_bg(depth), C_BAR_FG, C_BORDER,
                   C_ACCENT, C_ACCENT_FG, C_STATUS_FG))

    def _menu_pos(self, button):
        return button.mapToGlobal(QPoint(0, button.height()))

    def _refresh_current(self):
        view = self.current_view()
        if view:
            view.reload()

    # ----------------------------------------------------- privacy / content ----
    def _clean_active(self):
        """Clean mode is on if the GLOBAL switch or the ACTIVE profile's own
        switch is set. (One profile is active per window, so this is exact.)"""
        return bool(self.settings.get("clean_mode")) or \
            bool(self._active_profile().get("clean"))

    def _site_override(self, host):
        """Return the per-site exception dict for host (longest suffix match)."""
        if not host:
            return {}
        host = host.lower().replace("www.", "")
        best = {}
        best_len = -1
        for dom, ov in (self.settings.get("site_overrides") or {}).items():
            d = dom.lower()
            if (host == d or host.endswith("." + d)) and len(d) > best_len:
                best, best_len = ov, len(d)
        tmp = self._crash_overrides(host) if getattr(self, "_crash_off", None) else None
        if tmp:                                      # DEL 56: temporary "Try without..." switches
            best = dict(best or {})
            best.update(tmp)
        return best or {}

    def _apply_js_for_host(self, page, host):
        """NoScript-style: enable/disable JavaScript for this page based on the
        site's 'scripts_enabled' exception (default ON). Called from the page's
        acceptNavigationRequest so it takes effect BEFORE the page loads."""
        host = clean_host(host)
        want = True
        if host and not self._clean_active():
            want = bool(self._site_override(host).get("scripts_enabled", True))
        try:
            page.settings().setAttribute(
                QWebEngineSettings.WebAttribute.JavascriptEnabled, want)
        except Exception:
            pass

    def _cookie_filter(self, request):
        """Return False to block a cookie. Blocks third-party (cross-site) ones."""
        try:
            if self._clean_active():
                return True                        # clean mode: never block
            # Allow cookies on login pages AND for identity providers (Google,
            # Microsoft, Apple...) - blocking those breaks/skews their sign-in.
            # Also allow the cookie's OWN origin if it's a recognized payment
            # provider (PayPal, Klarna, Stripe, Adyen, Trustly...): their
            # checkout iframe/popup sets a session cookie that is third-party
            # from the merchant's page, and blocking it stalls the final
            # "confirm payment" step with no visible error (reported: PayPal's
            # last step just hangs). Same root cause as the Epic Games /
            # Arkose Labs fix above, applied to checkout flows.
            fp = request.firstPartyUrl.host()
            og = request.origin.host()
            if (is_login_host(fp) or is_identity_host(fp) or is_identity_host(og)
                    or is_payment_host(og)):
                return True
            # Human-verification widgets (Cloudflare Turnstile, hCaptcha,
            # reCAPTCHA, Arkose, DataDome...) live in an iframe on their OWN
            # domain, so their session cookie is third-party from the site you
            # are on. Block it and the widget cannot remember which puzzle it
            # gave you, so it never accepts you - the "Verify you are human"
            # loop. Let the challenge's own cookie through (both directions).
            if is_challenge_host(og) or is_challenge_host(fp):
                return True
            ov = self._site_override(fp)
            block3p = ov.get("block_third_party_cookies",
                             self.settings.get("block_third_party_cookies", True))
            if block3p and request.thirdParty:
                # "Stay signed in": while ANY Google/Microsoft/identity tab is open,
                # don't block third-party cookies at all. Their silent re-auth runs
                # through cross-site cookies, and blocking it is what makes pinned
                # Google Sheets/Drive go blank and demand a fresh login.
                if (self.settings.get("stay_signed_in", True)
                        and getattr(self, "_has_identity_tab", False)):
                    return True
                return False
        except Exception:
            pass
        return True

    def _update_identity_tab_flag(self):
        """Cache whether any open tab is a Google/Microsoft/identity site, so the
        per-cookie filter stays fast (it just reads the flag)."""
        flag = False
        try:
            for i in range(self.tabs.count()):
                v = self.tabs.widget(i)
                if v and is_identity_host(v.url().host()):
                    flag = True
                    break
        except Exception:
            pass
        self._has_identity_tab = flag

    def _engine_default_ua(self):
        """The engine's own, untouched user agent (still carrying QtWebEngine/..).
        Taken from the pristine copy WhyBrowse keeps (see _effective_user_agent)
        or, before that exists, from Qt's default profile, which WhyBrowse never
        writes to. "" if neither can be read."""
        ua = _PRISTINE_UA
        if not ua:
            try:
                ua = QWebEngineProfile.defaultProfile().httpUserAgent()
            except Exception:
                ua = ""
        return (ua or "").strip()

    def _site_ua_map(self):
        """{domain: user-agent} for every site with its own identity (DEL 53),
        plus the built-in engine identity for Amazon shops (DEL 58)."""
        out = {}
        # DEL 58 first, so an explicit choice of yours (below) replaces it.
        eua = self._engine_default_ua()
        if eua and "QtWebEngine/" in eua:
            for dom in ENGINE_UA_DOMAINS:
                out[dom] = eua
        for dom, ov in (self.settings.get("site_overrides") or {}).items():
            ua = ov.get("user_agent") if isinstance(ov, dict) else None
            if isinstance(ua, str) and ua.strip():
                out[dom.lower().replace("www.", "")] = ua.strip()
        return out

    def _content_cfg(self):
        # Clean mode = a plain browser: no injected scripts do anything at all.
        if self._clean_active():
            return {"freeze": False, "hideNags": False, "noPasskeys": False,
                    "fixGoogleLogin": False, "autoCookies": False, "spoof": False,
                    "scrollGuard": False, "keepScroll": False,
                    "chromeIdentity": False,
                    "siteUA": self._site_ua_map(),     # an explicit choice, kept in Plain mode
                    "lat": None, "lon": None, "searchBlock": [], "elementHide": []}
        sp = self.settings.get("spoof_location", {}) or {}
        spoof_on = bool(sp.get("enabled", False))
        return {
            "freeze": bool(self.settings.get("freeze_animations", True)),
            "freezeHard": bool(self.settings.get("freeze_js_animations", False)),
            "hideNags": bool(self.settings.get("hide_nag_banners", True)),
            "hideSearchAds": bool(self.settings.get("hide_search_ads", True)),
            "noPasskeys": bool(self.settings.get("disable_passkeys", True)),
            "fixGoogleLogin": bool(self.settings.get("fix_google_login", True)),
            "autoCookies": bool(self.settings.get("auto_accept_cookies", True)),
            "scrollGuard": bool(self.settings.get("scroll_guard", True)),
            "keepScroll": bool(self.settings.get("keep_scroll", True)),
            "spoof": spoof_on,
            "lat": sp.get("lat") if spoof_on else None,
            "lon": sp.get("lon") if spoof_on else None,
            "searchBlock": list(self.settings.get("search_block_domains", [])),
            "elementHide": list(self.settings.get("element_hide_rules", [])),
            "autosaveLogin": bool(self.settings.get("vault_autosave", True)),
            "stick": list(self.settings.get("sticky_rules", [])),
            "freezeEls": list(self.settings.get("freeze_rules", [])),
            "siteOverrides": self._crash_merged_overrides(),
            "crashOff": {h: sorted(t) for h, t in (getattr(self, "_crash_off", None) or {}).items()
                         if any(x.startswith("hide:") or x == "stick" for x in t)},
            "siteUA": self._site_ua_map(),             # per-site identity (DEL 53)
            "forced": self.settings.get("forced_colors", {}) or {},
            # Single source of truth for the cosmetic payment-safe check: the JS
            # no longer hand-copies these. payHosts = whole-domain payment hosts
            # (PAYMENT_DOMAINS); payPathHosts = merchant hosts that are only a
            # payment page under specific path prefixes (PAYMENT_PATH_HOSTS).
            "payHosts": list(PAYMENT_DOMAINS),
            "payPathHosts": [[h, list(prefixes)]
                             for h, prefixes in PAYMENT_PATH_HOSTS],
            # Hosts that serve human-verification widgets (see CHALLENGE_DOMAINS):
            # the cosmetic scripts must leave those pages completely alone.
            "chalHosts": list(CHALLENGE_DOMAINS),
            # The Chrome major version our user-agent STRING claims. The injected
            # script uses it to make navigator.userAgentData claim the same thing
            # (see UA_CH_FIX in GEO_SCRIPT) - otherwise the two disagree and bot
            # checks flag us instantly.
            "uaMajor": self._ua_chrome_major(),
            # ---- Chrome identity (DEL 50) ----
            # chBrands is the SINGLE source for both the Sec-CH-UA headers and
            # navigator.userAgentData, so the two can never contradict each
            # other; navLangs is derived from the Accept-Language header we send.
            "chromeIdentity": self._brand_fix_on(),
            "chBrands": chrome_brand_list(self._ua_chrome_major(),
                                          self._chrome_full_version()),
            "navLangs": accept_language_list(
                (self.settings.get("accept_language") or "").strip()
                or ACCEPT_LANGUAGE),
            "chHints": chrome_high_entropy_hints(),
        }

    def _guard_src(self, src, *kinds):
        """DEL 56: make an injected script skip the hosts that have switched this
        kind of script off (or "scripts" = all of them). Unchanged (the very same
        text) while nothing is switched off, which is nearly always."""
        hosts = self._crash_hosts_with("scripts", *kinds) if getattr(
            self, "_crash_off", None) else []
        if not hosts:
            return src
        return ("if(!(%s.some(function(d){var h=(location.hostname||'').replace(/^www\\./,'');"
                "return h===d||h.endsWith('.'+d);}))){\n%s\n}" % (json.dumps(hosts), src))

    def _install_scripts(self, engine):
        """Install the injected JavaScript on one engine from current settings."""
        cfg = json.dumps(self._content_cfg())
        scripts = engine.scripts()
        scripts.clear()

        geo = QWebEngineScript()
        geo.setName("whybrowse-geo")
        geo.setInjectionPoint(QWebEngineScript.InjectionPoint.DocumentCreation)
        geo.setWorldId(QWebEngineScript.ScriptWorldId.MainWorld)
        geo.setRunsOnSubFrames(True)
        geo.setSourceCode(self._guard_src(GEO_SCRIPT.replace("__CFG__", cfg), "identity"))
        scripts.insert(geo)

        cos = QWebEngineScript()
        cos.setName("whybrowse-cosmetic")
        cos.setInjectionPoint(QWebEngineScript.InjectionPoint.DocumentReady)
        cos.setWorldId(QWebEngineScript.ScriptWorldId.MainWorld)
        cos.setRunsOnSubFrames(False)
        cos.setSourceCode(self._guard_src(COSMETIC_SCRIPT.replace("__CFG__", cfg), "cosmetic"))
        scripts.insert(cos)

        # CP field-focus tracker (see FIELD_FOCUS_TRACKER_JS comment): lets the
        # CP button find/fill fields inside iframes (e.g. embedded payment
        # widgets), not just the main document. Always on, independent of
        # ad-block/cosmetic/clean settings - it's a plain utility, not a
        # privacy or content feature.
        cpt = QWebEngineScript()
        cpt.setName("whybrowse-cp-field-tracker")
        cpt.setInjectionPoint(QWebEngineScript.InjectionPoint.DocumentReady)
        cpt.setWorldId(QWebEngineScript.ScriptWorldId.MainWorld)
        cpt.setRunsOnSubFrames(True)
        cpt.setSourceCode(self._guard_src(FIELD_FOCUS_TRACKER_JS))
        scripts.insert(cpt)

        # DEL 48 scroll-lock guard. DocumentReady (it needs <body>) and main
        # world, like the cosmetic script - it has to see the same computed
        # styles the page itself has. It self-guards on the setting and on the
        # per-site exception, so it is always installed and decides in-page.
        sg = QWebEngineScript()
        sg.setName("whybrowse-scroll-guard")
        sg.setInjectionPoint(QWebEngineScript.InjectionPoint.DocumentReady)
        sg.setWorldId(QWebEngineScript.ScriptWorldId.MainWorld)
        sg.setRunsOnSubFrames(False)
        sg.setSourceCode(self._guard_src(SCROLL_GUARD_SCRIPT.replace("__CFG__", cfg), "scroll"))
        scripts.insert(sg)

        # DEL 51 "keep my place". DocumentCreation, NOT DocumentReady: it has to
        # wrap window.scrollTo and friends before the page's own scripts get a
        # reference to them. Main frame only - it guards the main page scroll,
        # never an iframe's or an inner panel's. It self-guards on the setting
        # and on the per-site exception, like the scroll-lock guard above.
        ks = QWebEngineScript()
        ks.setName("whybrowse-keep-scroll")
        ks.setInjectionPoint(QWebEngineScript.InjectionPoint.DocumentCreation)
        ks.setWorldId(QWebEngineScript.ScriptWorldId.MainWorld)
        ks.setRunsOnSubFrames(False)
        ks.setSourceCode(self._guard_src(KEEP_SCROLL_SCRIPT.replace("__CFG__", cfg), "scroll"))
        scripts.insert(ks)

        # Built-in YouTube ad-block (youtube.com only; self-guards on host).
        if self.settings.get("youtube_adblock", True):
            yt = QWebEngineScript()
            yt.setName("whybrowse-youtube-adblock")
            yt.setInjectionPoint(QWebEngineScript.InjectionPoint.DocumentCreation)
            yt.setWorldId(QWebEngineScript.ScriptWorldId.MainWorld)
            yt.setRunsOnSubFrames(True)
            yt.setSourceCode(self._guard_src(YOUTUBE_ADBLOCK_SCRIPT))
            scripts.insert(yt)

        # User add-ons (.js/.css from the userscripts folder), unless disabled.
        disabled = set(self.settings.get("userscripts_disabled", []))
        for us in getattr(self, "_userscripts", []):
            if us["name"] in disabled:
                continue
            sc = QWebEngineScript()
            sc.setName("wb-addon-" + us["name"])
            sc.setInjectionPoint(QWebEngineScript.InjectionPoint.DocumentReady)
            sc.setWorldId(QWebEngineScript.ScriptWorldId.MainWorld)
            sc.setRunsOnSubFrames(False)
            sc.setSourceCode(self._guard_src(self._wrap_userscript(us), "addons"))
            scripts.insert(sc)

    def _open_in_system_browser(self, url):
        """Hand a URL to the OS default browser (Edge/Chrome) - its engine is
        kept up to date by Windows, so it's the safest place for risky pages."""
        if url and url.startswith(("http://", "https://")):
            try:
                open_url(url)
                show_toast(self, "Opened in your system browser")
            except Exception:
                pass

    def _open_userscripts_folder(self):
        try:
            os.makedirs(USERSCRIPTS_DIR, exist_ok=True)
            open_path(USERSCRIPTS_DIR)            # Windows file explorer
        except Exception:
            show_toast(self, "Add-ons folder: %s" % USERSCRIPTS_DIR)

    def _reload_userscripts(self):
        self._userscripts = load_userscripts()
        self._apply_privacy()
        self._refresh_current()
        show_toast(self, "Reloaded %d add-on%s"
                   % (len(self._userscripts), "" if len(self._userscripts) == 1 else "s"))

    def _toggle_userscript(self, name):
        dis = self.settings.setdefault("userscripts_disabled", [])
        if name in dis:
            dis.remove(name)
        else:
            dis.append(name)
        save_json(SETTINGS_FILE, self.settings)
        self._apply_privacy()
        self._refresh_current()
        show_toast(self, "Add-on %s: %s" % (name, "OFF" if name in dis else "ON"))

    def _wrap_userscript(self, us):
        """Wrap a user add-on so it only runs on its @match hosts (CSS is injected
        as a <style>). Each add-on is its own script - a bad one can't break others."""
        hosts = json.dumps(us.get("hosts", []))
        if us["type"] == "css":
            body = ("var s=document.createElement('style');s.textContent=%s;"
                    "(document.head||document.documentElement).appendChild(s);"
                    % json.dumps(us["code"]))
        else:
            body = us["code"]
        return ("(function(){try{var hosts=%s;"
                "var h=(location.hostname||'').replace(/^www\\./,'');"
                "if(hosts.length && !hosts.some(function(d){return h===d||h.endsWith('.'+d);}))"
                " return;\n%s\n}catch(e){}})();" % (hosts, body))

    def rebuild_content_scripts(self):
        """Re-install the injected JavaScript on every profile engine."""
        for engine in self.engines.values():
            self._install_scripts(engine)

    def _apply_privacy(self):
        """Apply ad-block state + domain list and rebuild injected scripts."""
        clean = self._clean_active()
        domains = list(DEFAULT_ADBLOCK) + list(self.settings.get("adblock_extra", []))
        self.adblock.set_domains(domains)
        self.adblock.enabled = (not clean) and bool(self.settings.get("adblock_enabled", True))
        # Sites with an "ad blocker off" exception
        exempt = set(
            dom.lower().replace("www.", "")
            for dom, ov in (self.settings.get("site_overrides") or {}).items()
            if ov.get("adblock_enabled") is False)
        # ALWAYS exempt YouTube from the network ad-blocker: blocking its ad/tracking
        # domains doesn't stop the in-video ads (those ride googlevideo.com) but DOES
        # trip YouTube's "turn off your ad blocker" wall + black screen. The built-in
        # YouTube ad-block SCRIPT handles YouTube ads instead (toggle on the page).
        exempt.add("youtube.com")
        exempt.add("youtube-nocookie.com")
        # ALWAYS exempt IMDb too: its trailer player (IMDb is Amazon-owned) starts
        # the video session through amazon-adsystem.com / demdex.net, both on the
        # ad-block list. Blocking them makes the player throw "an error occurred"
        # and the trailer never plays. Exempting IMDb lets the video start (you may
        # see a short pre-roll). Turn adblock back on for imdb.com via Settings →
        # Exceptions if you'd rather block it and live without trailers.
        exempt.add("imdb.com")
        exempt |= set(self._crash_hosts_with("adblock"))      # DEL 56: "Try without..."
        self.adblock.exempt_hosts = exempt
        # Sites with their own browser identity (DEL 53): the header half.
        self.adblock.ua_by_host = {d: u.encode("utf-8", "ignore")
                                   for d, u in self._site_ua_map().items()}
        # Sites you blocked outright are NOT part of the ad blocker: `clean`
        # (Plain mode) and a per-site adblock exception must not reach them, so
        # they go in on their own, every time.
        self._sync_junk_block()
        # Clean mode also stands the Chrome-identity headers down, so re-arm
        # them here and not only from _apply_user_agent().
        self._apply_brand_headers()
        self.rebuild_content_scripts()

    def open_settings(self):
        dlg = SettingsDialog(self)
        if dlg.exec():
            self.settings.update(dlg.result_settings())
            # Default download folder is stored per-profile (not global).
            dl = dlg.ed_download.text().strip()
            prof = self._active_profile()
            if dl:
                prof["save_dir"] = dl
            else:
                prof.pop("save_dir", None)
            prof["quick_download"] = dlg.chk_quick_download.isChecked()
            prof["dupe_policy"] = dlg.cmb_dupe.currentData() or DUPE_ASK
            save_json(SETTINGS_FILE, self.settings)
            apply_theme_dict(self.settings.get("theme", {}))
            self.apply_theme()          # live recolor of all chrome + blank page
            write_new_tab_page(self.settings.get("search_engine", SEARCH_URL))
            self._apply_privacy()
            self._apply_user_agent()        # a changed UA must take effect now
            try:                            # new speed limits, live (DEL 49)
                eng = self.torrent_engine(create=False)
                if eng is not None:
                    eng.apply_limits()
            except Exception as e:
                log_line("torrent limits not applied: %s" % e)
            self.build_bookmarks_bar()      # reflect Tookmarks on/off
            self._refresh_current()
            show_toast(self, "Settings saved")

    def _apply_user_agent(self):
        """Push the current user-agent setting onto every live engine."""
        for eng in self.engines.values():
            try:
                eng.setHttpUserAgent(self._effective_user_agent(eng))
            except Exception:
                pass
        self._apply_brand_headers()
        self._apply_accept_language()

    def _chrome_full_version(self):
        """The full 4-part Chrome version our identity claims (140.0.7339.225).

        The engine's REAL build number when we are reporting the engine's real
        major (the normal case) - a made-up build number next to a real major is
        one more thing that can be checked. Only when _ua_chrome_major() has
        decided to claim a HIGHER major (ancient engine, see UA_BUMP_GAP) do we
        fall back to the x.0.0.0 form, because we have no real build number for
        a version this engine is not."""
        maj = self._ua_chrome_major()
        try:
            from PyQt6.QtWebEngineCore import qWebEngineChromiumVersion
            real = str(qWebEngineChromiumVersion())
            if real.split(".")[0] == str(maj) and len(real.split(".")) == 4:
                return real
        except Exception:
            pass
        return "%d.0.0.0" % maj

    def _brand_fix_on(self):
        """Sec-CH-UA rewriting is only correct while we present as Chrome.

        A hand-typed custom user-agent is the one case where it must stand down:
        if he sets a Firefox UA to get past a stubborn site, sending Chrome
        client hints alongside it would create exactly the contradiction this
        feature exists to remove."""
        if self._clean_active():
            return False
        if (self.settings.get("user_agent") or "").strip():
            return False
        return bool(self.settings.get("chrome_identity", True))

    def _apply_brand_headers(self):
        """Arm (or disarm) the interceptor's Sec-CH-UA rewrite."""
        try:
            if self._brand_fix_on():
                self.adblock.ch_ua, self.adblock.ch_ua_full = chrome_brand_headers(
                    self._ua_chrome_major(), self._chrome_full_version())
            else:
                self.adblock.ch_ua = self.adblock.ch_ua_full = b""
        except Exception as e:
            log_line("brand headers failed: %s" % e)

    def _apply_accept_language(self):
        """Send an Accept-Language header at all.

        MEASURED 2026-09-01: QWebEngineProfile.httpAcceptLanguage() is EMPTY on
        this build, so QtWebEngine sent no Accept-Language header whatsoever -
        something no real browser does, and a free tell on every request. It is
        also why navigator.languages was the bare ["sv"] instead of a real
        browser's ordered list."""
        val = (self.settings.get("accept_language") or "").strip() or ACCEPT_LANGUAGE
        for eng in self.engines.values():
            try:
                if eng.httpAcceptLanguage() != val:
                    eng.setHttpAcceptLanguage(val)
            except Exception:
                pass

    def open_feature_search(self, initial=""):
        """Open the feature/settings search popup (Ctrl+Shift+F)."""
        dlg = FeatureSearchDialog(self, initial)
        dlg.exec()

    def open_backup(self):
        dlg = BackupDialog(self)
        dlg.exec()

    def open_move(self):
        dlg = MoveDialog(self)
        dlg.exec()

    # ----------------------------------------------------- Firefox import ----
    def import_firefox_bookmarks(self):
        """Import the full bookmark TREE (folders too) from the active Firefox
        profile. Replaces the current tree with Firefox's structure."""
        src = firefox_places_path()
        if not src:
            QMessageBox.information(self, "Import from Firefox",
                                    "No Firefox profile (places.sqlite) was found.")
            return

        tmp = None
        try:
            tmp = os.path.join(tempfile.gettempdir(), "whybrowse_places.sqlite")
            shutil.copy2(src, tmp)                    # FF locks the live DB
            con = sqlite3.connect(tmp)
            cur = con.cursor()
            cur.execute(
                "SELECT b.id, b.type, b.title, b.parent, p.url "
                "FROM moz_bookmarks b LEFT JOIN moz_places p ON b.fk = p.id "
                "ORDER BY b.parent, b.position")
            children = {}
            for bid, typ, title, parent, url in cur.fetchall():
                children.setdefault(parent, []).append((bid, typ, title, url))

            def folder_id(guid):
                cur.execute("SELECT id FROM moz_bookmarks WHERE guid=?", (guid,))
                r = cur.fetchone()
                return r[0] if r else None

            def build(pid):
                out = []
                for bid, typ, title, url in children.get(pid, []):
                    if typ == 1 and url and url.startswith("http"):
                        out.append({"title": title or url, "url": url})
                    elif typ == 2:                    # folder
                        kids = build(bid)
                        if kids:
                            out.append({"title": title or "Folder", "folder": kids})
                return out

            toolbar = folder_id("toolbar_____")
            menu_f  = folder_id("menu________")
            unfiled = folder_id("unfiled_____")
            bar_tree  = build(toolbar) if toolbar else []
            menu_tree = build(menu_f) if menu_f else []
            other = build(unfiled) if unfiled else []
            if other:
                menu_tree.append({"title": "Other Bookmarks", "folder": other})
            con.close()
        except Exception as e:
            log_line("Firefox import failed: {}".format(e))
            QMessageBox.warning(self, "Import from Firefox",
                                "Could not read Firefox bookmarks:\n{}".format(e))
            return
        finally:
            if tmp and os.path.isfile(tmp):
                try: os.remove(tmp)
                except Exception: pass

        n_links = len(bookmark_flatten(bar_tree)) + len(bookmark_flatten(menu_tree))
        n_folders = (json.dumps(bar_tree).count('"folder"') +
                     json.dumps(menu_tree).count('"folder"'))
        self.bookmarks = {"bar": bar_tree, "menu": menu_tree}
        self._save_bm()
        self.build_bookmarks_bar()
        prof = os.path.basename(os.path.dirname(src))
        show_toast(self, "Imported {} links in {} folders".format(n_links, n_folders))
        log_line("Firefox import from {}: {} links, {} folders".format(prof, n_links, n_folders))

    # ---- Google sign-in carried over from Firefox (DEL 50, route B) ----------
    def import_google_login(self):
        GoogleLoginImportDialog(self).exec()

    def install_google_cookies(self, pid, rows, done):
        """Write Firefox's Google cookies into ONE profile's cookie store.

        Asynchronous, and it has to be. MEASURED 2026-09-01, and the single
        thing that makes this feature work at all:

            QWebEngineCookieStore.setCookie() is SILENTLY DISCARDED on a profile
            whose store has never had a live page.

        Not an error, not a warning - 26 cookies sent, 0 stored, no Cookies
        table on disk at all. loadAllCookies() does not wake it either, and
        merely CONSTRUCTING a QWebEnginePage is not enough: the page has to have
        actually loaded something. Which is exactly the case that matters here,
        because the profile Google refuses is usually not the one on screen.
        The first version of this reported a cheerful "imported 26 cookies"
        while writing nothing whatsoever.

        So: give the target profile a throwaway page on an https origin, wait
        for it to finish, and only then push. And count what the store SAYS it
        accepted (cookieAdded) rather than what we handed it, so the number he
        is shown is the number that really landed.  done(imported, skipped)."""
        eng = self._get_engine(pid)
        store = eng.cookieStore()
        accepted = set()
        state = {"finished": False, "sent": 0, "bad": 0}

        def on_added(c):
            try:
                accepted.add(bytes(c.name()).decode("utf-8", "replace"))
            except Exception:
                pass

        store.cookieAdded.connect(on_added)
        # Parented to the window so it cannot be collected mid-load; dropped in
        # finish(). An https origin, because these are Secure cookies.
        page = QWebEnginePage(eng, self)
        self._cookie_import_page = page

        def push(_ok=True):
            if state["sent"]:
                return                          # loadFinished can fire twice
            for row in rows:
                try:
                    cookie, origin = firefox_cookie_to_qt(row)
                    store.setCookie(cookie, origin)
                    state["sent"] += 1
                except Exception as e:
                    state["bad"] += 1
                    log_line("cookie import skipped %s@%s: %s"
                             % (row.get("name"), row.get("host"), e))
            QTimer.singleShot(1500, finish)

        def finish():
            if state["finished"]:
                return
            state["finished"] = True
            try:
                store.cookieAdded.disconnect(on_added)
            except Exception:
                pass
            self._cookie_import_page = None
            try:
                page.deleteLater()
            except Exception:
                pass
            got = len(accepted)
            skipped = state["bad"] + max(0, state["sent"] - got)
            log_line("Google login import into profile %s: %d accepted, "
                     "%d sent, %d skipped" % (pid, got, state["sent"], skipped))
            # The store writes lazily; take the safety-net snapshot afterwards
            # so an unclean shutdown cannot lose a login we just carried over.
            try:
                self._backup_storage_cookies(profile_paths(pid)["storage"])
            except Exception as e:
                log_line("cookie backup after import failed: %s" % e)
            done(got, skipped)

        page.loadFinished.connect(push)
        page.setHtml("<html><body></body></html>", QUrl("https://www.google.com/"))
        # Belt and braces: if loadFinished never arrives, push anyway rather
        # than leaving the dialog waiting for a callback that never comes.
        QTimer.singleShot(4000, push)

    def open_google_drive_check(self, pid):
        """Switch to the profile the cookies went into and open Drive there."""
        try:
            if pid != self.active_id:
                self.switch_profile(pid)
        except Exception as e:
            log_line("drive check switch failed: %s" % e)
        self.add_tab("https://drive.google.com/", switch=True)

    # ----------------------------------------------------- geometry / state ----
    def _restore_geometry(self):
        w = self.settings["window"]
        wide, high = int(w.get("w") or 1200), int(w.get("h") or 800)
        x, y = w.get("x"), w.get("y")
        if x is not None and y is not None:
            # The other half of the minimised-window trap (see _collect_settings):
            # a settings.json poisoned by an older build still holds -32000, and a
            # monitor that has been unplugged since leaves a saved corner behind
            # just as dead. Either way the corner sits on no screen at all, so the
            # whole saved rectangle is junk - its size came from the same bad read
            # - and the defaults are used instead. That heals the file by itself:
            # the next close writes a rectangle that is on the desktop.
            if QApplication.screenAt(QPoint(int(x), int(y))) is None:
                log_line("saved window geometry is off every screen (%s,%s %sx%s)"
                         " - falling back to the default size" % (x, y, wide, high))
                x = y = None
                wide, high = 1200, 800
        self.resize(wide, high)
        if x is not None and y is not None:
            self.move(int(x), int(y))
        if w.get("maximized"):
            self.showMaximized()
        else:
            fit_to_screen(self)

    def _check_engine_update_on_startup(self):
        """Kick off a background check (see EngineUpdateChecker) for a newer
        PyQt6-WebEngine release. Off by default toggle lives in Settings ->
        Performance. Never blocks startup and never auto-installs anything -
        worst case on failure (no internet, PyPI unreachable) is silence."""
        if not bool(self.settings.get("check_engine_updates", True)):
            return
        self._engine_checker = EngineUpdateChecker()
        self._engine_checker.checked.connect(self._on_engine_update_checked)
        self._engine_checker.check()

    def _check_chrome_version_on_startup(self):
        """Fetch the latest stable Chrome major version from Google's public
        VERSIONHISTORY API (at most once every 30 days) and cache it in
        settings so _effective_user_agent() always reports a current Chrome.
        Completely silent on failure.  Called from main() with a short delay
        so it never competes with startup for CPU/network."""
        self._chrome_ver_checker = ChromeVersionChecker(self.settings, self)
        if not self._chrome_ver_checker.should_check():
            log_line("Chrome version cache is fresh (major=%s), skipping fetch." %
                     self.settings.get("cached_chrome_major", "?"))
            return
        self._chrome_ver_checker.fetched.connect(self._on_chrome_version_fetched)
        self._chrome_ver_checker.check()

    def _on_chrome_version_fetched(self, major, ver_str, error):
        if error or major < 100:
            log_line("Chrome version fetch failed: %s" % (error or "major=%d" % major))
            return
        old = self.settings.get("cached_chrome_major", 0)
        self.settings["cached_chrome_major"] = major
        self.settings["cached_chrome_version_date"] = int(time.time())
        log_line("Chrome version updated: %s -> %s (full: %s)" % (old, major, ver_str))
        # Re-apply the UA on all open engine profiles so currently-open tabs
        # benefit immediately (without needing a restart).
        try:
            for pid, eng in self.engines.items():
                if not self.settings.get("user_agent", "").strip():
                    eng.setHttpUserAgent(self._effective_user_agent(eng))
        except Exception as e:
            log_line("UA refresh after chrome version update failed: %s" % e)

    def _on_engine_update_checked(self, installed, latest, is_newer, error):
        if error:
            log_line("Engine update check failed (installed=%s): %s" % (installed, error))
            return
        log_line("Engine update check: installed PyQt6-WebEngine=%s, latest on PyPI=%s%s" % (
            installed, latest, "  (NEWER AVAILABLE)" if is_newer else ""))
        self._engine_newer = (installed, latest) if is_newer else None   # DEL 56 error page
        if is_newer:
            show_toast(self,
                "A newer browser engine is available (PyQt6-WebEngine %s → %s). "
                "Update with: pip install --upgrade PyQt6 PyQt6-WebEngine" % (installed, latest),
                duration=8000)

    def _collect_settings(self):
        # Window. A MINIMISED window does not report where it will come back:
        # Windows parks it on the placeholder rectangle (-32000,-32000, a few
        # hundred pixels) and geometry() hands that straight out. Written to
        # settings.json once - close the browser while it sits in the taskbar
        # and it is - every later start restores a window that is alive and
        # shows a thumbnail on hover but is nowhere on the desktop. So while
        # minimised, keep the last good rectangle and touch nothing.
        if self.isMinimized():
            pass
        elif not self.isMaximized() and not self.isFullScreen():
            g = self.geometry()
            self.settings["window"] = {
                "x": g.x(), "y": g.y(), "w": g.width(), "h": g.height(),
                "maximized": False,
            }
        else:
            self.settings["window"]["maximized"] = self.isMaximized()
        # Open tabs of the ACTIVE profile (blank start pages are not saved)
        self._stash_current_tabs()       # writes into the active profile's last_tabs
        # Don't let a window that was FORCED onto profile 1 by an external link
        # click overwrite the profile you normally start in.
        if not getattr(self, "_launch_url", None):
            self.settings["active_profile"] = self.active_id
        return self.settings

    def closeEvent(self, event):
        # Downloads are not tied to their window any more, so quitting is the
        # one thing that stops them - say so instead of doing it silently.
        _n_dl = self.media_active_count()
        if _n_dl:
            if QMessageBox.question(
                    self, "Downloads running",
                    "%d download(s) are still running or waiting.\n\nQuit anyway? They "
                    "will be stopped; partly downloaded files are kept, so you can "
                    "carry on later." % _n_dl,
                    QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
                    QMessageBox.StandardButton.No) != QMessageBox.StandardButton.Yes:
                event.ignore()
                return
        try:
            save_json(SETTINGS_FILE, self._collect_settings())
            self._save_bm()
            self._save_hist()
            save_json(SCROLL_POS_FILE, self._scroll_pos)
        except Exception as e:
            log_line("closeEvent save error: {}".format(e))
        self._remove_ipc_file()        # the pipe dies with us - say so (DEL 01b)
        try:
            if self._osk is not None:          # close the floating keyboard too
                self._osk.close()
        except Exception:
            pass
        try:
            if getattr(self, "_media_q", None) is not None:   # stop what still runs
                self._media_q.shutdown()
            if self._media_dlg is not None:    # and close its window
                self._media_dlg.close()
        except Exception:
            pass
        # ---- Torrents (DEL 49): remember the list, then let the engine go ----
        # With UPnP off (the default) this returns immediately; with UPnP ON,
        # libtorrent's own shutdown can take ~20 s - which is exactly why the
        # setting warns about it.
        try:
            if getattr(self, "_torrent_dlg", None) is not None:
                self._torrent_dlg.close()
        except Exception:
            pass
        try:
            eng = getattr(self, "_torrent_engine", None)
            if eng is not None:
                eng.shutdown()
        except Exception as e:
            log_line("torrent shutdown error: %s" % e)
        # Give Chromium's storage service a moment to flush cookies / localStorage
        # to disk BEFORE the process exits. Without this, recently-set cookies
        # (logins, cookie-consent) can be lost on close, so you'd log in again next
        # launch. We spin the event loop briefly (non-blocking-ish) rather than hard
        # sleep, so the IO writes complete.
        try:
            from PyQt6.QtCore import QEventLoop
            deadline = time.time() + 1.2
            while time.time() < deadline:
                QApplication.processEvents(QEventLoop.ProcessEventsFlag.AllEvents, 50)
                time.sleep(0.03)
        except Exception:
            pass
        super().closeEvent(event)


# ============================================================================
#  DEL 13Z - BOOKMARK TREE MANAGER  (reorder/move/rename/edit/delete; ESC closes)
# ----------------------------------------------------------------------------
#  A full tree editor for the whole bookmark set (the Bar AND the Menu):
#    - drag an item to reorder it or drop it into a folder
#    - ▲ / ▼ to nudge it within its current folder
#    - New folder / Rename / Edit address / Delete / Open
#  The two roots ("Bookmarks Bar" / "Bookmarks Menu") are fixed: you can't drag
#  them, drop a sibling at the very top level, or nest items inside a link.
# ============================================================================
# ============================================================================
#  DEL 12F - UPDATE SCANNER  (watch web pages for changes, like Firefox's)
# ----------------------------------------------------------------------------
#  Fetches a page's HTML in a background thread, reduces it to visible text and
#  hashes it. When the hash changes between checks, the page is flagged changed.
#  Signals are delivered back to the GUI thread (Qt queues cross-thread signals).
# ============================================================================
_WATCH_UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
             "(KHTML, like Gecko) Chrome/124.0 Safari/537.36")


def html_to_text(html):
    """Strip scripts/styles/markup so we compare what a reader actually sees -
    this avoids most false 'changed' hits from shifting markup/whitespace."""
    html = re.sub(r'(?is)<(script|style|noscript)[^>]*>.*?</\1>', ' ', html)
    html = re.sub(r'(?s)<[^>]+>', ' ', html)
    html = re.sub(r'\s+', ' ', html)
    return html.strip()


class EngineUpdateChecker(QObject):
    """At startup, checks PyPI for a newer PyQt6-WebEngine release than the one
    currently installed. PyQt6-WebEngine is the Chromium build WhyBrowse
    actually renders with, and it lags behind real Chrome/Firefox - that gap
    is the likely cause of "works in Chrome/Firefox but not in WhyBrowse"
    reports (e.g. Google Sheets xlsx/ods export). This doesn't auto-update
    anything - it only checks and tells the user, so they can run
    'pip install --upgrade PyQt6 PyQt6-WebEngine' themselves.

    checked emits (installed_version, latest_version, is_newer_available, error_text).
    error_text is empty on a normal successful check (even if no update is available).
    """
    checked = pyqtSignal(str, str, bool, str)

    @staticmethod
    def _version_tuple(v):
        # Best-effort "1.2.3" -> (1, 2, 3) so versions compare numerically
        # instead of as strings (where "1.10" < "1.9" alphabetically).
        parts = []
        for chunk in (v or "").split("."):
            digits = "".join(c for c in chunk if c.isdigit())
            parts.append(int(digits) if digits else 0)
        return tuple(parts)

    def check(self):
        threading.Thread(target=self._run, daemon=True).start()

    def _run(self):
        installed = "unknown"
        try:
            import importlib.metadata
            installed = importlib.metadata.version("PyQt6-WebEngine")
        except Exception:
            pass
        try:
            req = urllib.request.Request(
                "https://pypi.org/pypi/PyQt6-WebEngine/json",
                headers={"User-Agent": "WhyBrowse-engine-update-check"})
            with urllib.request.urlopen(req, timeout=8) as r:
                data = json.loads(r.read().decode("utf-8", "replace"))
            latest = data.get("info", {}).get("version", "")
            is_newer = (installed != "unknown" and latest and
                        self._version_tuple(latest) > self._version_tuple(installed))
            self.checked.emit(installed, latest, is_newer, "")
        except Exception as e:
            self.checked.emit(installed, "", False, str(e)[:200])


class ChromeVersionChecker(QObject):
    """Fetches the latest stable Chrome major version from Google's public
    VERSIONHISTORY API and caches it in settings so _effective_user_agent()
    can always present a believable, current Chrome UA string.

    The check runs in a background thread and is completely silent on failure
    (no internet, API unreachable).  The result is stored in settings as
    'cached_chrome_major' (int) and 'cached_chrome_version_date' (unix time).
    A new fetch is only triggered if more than 30 days have passed since the
    last successful one, or if no cached value exists yet.

    fetched emits (major: int, version_string: str, error: str).
    error is empty on success.
    """
    fetched = pyqtSignal(int, str, str)
    CHECK_INTERVAL_DAYS = 30

    def __init__(self, settings, parent=None):
        super().__init__(parent)
        self._settings = settings

    def should_check(self):
        """True if we have never fetched or the cache is older than 30 days."""
        last = self._settings.get("cached_chrome_version_date", 0)
        if not last:
            return True
        return (time.time() - last) > self.CHECK_INTERVAL_DAYS * 86400

    def check(self):
        """Spawn a background thread; result arrives via the 'fetched' signal."""
        threading.Thread(target=self._run, daemon=True).start()

    def _run(self):
        # Google's public VERSIONHISTORY REST API — no key required.
        # Returns JSON with all releases; we filter for platform=win64,
        # channel=stable, take the highest version number.
        # NOTE: "filter=endtime=none" makes this endpoint answer 400 Bad Request,
        # and "order_by=version+desc" needs a real %20 rather than "+". That is
        # why every startup logged "Chrome version fetch failed: HTTP Error 400"
        # and the cached major sat frozen at 136 for months. The plain endpoint
        # already returns newest-stable first, so ask for exactly that.
        url = ("https://versionhistory.googleapis.com/v1/chrome/platforms/"
               "win64/channels/stable/versions?page_size=1")
        try:
            req = urllib.request.Request(
                url, headers={"User-Agent": "WhyBrowse-chrome-version-check/1.0"})
            with urllib.request.urlopen(req, timeout=8) as r:
                data = json.loads(r.read().decode("utf-8", "replace"))
            versions = data.get("versions", [])
            if not versions:
                self.fetched.emit(0, "", "empty response from versionhistory API")
                return
            ver_str = versions[0].get("version", "")  # e.g. "149.0.7972.33"
            major = int(ver_str.split(".")[0]) if ver_str else 0
            if major < 100:
                self.fetched.emit(0, ver_str, "unexpected version: %s" % ver_str)
                return
            self.fetched.emit(major, ver_str, "")
        except Exception as e:
            self.fetched.emit(0, "", str(e)[:200])


class PageWatcher(QObject):
    # url, visible-text (capped; empty on error), error-text (empty on success).
    # We send the text (not a hash) so the GUI thread can apply this watch's own
    # options - ignore numbers, minimum changed characters - when comparing.
    result = pyqtSignal(str, str, str)
    TEXT_CAP = 60000                              # chars kept for comparison/diff

    def check(self, url):
        threading.Thread(target=self._run, args=(url,), daemon=True).start()

    def _run(self, url):
        try:
            req = urllib.request.Request(url, headers={"User-Agent": _WATCH_UA})
            with urllib.request.urlopen(req, timeout=20) as r:
                raw = r.read(2_000_000)               # cap download at ~2 MB
            text = html_to_text(raw.decode("utf-8", "replace"))[:self.TEXT_CAP]
            self.result.emit(url, text, "")
        except Exception as e:
            self.result.emit(url, "", str(e)[:200])


class _BMTree(QTreeWidget):
    """A tree whose internal drag-drop MOVES the real items (takeChild /
    insertChild) instead of letting Qt serialise+recreate them - so each item
    keeps its Python payload (._node / ._is_folder / ._is_root) and its whole
    subtree, and the two fixed roots can never be reordered or nested into."""

    dropped = pyqtSignal()   # emitted after every successful drag-drop

    def dropEvent(self, event):
        sel = self.selectedItems()
        src = sel[0] if sel else self.currentItem()
        if src is None or getattr(src, "_is_root", False):
            event.ignore(); return
        DI = QAbstractItemView.DropIndicatorPosition
        invis = self.invisibleRootItem()
        target = self.itemAt(event.position().toPoint())
        ind = self.dropIndicatorPosition()
        if target is None or ind == DI.OnViewport:
            event.ignore(); return                       # no top-level drops
        if ind == DI.OnItem:
            if getattr(target, "_is_folder", False):
                parent, index = target, target.childCount()
            else:                                        # onto a link -> sibling
                parent = target.parent() or invis
                index = parent.indexOfChild(target) + 1
        else:                                            # Above / Below an item
            parent = target.parent() or invis
            index = parent.indexOfChild(target) + (1 if ind == DI.BelowItem else 0)
        if parent is invis:
            event.ignore(); return                       # keep the two roots fixed
        p = parent                                       # forbid into self/descendant
        while p is not None:
            if p is src:
                event.ignore(); return
            p = p.parent()
        old_parent = src.parent() or invis
        old_index = old_parent.indexOfChild(src)
        if old_parent is parent and old_index < index:
            index -= 1                                   # removal shifts indices
        expanded = src.isExpanded()
        old_parent.takeChild(old_index)
        parent.insertChild(index, src)
        src.setExpanded(expanded)
        parent.setExpanded(True)
        self.setCurrentItem(src)
        # We moved the item ourselves; tell Qt NOT to also remove the source row
        # (InternalMove would double-remove it → the bookmark would vanish).
        event.setDropAction(Qt.DropAction.IgnoreAction)
        event.accept()
        self.dropped.emit()


class BookmarkManagerDialog(QDialog):
    def __init__(self, window):
        super().__init__(window)
        self.win = window
        self.setWindowTitle(APP_NAME + " - Manage bookmarks")
        self.setModal(True)
        self.resize(660, 640)
        self.setStyleSheet(dialog_qss())
        apply_window_icon(self)
        lay = QVBoxLayout(self)
        hint = QLabel("Drag to reorder or move into a folder. Double-click or press "
                      "Enter to open a link. Ctrl/Shift-click to select multiple items "
                      "for bulk delete or move. Folders are shown in bold.")
        hint.setWordWrap(True)
        hint.setStyleSheet("color:%s; font-size:9pt;" % C_STATUS_FG)
        lay.addWidget(hint)

        self.tree = _BMTree()
        self.tree.setHeaderHidden(True)
        self.tree.setDragDropMode(QAbstractItemView.DragDropMode.InternalMove)
        self.tree.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection)
        self.tree.itemActivated.connect(self._activated)   # Enter / double-click opens a link
        self.tree.dropped.connect(self._on_change)         # drag-drop triggers auto-save
        lay.addWidget(self.tree, 1)

        self.root_bar = self._make_item(None, {"title": "Bookmarks Bar"}, is_root=True)
        self.root_menu = self._make_item(None, {"title": "Bookmarks Menu"}, is_root=True)
        self.tree.addTopLevelItem(self.root_bar)
        self.tree.addTopLevelItem(self.root_menu)
        self._fill(self.root_bar, self.win.bookmarks.get("bar", []))
        self._fill(self.root_menu, self.win.bookmarks.get("menu", []))
        self.root_bar.setExpanded(True)
        self.root_menu.setExpanded(True)

        def btn(txt, fn, accent=False):
            b = QPushButton(txt)
            if accent:
                b.setStyleSheet(
                    "QPushButton{background:%s; color:%s; border:none; padding:6px 10px;"
                    "border-radius:6px; font-weight:bold;}QPushButton:hover{background:%s;}"
                    % (C_ACCENT, C_ACCENT_FG, C_ACCENT_HOV))
            else:
                b.setStyleSheet(
                    "QPushButton{background:%s; color:%s; border:none; padding:6px 10px;"
                    "border-radius:6px;}QPushButton:hover{background:%s;}"
                    % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
            b.clicked.connect(fn)
            return b

        row1 = QHBoxLayout()
        for txt, fn in (("📁  New folder", self._new_folder), ("✎  Rename", self._rename),
                        ("🔗  Edit address", self._edit_url), ("🗑  Delete", self._delete),
                        ("↗  Open", self._open)):
            row1.addWidget(btn(txt, fn))
        lay.addLayout(row1)

        row2 = QHBoxLayout()
        row2.addWidget(btn("▲  Move up", self._move_up))
        row2.addWidget(btn("▼  Move down", self._move_down))
        row2.addWidget(btn("➡  Move into folder...", self._move_into))
        lay.addLayout(row2)

        # ---- Save row ----
        row3 = QHBoxLayout()
        self.chk_autosave = QCheckBox("Auto-save on every change")
        self.chk_autosave.setStyleSheet("color:%s;" % C_BAR_FG)
        self.chk_autosave.setChecked(
            bool(window.settings.get("bookmark_manager_autosave", False)))
        self.chk_autosave.toggled.connect(self._autosave_toggled)
        row3.addWidget(self.chk_autosave)

        self.lbl_saved = QLabel("")
        self.lbl_saved.setStyleSheet("color:%s; font-size:9pt;" % C_STATUS_FG)
        row3.addWidget(self.lbl_saved)
        row3.addStretch(1)

        self.btn_save = btn("💾  Save", self._save, accent=True)
        row3.addWidget(self.btn_save)
        row3.addWidget(btn("↩  Cancel (discard changes)", self._cancel))
        row3.addWidget(btn("✕  Close", self.accept))
        lay.addLayout(row3)

    # ---- build ----
    def _make_item(self, parent, node, is_folder=False, is_root=False):
        title = node.get("title") or node.get("url") or "Untitled"
        it = QTreeWidgetItem([title])
        it._node = dict(node)
        it._is_folder = bool(is_folder or is_root)
        it._is_root = bool(is_root)
        base = Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsSelectable
        if is_root:
            it.setFlags(base | Qt.ItemFlag.ItemIsDropEnabled)
        elif is_folder:
            it.setFlags(base | Qt.ItemFlag.ItemIsDragEnabled | Qt.ItemFlag.ItemIsDropEnabled)
        else:
            it.setFlags(base | Qt.ItemFlag.ItemIsDragEnabled)   # link: no drop INTO it
            it.setToolTip(0, node.get("url", ""))
        if it._is_folder:
            f = it.font(0); f.setBold(True); it.setFont(0, f)
        if parent is not None:
            parent.addChild(it)
        return it

    def _fill(self, parent_item, nodes):
        for n in nodes or []:
            if "folder" in n:
                it = self._make_item(parent_item, n, is_folder=True)
                self._fill(it, n.get("folder", []))
            elif n.get("url"):
                self._make_item(parent_item, n, is_folder=False)

    # ---- helpers ----
    def _cur(self):
        """Return the single focused item (for single-item actions)."""
        return self.tree.currentItem()

    def _selected(self):
        """Return all selected items (for bulk actions)."""
        return self.tree.selectedItems()

    def _parent_of(self, it):
        return it.parent() or self.tree.invisibleRootItem()

    # ---- actions ----
    def _activated(self, it, _col):
        """Double-click or Enter on a link: open it (without closing the dialog
        so the user can keep browsing the list)."""
        if it is not None and not it._is_folder:
            self.win.add_tab(it._node["url"], switch=True)

    def _new_folder(self):
        title, ok = QInputDialog.getText(self, "New folder", "Folder name:")
        if not ok or not title.strip():
            return
        it = self._cur()
        parent = it if (it and it._is_folder) else (it.parent() if it else None) or self.root_menu
        folder = self._make_item(parent, {"title": title.strip()}, is_folder=True)
        parent.setExpanded(True)
        self.tree.setCurrentItem(folder)
        self._on_change()

    def _rename(self):
        it = self._cur()
        if not it or it._is_root:
            return
        title, ok = QInputDialog.getText(self, "Rename", "Name:", text=it.text(0))
        if ok and title.strip():
            it.setText(0, title.strip())
            self._on_change()

    def _edit_url(self):
        it = self._cur()
        if not it or it._is_root or it._is_folder:
            return
        url, ok = QInputDialog.getText(self, "Edit address", "URL:",
                                       text=it._node.get("url", ""))
        if ok and url.strip():
            it._node["url"] = url.strip()
            it.setToolTip(0, url.strip())
            self._on_change()

    def _delete(self):
        items = [i for i in self._selected() if not i._is_root]
        if not items:
            return
        # If any non-empty folder is in the selection, ask once for all
        heavy = [i for i in items if i._is_folder and i.childCount()]
        if heavy:
            names = ", ".join('"%s"' % i.text(0) for i in heavy[:3])
            if len(heavy) > 3:
                names += " …"
            if QMessageBox.question(
                    self, "Delete folders",
                    "Delete %s and everything inside?" % names
            ) != QMessageBox.StandardButton.Yes:
                return
        for it in items:
            self._parent_of(it).removeChild(it)
        self._on_change()

    def _open(self):
        """Open all selected links in new tabs (dialog stays open so the
        user can keep scrolling and picking more)."""
        opened = 0
        for it in self._selected():
            if not it._is_folder and it._node.get("url"):
                self.win.add_tab(it._node["url"], switch=(opened == 0))
                opened += 1
        if not opened:
            # Fallback: use current item
            it = self._cur()
            if it and not it._is_folder and it._node.get("url"):
                self.win.add_tab(it._node["url"], switch=True)

    def _move(self, delta):
        it = self._cur()
        if not it or it._is_root:
            return
        parent = self._parent_of(it)
        idx = parent.indexOfChild(it)
        j = idx + delta
        if 0 <= j < parent.childCount():
            expanded = it.isExpanded()
            parent.takeChild(idx)
            parent.insertChild(j, it)
            it.setExpanded(expanded)
            self.tree.setCurrentItem(it)
            self._on_change()

    def _move_up(self):
        self._move(-1)

    def _move_down(self):
        self._move(+1)

    def _is_descendant(self, anc, node):
        p = node
        while p is not None:
            if p is anc:
                return True
            p = p.parent()
        return False

    def _move_into(self):
        """Reliable alternative to drag: pick a destination folder from a menu.
        Works for a single item or the whole current selection."""
        items = [i for i in self._selected() if not getattr(i, "_is_root", False)]
        if not items:
            return
        m = QMenu(self)
        m.setStyleSheet(self.win._menu_style())

        def add_dests(parent_item, depth):
            for i in range(parent_item.childCount()):
                ch = parent_item.child(i)
                # Skip folders that are in the selection or are descendants of
                # any selected item (can't move a folder into itself).
                if not getattr(ch, "_is_folder", False):
                    continue
                if any(ch is sel or self._is_descendant(sel, ch) for sel in items):
                    continue
                a = m.addAction("   " * depth + "📁 " + ch.text(0))
                a.triggered.connect(lambda _=False, d=ch: self._do_move_all(items, d))
                add_dests(ch, depth + 1)
        for root in (self.root_bar, self.root_menu):
            a = m.addAction(root.text(0))
            a.triggered.connect(lambda _=False, d=root: self._do_move_all(items, d))
            add_dests(root, 1)
        m.exec(QCursor.pos())

    def _do_move_all(self, items, dest):
        """Move all items in *items* into *dest* (appended in order)."""
        for it in items:
            old = it.parent() or self.tree.invisibleRootItem()
            old.takeChild(old.indexOfChild(it))
            dest.addChild(it)
        dest.setExpanded(True)
        if items:
            self.tree.setCurrentItem(items[-1])
        self._on_change()

    # ---- save ----
    def _collect(self, parent_item):
        out = []
        for i in range(parent_item.childCount()):
            it = parent_item.child(i)
            base = dict(getattr(it, "_node", {}) or {})
            base["title"] = it.text(0)
            if it._is_folder:
                base.pop("url", None)
                base["folder"] = self._collect(it)
            else:
                base.pop("folder", None)
            out.append(base)
        return out

    def _save(self):
        """Save bookmarks to disk (dialog stays open)."""
        self.win.bookmarks["bar"] = self._collect(self.root_bar)
        self.win.bookmarks["menu"] = self._collect(self.root_menu)
        self.win._save_bm()
        self.win.build_bookmarks_bar()
        self.lbl_saved.setText("Saved ✓")
        QTimer.singleShot(2000, lambda: self.lbl_saved.setText(""))
        show_toast(self.win, "Bookmarks saved")

    def _cancel(self):
        """Discard in-memory changes by reloading from disk (dialog stays open)."""
        self.win.bookmarks = load_json(BOOKMARKS_FILE, {"bar": [], "menu": []})
        # Rebuild the tree from the freshly loaded data
        self.tree.clear()
        self.root_bar = self._make_item(None, {"title": "Bookmarks Bar"}, is_root=True)
        self.root_menu = self._make_item(None, {"title": "Bookmarks Menu"}, is_root=True)
        self.tree.addTopLevelItem(self.root_bar)
        self.tree.addTopLevelItem(self.root_menu)
        self._fill(self.root_bar, self.win.bookmarks.get("bar", []))
        self._fill(self.root_menu, self.win.bookmarks.get("menu", []))
        self.root_bar.setExpanded(True)
        self.root_menu.setExpanded(True)
        self.win.build_bookmarks_bar()
        self.lbl_saved.setText("Changes discarded")
        QTimer.singleShot(2000, lambda: self.lbl_saved.setText(""))

    def _on_change(self):
        """Called after every mutation when auto-save is active."""
        if self.chk_autosave.isChecked():
            self._save()

    def _autosave_toggled(self, checked):
        """Persist the auto-save preference in settings."""
        self.win.settings["bookmark_manager_autosave"] = checked
        save_json(SETTINGS_FILE, self.win.settings)
        if checked:
            self._save()   # save immediately when turned on

    def keyPressEvent(self, e):
        if e.key() == Qt.Key.Key_Escape:
            self.reject()
        else:
            super().keyPressEvent(e)


# ============================================================================
#  DEL 43 - PAGE RIGHT-CLICK MENU LAYOUT  (drag it into the order YOU want)
# ----------------------------------------------------------------------------
#  The page right-click menu grew to ~50 entries in a fixed, hardcoded order.
#  This section makes that order YOURS:
#
#    * every entry has a stable id and is collected as an (id, builder) pair
#      by Browser._page_menu_entries() - nothing is added to a QMenu directly;
#    * render_page_menu() then lays those entries out following the saved
#      arrangement (Helpfiles/WhyBrowse/page_menu.json): your order, your own
#      sub-menus ("folders"), your separators, minus whatever you hid;
#    * PageMenuLayoutDialog is the editor - drag rows to reorder, drag them
#      into a sub-menu you made yourself, or into the Hidden bin.
#
#  Two safety rules keep the menu from ever losing an entry:
#    1. an entry that exists in the program but is missing from your saved
#       arrangement (e.g. a feature added in a later version) is appended at
#       the BOTTOM instead of vanishing;
#    2. "⚙ Arrange this menu…" can be moved but never hidden, so there is
#       always a way back (Settings has the same button as a second route).
#
#  Entries that don't apply to the page you right-clicked (link actions with
#  no link under the cursor, "un-hide" with nothing hidden, …) are simply never
#  collected, and separators around them collapse automatically - so a
#  rearranged menu never shows a stray double line or an empty sub-menu.
# ============================================================================

# (id, label shown in the editor, when the entry appears)
PAGE_MENU_CATALOG = [
    ("yt_adblock",             "▶  Block YouTube ads",                          "YouTube pages"),
    ("link_open_stay",         "↗  Open link in new tab (stay here)",           "on a link"),
    ("link_open_go",           "➡  Open link in new tab and go there",          "on a link"),
    ("link_open_temp",         "🕒  Open link in the TEMP tab",                 "on a link"),
    ("link_copy",              "⎘  Copy link",                                  "on a link"),
    ("link_newtab_default",    "🆕  Open links in a NEW tab by default",        "on a link"),
    ("link_same_tab_domain",   "↩  …except links to this domain (same tab)",    "on a link"),
    ("link_bookmark_bar",      "☆  Bookmark this link (to bar)",                "on a link"),
    ("link_bookmark_unsorted", "🆕  Bookmark this link → Unsorted",             "on a link"),
    ("link_bookmark_folder",   "📁  Bookmark link in folder…  ▸",               "on a link"),
    ("link_hide_domain",       "🚫  Hide this domain from search results",      "on a link"),
    ("link_block_domain",      "⛔  BLOCK this link's site (never again)",    "on a link"),
    ("img_copy",               "\U0001f5bc  Copy image",                         "on a picture"),
    ("img_save_now",           "\U0001f4be  Save image",                         "on a picture"),
    ("img_save",               "\U0001f4be  Save image as\u2026",                    "on a picture"),
    ("img_copy_address",       "\u2398  Copy image address",                      "on a picture"),
    ("img_open",               "\u2197  Open image in a new tab",                 "on a picture"),
    ("media_copy_address",     "\u2398  Copy video / audio address",              "on a video or audio"),
    ("page_copy",              "Copy",                                          "when something is selected"),
    ("page_paste",             "Paste",                                         "in a text field"),
    ("page_select_all",        "Select all",                                    "always"),
    ("translate",              "🌍  Translate  ▸",                              "always"),
    ("unlock_scroll",          "🔓  Get scrolling back (unlock this page)",     "always"),
    ("copy_page_address",      "⎘  Copy this page's address",                   "always"),
    ("fav_add",                "⭐  Add this page to Favourites",               "pages not already starred"),
    ("fav_add_login",          "⭐  Add to Favourites using login…  ▸",         "web pages"),
    ("snippet_stars",          "📝  Insert: …  (one row per starred word)",     "when you have starred words"),
    ("snippets",               "📝  Saved words / snippets  ▸",                 "always"),
    ("remember_field",         "💾  Remember this field's value here",          "always"),
    ("forget_fields",          "🚫  Forget saved fields for this site",         "sites with saved fields"),
    ("block_site",             "⛔  BLOCK this site — never open it again",   "web pages"),
    ("no_history_domain",      "🙈  Keep this site out of history & suggestions", "web pages"),
    ("popup_kill",             "🗯  Kill a pop-up box on this page (click it)…", "always"),
    ("autoclick",              "👆  Click a button for me every time…",         "always"),
    ("popup_rules",            "🗯  Pop-up rules here  ▸",                      "sites with pop-up rules"),
    ("freeze_element",         "🧊  Stop an element from moving (click)",       "always"),
    ("zap_element",            "✂  Hide an element (click to zap)",             "always"),
    ("sticky_section",         "📌  Freeze a section to the top",               "always"),
    ("freeze_clear",           "↺  Let elements move again on this site",       "sites with frozen elements"),
    ("unhide_pick",            "👁  Show hidden, remove individually",          "sites with hidden elements"),
    ("unhide_all",             "↺  Un-hide ALL elements on this site",          "sites with hidden elements"),
    ("sticky_clear",           "↺  Un-freeze sections on this site",            "sites with frozen sections"),
    ("site_macro",             "🎬  Site macro (remember my actions here)  ▸",  "always"),
    ("watch_page",             "🔭  Watch this page for changes",               "always"),
    ("watch_check_now",        "🔄  Check this page for changes now",           "pages you already watch"),
    ("link_open_favourite_1",  "⭐  My favourite open-link action  (copy 1)",   "on a link"),
    ("temp_download",          "📥  Download to temp directory  ▸",             "always"),
    ("torrent_link",           "🧲  Torrent this link…",                       "on a magnet / .torrent link"),
    ("torrents_window",        "🧲  Torrents…",                                "always"),
    ("download_media_link",    "⬇  Download video/audio from this LINK…",      "on a link"),
    ("download_media_page",    "⬇  Download video/audio from this page…",      "always"),
    ("split_view",             "⊞  Split view (second page beside)",            "always"),
    ("open_link_system",       "🌐  Open LINK in my system browser",            "on a link"),
    ("view_source",            "🔍  View page source",                          "always"),
    ("save_page",              "💾  Save page as…",                             "always"),
    ("print_pdf",              "🖨  Print / Save as PDF…  (Ctrl+P)",            "always"),
    ("link_open_favourite_2",  "⭐  My favourite open-link action  (copy 2)",   "on a link"),
    ("features",               "🎛  Features (quick toggle, all sites)  ▸",     "always"),
    ("site_exceptions",        "🌐  Exceptions for this site  ▸",               "always"),
    ("troubleshoot",           "🔧  Troubleshoot this page  ▸",                 "always"),
    ("arrange_menu",           "⚙  Arrange this menu…",                        "always (can't be hidden)"),
]

PAGE_MENU_LABELS = {i: lbl for i, lbl, _w in PAGE_MENU_CATALOG}
PAGE_MENU_WHEN   = {i: w   for i, _lbl, w in PAGE_MENU_CATALOG}

# The entry that must always stay reachable, so the editor can never lock itself
# away. It may be MOVED anywhere, but not hidden or deleted.
PAGE_MENU_ANCHOR = "arrange_menu"

# Where a NEW entry belongs in an arrangement you saved before it existed.
# Without this, anything added later is appended at the very bottom of YOUR
# menu - under "Arrange this menu..." and under any sub-menu you made - which
# is precisely where a new feature is never seen. id -> the entry it belongs
# beside; if that one is anywhere in your arrangement the newcomer is put
# straight after it, otherwise it falls back to the bottom exactly as before.
PAGE_MENU_NEAR = {
    "block_site":        "popup_kill",
    "no_history_domain": "block_site",
    "link_block_domain": "link_hide_domain",
}


# Factory order - identical to how the menu looked before it became editable.
# "---" is a separator line.
PAGE_MENU_DEFAULT = [
    "yt_adblock", "---",
    "link_open_stay", "link_open_go", "link_open_temp", "link_copy",
    "link_newtab_default",
    "link_same_tab_domain", "link_bookmark_bar", "link_bookmark_unsorted",
    "link_bookmark_folder", "link_hide_domain", "link_block_domain", "---",
    "img_copy", "img_save", "img_copy_address", "img_open",
    "media_copy_address", "---",
    "page_copy", "page_paste", "page_select_all",
    "translate", "unlock_scroll", "copy_page_address", "fav_add", "fav_add_login",
    "snippet_stars", "snippets", "remember_field", "forget_fields", "---",
    "block_site", "no_history_domain", "---",
    "popup_kill", "autoclick", "popup_rules", "freeze_element", "zap_element",
    "sticky_section", "freeze_clear", "unhide_pick", "unhide_all",
    "sticky_clear", "---",
    "site_macro", "watch_page", "watch_check_now", "---",
    "link_open_favourite_1", "---",
    "temp_download", "torrent_link", "torrents_window",
    "download_media_link", "download_media_page", "---",
    "split_view", "---",
    "open_link_system", "view_source", "save_page", "print_pdf", "---",
    "link_open_favourite_2", "features", "site_exceptions", "troubleshoot", "---",
    "arrange_menu",
]


def default_page_menu_layout():
    """The factory arrangement, as the same structure a saved one uses."""
    items = [{"t": "s"} if x == "---" else {"t": "i", "id": x}
             for x in PAGE_MENU_DEFAULT]
    return {"items": items, "hidden": []}


def _page_menu_walk_ids(nodes):
    """Every entry id used anywhere in an arrangement (sub-menus included)."""
    for n in nodes or []:
        if not isinstance(n, dict):
            continue
        if n.get("t") == "f":
            for x in _page_menu_walk_ids(n.get("items")):
                yield x
        elif n.get("t", "i") == "i" and n.get("id"):
            yield n["id"]


def _page_menu_place_near(nodes, item_id):
    """Put `item_id` directly after the entry PAGE_MENU_NEAR pairs it with,
    wherever that one sits - top level, or inside one of your own sub-menus.
    True when a home was found; False tells the caller to append as before."""
    anchor = PAGE_MENU_NEAR.get(item_id)
    if not anchor:
        return False
    for pos, n in enumerate(nodes or []):
        if not isinstance(n, dict):
            continue
        if n.get("t") == "f":
            if _page_menu_place_near(n.get("items"), item_id):
                return True
        elif n.get("t", "i") == "i" and n.get("id") == anchor:
            nodes.insert(pos + 1, {"t": "i", "id": item_id})
            return True
    return False


def normalise_page_menu_layout(raw):
    """Clean up an arrangement read from disk (or from the editor):

      * anything that isn't a dict with an "items" list falls back to factory;
      * ids this version doesn't have any more are dropped;
      * an id used twice keeps only its first place;
      * the anchor entry can never be hidden;
      * ids the program HAS but the arrangement doesn't mention are appended
        at the bottom, so a feature added later can never go missing.
    """
    if not isinstance(raw, dict) or not isinstance(raw.get("items"), list):
        return default_page_menu_layout()

    known = set(PAGE_MENU_LABELS)
    hidden = [i for i in (raw.get("hidden") or [])
              if isinstance(i, str) and i in known and i != PAGE_MENU_ANCHOR]
    hidden = list(dict.fromkeys(hidden))
    hidden_set = set(hidden)
    seen = set()

    def clean(nodes):
        out = []
        for n in nodes or []:
            if not isinstance(n, dict):
                continue
            t = n.get("t", "i")
            if t == "s":
                out.append({"t": "s"})
            elif t == "f":
                out.append({"t": "f",
                            "name": str(n.get("name") or "My sub-menu")[:60],
                            "items": clean(n.get("items"))})
            else:
                iid = n.get("id")
                if iid in known and iid not in seen and iid not in hidden_set:
                    seen.add(iid)
                    out.append({"t": "i", "id": iid})
        return out

    items = clean(raw.get("items"))
    missing = [i for i, _l, _w in PAGE_MENU_CATALOG
               if i not in seen and i not in hidden_set]
    if missing:
        rest = [i for i in missing if not _page_menu_place_near(items, i)]
        if rest:
            items.append({"t": "s"})
            items.extend({"t": "i", "id": i} for i in rest)
    return {"items": items, "hidden": hidden}


def render_page_menu(menu, entries, layout, style_for_depth=None):
    """Fill `menu` with `entries` arranged the way `layout` says.

    entries          [(id, add_fn)]  in factory order; add_fn(target, depth)
                     puts that one entry into `target`. Only entries that
                     actually apply to the current page are in the list.
    layout           {"items": [...], "hidden": [ids]} - see the section header.
    style_for_depth  optional fn(depth) -> stylesheet for created sub-menus.

    Separators are collapsed on the fly (never leading, never doubled, never
    trailing) and a self-made sub-menu that ends up empty is left out - both
    matter because whole groups disappear depending on what was right-clicked.
    """
    by_id = {}
    order = []
    for iid, fn in entries:
        by_id.setdefault(iid, []).append(fn)
        if iid not in order:
            order.append(iid)
    hidden = set((layout or {}).get("hidden") or [])
    hidden.discard(PAGE_MENU_ANCHOR)
    used = set()

    def add_one(iid, target, depth):
        """Run an entry's builder(s); True when it really added something."""
        before = len(target.actions())
        for fn in by_id.get(iid, []):
            try:
                fn(target, depth)
            except Exception as exc:
                log_line("page menu entry %s failed: %s" % (iid, exc))
        used.add(iid)
        return len(target.actions()) > before

    def build(nodes, target, depth):
        added = 0
        want_sep = False
        for n in nodes or []:
            t = n.get("t", "i")
            if t == "s":
                want_sep = added > 0
                continue
            if t == "f":
                sub = QMenu(n.get("name") or "My sub-menu", target)
                if style_for_depth:
                    sub.setStyleSheet(style_for_depth(depth + 1))
                if build(n.get("items"), sub, depth + 1):
                    if want_sep:
                        target.addSeparator()
                        want_sep = False
                    target.addMenu(sub)
                    added += 1
                else:
                    sub.deleteLater()
                continue
            iid = n.get("id")
            if not iid or iid in hidden or iid in used or iid not in by_id:
                continue
            if want_sep:
                target.addSeparator()
                want_sep = False
            if add_one(iid, target, depth):
                added += 1
        return added

    build((layout or {}).get("items"), menu, 0)

    # Safety net: anything the program offers but the arrangement never placed
    # goes at the bottom rather than disappearing.
    leftovers = [i for i in order if i not in used and i not in hidden]
    if leftovers:
        if menu.actions():
            menu.addSeparator()
        for iid in leftovers:
            add_one(iid, menu, 0)


class _MenuLayoutTree(_BMTree):
    """The bookmark tree's drag-drop (which MOVES the real item and keeps its
    Python payload) reused for the menu arrangement: the two roots stay put,
    a row can be dropped into a sub-menu, and nothing can be nested into a
    plain entry."""
    pass


class PageMenuLayoutDialog(QDialog):
    """Editor for the page right-click menu: drag rows into the order you want,
    make your own sub-menus and drop entries into them, park what you never use
    in the Hidden bin. ESC closes."""

    def __init__(self, window):
        super().__init__(window)
        self.win = window
        self.setWindowTitle(APP_NAME + " - Arrange the page right-click menu")
        self.setModal(True)
        self.resize(720, 760)
        self.setStyleSheet(dialog_qss())
        apply_window_icon(self)

        lay = QVBoxLayout(self)
        hint = QLabel(
            "Drag any row to move it up or down, or drop it INTO one of your own "
            "sub-menus (📁  New sub-menu…). Rows in the Hidden bin never show up "
            "in the menu. Entries that only apply sometimes — link actions, "
            "'un-hide elements', and so on — keep the place you give them here and "
            "simply stay out of the menu when they don't apply.")
        hint.setWordWrap(True)
        hint.setStyleSheet("color:%s; font-size:9pt;" % C_STATUS_FG)
        lay.addWidget(hint)

        self.tree = _MenuLayoutTree()
        self.tree.setHeaderHidden(True)
        self.tree.setDragDropMode(QAbstractItemView.DragDropMode.InternalMove)
        self.tree.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection)
        self.tree.dropped.connect(self._changed)
        lay.addWidget(self.tree, 1)

        self._build_tree(self.win.page_menu_layout())

        def btn(txt, fn, accent=False):
            b = QPushButton(txt)
            if accent:
                b.setStyleSheet(
                    "QPushButton{background:%s; color:%s; border:none; padding:6px 10px;"
                    "border-radius:6px; font-weight:bold;}QPushButton:hover{background:%s;}"
                    % (C_ACCENT, C_ACCENT_FG, C_ACCENT_HOV))
            else:
                b.setStyleSheet(
                    "QPushButton{background:%s; color:%s; border:none; padding:6px 10px;"
                    "border-radius:6px;}QPushButton:hover{background:%s;}"
                    % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
            b.clicked.connect(fn)
            return b

        row1 = QHBoxLayout()
        for txt, fn in (("📁  New sub-menu", self._new_folder),
                        ("✎  Rename sub-menu", self._rename),
                        ("─  Add separator", self._add_separator),
                        ("🗑  Delete", self._delete),
                        ("👁  Hide / Show", self._toggle_hidden)):
            row1.addWidget(btn(txt, fn))
        lay.addLayout(row1)

        row2 = QHBoxLayout()
        row2.addWidget(btn("▲  Move up", self._move_up))
        row2.addWidget(btn("▼  Move down", self._move_down))
        row2.addWidget(btn("➡  Move into…", self._move_into))
        row2.addWidget(btn("🔍  Preview the menu", self._preview))
        row2.addWidget(btn("↺  Factory order", self._reset))
        lay.addLayout(row2)

        row3 = QHBoxLayout()
        self.lbl_status = QLabel("")
        self.lbl_status.setStyleSheet("color:%s; font-size:9pt;" % C_STATUS_FG)
        row3.addWidget(self.lbl_status, 1)
        row3.addWidget(btn("💾  Save", self._save, accent=True))
        row3.addWidget(btn("↩  Undo my changes", self._cancel))
        row3.addWidget(btn("✕  Close", self.accept))
        lay.addLayout(row3)

    # ---- build the tree -------------------------------------------------
    def _mk_root(self, title):
        it = QTreeWidgetItem([title])
        it._kind = "root"
        it._is_root = True
        it._is_folder = True
        it.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsSelectable
                    | Qt.ItemFlag.ItemIsDropEnabled)
        f = it.font(0)
        f.setBold(True)
        it.setFont(0, f)
        it.setForeground(0, QColor(C_ACCENT))
        return it

    def _mk_entry(self, parent, iid, index=None):
        label = PAGE_MENU_LABELS.get(iid, iid)
        when = PAGE_MENU_WHEN.get(iid, "always")
        if when != "always":
            label = "%s     ·  %s" % (label, when)
        it = QTreeWidgetItem([label])
        it._kind = "i"
        it._id = iid
        it._is_root = False
        it._is_folder = False
        it.setToolTip(0, "Appears: %s" % when)
        it.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsSelectable
                    | Qt.ItemFlag.ItemIsDragEnabled)
        if parent is not None:
            if index is None:
                parent.addChild(it)
            else:
                parent.insertChild(index, it)
        return it

    def _mk_separator(self, parent, index=None):
        it = QTreeWidgetItem(["────────────────  (separator line)"])
        it._kind = "s"
        it._id = ""
        it._is_root = False
        it._is_folder = False
        it.setForeground(0, QColor(C_STATUS_FG))
        it.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsSelectable
                    | Qt.ItemFlag.ItemIsDragEnabled)
        if parent is not None:
            if index is None:
                parent.addChild(it)
            else:
                parent.insertChild(index, it)
        return it

    def _mk_folder(self, parent, name, index=None):
        it = QTreeWidgetItem(["📁  " + name])
        it._kind = "f"
        it._name = name
        it._id = ""
        it._is_root = False
        it._is_folder = True
        f = it.font(0)
        f.setBold(True)
        it.setFont(0, f)
        it.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsSelectable
                    | Qt.ItemFlag.ItemIsDragEnabled | Qt.ItemFlag.ItemIsDropEnabled)
        if parent is not None:
            if index is None:
                parent.addChild(it)
            else:
                parent.insertChild(index, it)
        return it

    def _fill(self, parent_item, nodes):
        for n in nodes or []:
            t = n.get("t", "i")
            if t == "s":
                self._mk_separator(parent_item)
            elif t == "f":
                folder = self._mk_folder(parent_item, n.get("name") or "My sub-menu")
                self._fill(folder, n.get("items"))
                folder.setExpanded(True)
            elif n.get("id") in PAGE_MENU_LABELS:
                self._mk_entry(parent_item, n["id"])

    def _build_tree(self, layout):
        self.tree.clear()
        self.root_menu = self._mk_root("📋  The right-click menu   (top → bottom)")
        self.root_hidden = self._mk_root("🚫  Hidden — never shown in the menu")
        self.tree.addTopLevelItem(self.root_menu)
        self.tree.addTopLevelItem(self.root_hidden)
        self._fill(self.root_menu, (layout or {}).get("items"))
        for iid in (layout or {}).get("hidden") or []:
            if iid in PAGE_MENU_LABELS:
                self._mk_entry(self.root_hidden, iid)
        self.root_menu.setExpanded(True)
        self.root_hidden.setExpanded(True)

    # ---- helpers --------------------------------------------------------
    def _cur(self):
        return self.tree.currentItem()

    def _selected(self):
        return [i for i in self.tree.selectedItems()
                if not getattr(i, "_is_root", False)]

    def _parent_of(self, it):
        return it.parent() or self.tree.invisibleRootItem()

    def _root_of(self, it):
        p = it
        while p is not None and not getattr(p, "_is_root", False):
            p = p.parent()
        return p

    def _note(self, text):
        self.lbl_status.setText(text)
        QTimer.singleShot(2500, lambda: self.lbl_status.setText(""))

    def _changed(self):
        self.lbl_status.setText("Changed — press 💾 Save to keep it")

    # ---- actions --------------------------------------------------------
    def _new_folder(self):
        name, ok = QInputDialog.getText(
            self, "New sub-menu",
            "Name of the sub-menu (add your own emoji if you like):")
        if not ok or not name.strip():
            return
        it = self._cur()
        if it is not None and getattr(it, "_is_folder", False):
            parent, index = it, it.childCount()
        elif it is not None:
            parent = it.parent() or self.root_menu
            index = parent.indexOfChild(it) + 1
        else:
            parent, index = self.root_menu, self.root_menu.childCount()
        folder = self._mk_folder(parent, name.strip()[:60], index)
        parent.setExpanded(True)
        self.tree.setCurrentItem(folder)
        self._changed()

    def _rename(self):
        it = self._cur()
        if it is None or getattr(it, "_kind", "") != "f":
            self._note("Pick one of your own sub-menus to rename")
            return
        name, ok = QInputDialog.getText(self, "Rename sub-menu", "Name:",
                                        text=it._name)
        if ok and name.strip():
            it._name = name.strip()[:60]
            it.setText(0, "📁  " + it._name)
            self._changed()

    def _add_separator(self):
        it = self._cur()
        if it is not None and getattr(it, "_is_folder", False) \
                and not getattr(it, "_is_root", False):
            parent, index = it, it.childCount()
        elif it is not None and not getattr(it, "_is_root", False):
            parent = it.parent() or self.root_menu
            index = parent.indexOfChild(it) + 1
        else:
            parent, index = self.root_menu, self.root_menu.childCount()
        if self._root_of(parent) is self.root_hidden:
            parent, index = self.root_menu, self.root_menu.childCount()
        sep = self._mk_separator(parent, index)
        parent.setExpanded(True)
        self.tree.setCurrentItem(sep)
        self._changed()

    def _delete(self):
        """Separators and your own sub-menus can be deleted. A real menu entry
        cannot — it is hidden instead, so it is always recoverable."""
        items = self._selected()
        if not items:
            return
        moved_out = 0
        for it in items:
            kind = getattr(it, "_kind", "i")
            if kind == "i":
                self._hide_item(it)
                continue
            if kind == "f" and it.childCount():
                # Never swallow entries with the folder: lift them out first.
                parent = self._parent_of(it)
                index = parent.indexOfChild(it)
                for child in list(it.takeChildren()):
                    index += 1
                    parent.insertChild(index, child)
                    moved_out += 1
            self._parent_of(it).removeChild(it)
        if moved_out:
            self._note("Sub-menu deleted — its %d entr%s moved out, nothing lost"
                       % (moved_out, "y" if moved_out == 1 else "ies"))
        self._changed()

    def _hide_item(self, it):
        if getattr(it, "_id", "") == PAGE_MENU_ANCHOR:
            self._note("\"Arrange this menu…\" can be moved, but not hidden — "
                       "otherwise there would be no way back")
            return False
        self._parent_of(it).removeChild(it)
        self.root_hidden.addChild(it)
        self.root_hidden.setExpanded(True)
        return True

    def _toggle_hidden(self):
        items = self._selected()
        if not items:
            return
        for it in items:
            if getattr(it, "_kind", "i") != "i":
                continue
            if self._root_of(it) is self.root_hidden:
                self._parent_of(it).removeChild(it)
                self.root_menu.addChild(it)
                self.tree.setCurrentItem(it)
            else:
                self._hide_item(it)
        self._changed()

    def _move(self, delta):
        it = self._cur()
        if it is None or getattr(it, "_is_root", False):
            return
        parent = self._parent_of(it)
        idx = parent.indexOfChild(it)
        j = idx + delta
        if 0 <= j < parent.childCount():
            expanded = it.isExpanded()
            parent.takeChild(idx)
            parent.insertChild(j, it)
            it.setExpanded(expanded)
            self.tree.setCurrentItem(it)
            self._changed()

    def _move_up(self):
        self._move(-1)

    def _move_down(self):
        self._move(+1)

    def _is_descendant(self, ancestor, node):
        p = node
        while p is not None:
            if p is ancestor:
                return True
            p = p.parent()
        return False

    def _move_into(self):
        """Keyboard-friendly alternative to dragging: pick the destination."""
        items = self._selected()
        if not items:
            return
        m = QMenu(self)
        m.setStyleSheet(self.win._menu_style())

        def add_dests(parent_item, depth):
            for i in range(parent_item.childCount()):
                ch = parent_item.child(i)
                if not getattr(ch, "_is_folder", False):
                    continue
                if any(ch is sel or self._is_descendant(sel, ch) for sel in items):
                    continue
                a = m.addAction("   " * depth + "📁  " + getattr(ch, "_name", ch.text(0)))
                a.triggered.connect(lambda _=False, d=ch: self._do_move_all(items, d))
                add_dests(ch, depth + 1)

        for root in (self.root_menu, self.root_hidden):
            a = m.addAction(root.text(0))
            a.triggered.connect(lambda _=False, d=root: self._do_move_all(items, d))
            add_dests(root, 1)
        m.exec(QCursor.pos())

    def _do_move_all(self, items, dest):
        if dest is self.root_hidden:
            for it in items:
                if getattr(it, "_kind", "i") == "i":
                    self._hide_item(it)
            self._changed()
            return
        for it in items:
            old = self._parent_of(it)
            old.takeChild(old.indexOfChild(it))
            dest.addChild(it)
        dest.setExpanded(True)
        if items:
            self.tree.setCurrentItem(items[-1])
        self._changed()

    def _preview(self):
        """Show the arrangement as a real menu (entries disabled). What you see
        is the full list; on an actual page the entries that don't apply are
        left out and the separators around them close up."""
        m = QMenu(self)
        m.setStyleSheet(self.win._menu_style())

        def build(parent_item, target, depth):
            for i in range(parent_item.childCount()):
                it = parent_item.child(i)
                kind = getattr(it, "_kind", "i")
                if kind == "s":
                    target.addSeparator()
                elif kind == "f":
                    sub = target.addMenu(it._name)
                    sub.setStyleSheet(self.win._menu_style(min(depth + 1, 2)))
                    build(it, sub, depth + 1)
                else:
                    a = target.addAction(PAGE_MENU_LABELS.get(it._id, it._id))
                    a.setEnabled(False)

        build(self.root_menu, m, 0)
        m.addSeparator()
        note = m.addAction("(preview — on a real page, entries that don't apply "
                           "are left out)")
        note.setEnabled(False)
        m.exec(QCursor.pos())

    def _reset(self):
        if QMessageBox.question(
                self, "Factory order",
                "Put every entry back in the original order and un-hide "
                "everything?\n\nYour own sub-menus are removed (the entries "
                "inside them are kept)."
        ) != QMessageBox.StandardButton.Yes:
            return
        self._build_tree(default_page_menu_layout())
        self._note("Factory order restored — press 💾 Save to keep it")

    # ---- save / cancel --------------------------------------------------
    def _collect(self, parent_item):
        out = []
        for i in range(parent_item.childCount()):
            it = parent_item.child(i)
            kind = getattr(it, "_kind", "i")
            if kind == "s":
                out.append({"t": "s"})
            elif kind == "f":
                out.append({"t": "f", "name": it._name,
                            "items": self._collect(it)})
            elif it._id in PAGE_MENU_LABELS:
                out.append({"t": "i", "id": it._id})
        return out

    def _collect_hidden(self, parent_item):
        out = []
        for i in range(parent_item.childCount()):
            it = parent_item.child(i)
            if getattr(it, "_kind", "i") == "f":
                out.extend(self._collect_hidden(it))
            elif getattr(it, "_id", "") and it._id != PAGE_MENU_ANCHOR:
                out.append(it._id)
        return out

    def _save(self):
        layout = {"items": self._collect(self.root_menu),
                  "hidden": self._collect_hidden(self.root_hidden)}
        self.win.save_page_menu_layout(layout)
        self.lbl_status.setText("Saved ✓  — right-click any page to see it")
        QTimer.singleShot(2500, lambda: self.lbl_status.setText(""))
        show_toast(self.win, "Right-click menu saved")

    def _cancel(self):
        self._build_tree(self.win.page_menu_layout())
        self._note("Back to the last saved arrangement")

    def keyPressEvent(self, e):
        if e.key() == Qt.Key.Key_Escape:
            self.reject()
        else:
            super().keyPressEvent(e)


# ============================================================================
#  DEL 14A1 - TAB SEARCH  (find/jump to any open tab; type to filter; ESC closes)
# ============================================================================
class TabSearchDialog(QDialog):
    def __init__(self, window):
        super().__init__(window)
        self.win = window
        self.setWindowTitle(APP_NAME + " - Find a tab")
        self.setModal(True)
        self.resize(560, 480)
        self.setStyleSheet(dialog_qss())
        apply_window_icon(self)
        lay = QVBoxLayout(self)
        self.search = QLineEdit()
        self.search.setPlaceholderText("Type to filter tabs by title or address…")
        self.search.textChanged.connect(self._reload)
        self.search.returnPressed.connect(self._open)
        lay.addWidget(self.search)
        self.listw = QListWidget()
        self.listw.itemDoubleClicked.connect(lambda _i: self._open())
        lay.addWidget(self.listw, 1)
        row = QHBoxLayout()
        for txt, fn in (("↗  Go to tab", self._open),
                        ("✕  Close tab", self._close_sel), ("Close", self.accept)):
            b = QPushButton(txt)
            b.clicked.connect(fn)
            row.addWidget(b)
        lay.addLayout(row)
        self._reload()
        self.search.setFocus()

    def _reload(self):
        q = self.search.text().strip().lower()
        self.listw.clear()
        cur = self.win.current_view()
        for i in range(self.win.tabs.count()):
            v = self.win.tabs.widget(i)
            if not v:
                continue
            title = getattr(v, "_custom_title", None) or v.title() or "New Tab"
            url = v.url().toString()
            if q and q not in title.lower() and q not in url.lower():
                continue
            mark = ("▶ " if v is cur else "   ")
            if getattr(v, "_asleep", False):
                mark += "💤 "
            elif self.win._combo_key(v):
                mark += "● "
            it = QListWidgetItem("%s%s\n        %s" % (mark, title[:60], url[:90]))
            it.setData(Qt.ItemDataRole.UserRole, v)
            self.listw.addItem(it)
        if self.listw.count():
            self.listw.setCurrentRow(0)

    def _sel_view(self):
        it = self.listw.currentItem()
        return it.data(Qt.ItemDataRole.UserRole) if it else None

    def _open(self):
        v = self._sel_view()
        if v is not None:
            idx = self.win.tabs.indexOf(v)
            if idx >= 0:
                self.win.tabs.setCurrentIndex(idx)
            self.accept()

    def _close_sel(self):
        v = self._sel_view()
        if v is not None:
            idx = self.win.tabs.indexOf(v)
            if idx >= 0:
                self.win.close_tab(idx)
            self._reload()

    def keyPressEvent(self, e):
        if e.key() == Qt.Key.Key_Escape:
            self.reject()
        elif e.key() == Qt.Key.Key_Down and self.search.hasFocus():
            self.listw.setFocus()                  # arrow from the search into the list
        else:
            super().keyPressEvent(e)


# ============================================================================
#  DEL 14A2 - WATCHED PAGES MANAGER  (Update Scanner list; ESC closes)
# ----------------------------------------------------------------------------
#  Lists every watched page with its status (changed / ok / error / new), and
#  lets you Open (clears the "changed" flag), Check now, set the interval,
#  rename-by-reopening, or remove a watch.
# ============================================================================
class WatchOptionsDialog(QDialog):
    """Ask how a page should be watched: how often (default every 6 hours),
    whether to ignore number changes, and the minimum changed-character count."""

    def __init__(self, window, initial=None):
        super().__init__(window)
        self.setWindowTitle(APP_NAME + " - Watch options")
        self.setModal(True)
        self.setStyleSheet(dialog_qss())
        apply_window_icon(self)
        ini = initial or {}
        lay = QVBoxLayout(self)

        lay.addWidget(QLabel("How often should this page be checked?"))
        irow = QHBoxLayout()
        irow.addWidget(QLabel("Every"))
        self.sp_every = QSpinBox(); self.sp_every.setRange(1, 999)
        irow.addWidget(self.sp_every)
        self.cmb_unit = QComboBox(); self.cmb_unit.addItems(["minutes", "hours", "days"])
        irow.addWidget(self.cmb_unit); irow.addStretch(1)
        lay.addLayout(irow)
        self._set_interval(int(ini.get("interval_min", 360)))    # default = every 6 hours

        self.chk_nums = QCheckBox("Ignore number changes (prices, counts, dates, times)")
        self.chk_nums.setChecked(bool(ini.get("ignore_numbers", False)))
        lay.addWidget(self.chk_nums)

        mrow = QHBoxLayout()
        mrow.addWidget(QLabel("Only alert if at least this many characters change:"))
        self.sp_min = QSpinBox(); self.sp_min.setRange(1, 100000)
        self.sp_min.setValue(int(ini.get("min_change", 20)))
        mrow.addWidget(self.sp_min); mrow.addStretch(1)
        lay.addLayout(mrow)

        brow = QHBoxLayout(); brow.addStretch(1)
        for txt, fn, default in (("OK", self.accept, True), ("Cancel", self.reject, False)):
            b = QPushButton(txt)
            b.setDefault(default)
            b.setStyleSheet("QPushButton{background:%s; color:%s; border:none; padding:6px 16px;"
                            "border-radius:6px;}QPushButton:hover{background:%s;}"
                            % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
            b.clicked.connect(fn)
            brow.addWidget(b)
        lay.addLayout(brow)

    def _set_interval(self, mins):
        if mins % 1440 == 0 and mins >= 1440:
            self.sp_every.setValue(mins // 1440); self.cmb_unit.setCurrentText("days")
        elif mins % 60 == 0 and mins >= 60:
            self.sp_every.setValue(mins // 60); self.cmb_unit.setCurrentText("hours")
        else:
            self.sp_every.setValue(mins); self.cmb_unit.setCurrentText("minutes")

    def _interval_min(self):
        u = self.cmb_unit.currentText()
        return self.sp_every.value() * (1440 if u == "days" else 60 if u == "hours" else 1)

    def get(self):
        """Show modally; return the chosen options dict, or None if cancelled."""
        if self.exec():
            return {"interval_min": self._interval_min(),
                    "ignore_numbers": self.chk_nums.isChecked(),
                    "min_change": int(self.sp_min.value())}
        return None

    def keyPressEvent(self, e):
        if e.key() == Qt.Key.Key_Escape:
            self.reject()
        else:
            super().keyPressEvent(e)


class WatchManagerDialog(QDialog):
    def __init__(self, window):
        super().__init__(window)
        self.win = window
        self.setWindowTitle(APP_NAME + " - Watched pages")
        self.setModal(True)
        self.resize(640, 520)
        self.setStyleSheet(dialog_qss())
        apply_window_icon(self)
        lay = QVBoxLayout(self)
        hint = QLabel("Pages are checked in the background. Double-click a changed "
                      "page to open it (that clears the ‘changed’ mark).")
        hint.setWordWrap(True)
        hint.setStyleSheet("color:%s; font-size:9pt;" % C_STATUS_FG)
        lay.addWidget(hint)

        self.listw = QListWidget()
        self.listw.setStyleSheet(
            "QListWidget{background:%s; border:1px solid %s; border-radius:6px;}"
            "QListWidget::item{padding:6px;}"
            "QListWidget::item:selected{background:%s; color:%s;}"
            % (C_ADDR_BG, C_BORDER, C_ACCENT, C_ACCENT_FG))
        self.listw.itemDoubleClicked.connect(lambda _i: self._open())
        lay.addWidget(self.listw, 1)
        self._reload()

        # ---- "Check all now" row ----
        self._pending = set()   # URLs currently being checked
        row_all = QHBoxLayout()
        self.btn_check_all = QPushButton("🔄  Check ALL now")
        self.btn_check_all.setStyleSheet(
            "QPushButton{background:%s; color:%s; border:none; padding:6px 14px;"
            "border-radius:6px; font-weight:bold;}QPushButton:hover{background:%s;}"
            % (C_ACCENT, C_ACCENT_FG, C_ACCENT_HOV))
        self.btn_check_all.clicked.connect(self._check_all_now)
        row_all.addWidget(self.btn_check_all)
        self.lbl_check_all = QLabel("")
        self.lbl_check_all.setStyleSheet("color:%s; font-size:9pt;" % C_STATUS_FG)
        row_all.addWidget(self.lbl_check_all)
        row_all.addStretch(1)
        lay.addLayout(row_all)

        row = QHBoxLayout()
        for txt, fn in (("↗  Open", self._open), ("🔄  Check now", self._check_now),
                        ("⚙  Edit options...", self._edit_options),
                        ("✓  Clear changed", self._clear_changed),
                        ("🗑  Remove", self._remove), ("Close", self.accept)):
            b = QPushButton(txt)
            b.setStyleSheet("QPushButton{background:%s; color:%s; border:none; padding:6px 12px;"
                            "border-radius:6px;}QPushButton:hover{background:%s;}"
                            % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
            b.clicked.connect(fn)
            row.addWidget(b)
        lay.addLayout(row)

        # Listen for watcher results while dialog is open → refresh list live
        self.win._watcher.result.connect(self._on_result)

    def _check_all_now(self):
        """Fire off a background check for every watched page at once."""
        ws = self._watches()
        if not ws:
            self.lbl_check_all.setText("No pages being watched.")
            return
        self._pending = {w["url"] for w in ws if w.get("url")}
        if not self._pending:
            return
        now = int(time.time())
        for w in ws:
            if w.get("url") in self._pending:
                w["last_checked"] = now
                self.win._watcher.check(w["url"])
        self.btn_check_all.setEnabled(False)
        self.lbl_check_all.setText("Checking %d page%s…" % (
            len(self._pending), "" if len(self._pending) == 1 else "s"))

    def _on_result(self, url, _text, _error):
        """Called each time any check finishes while dialog is open."""
        self._pending.discard(url)
        self._reload()
        n = len(self._pending)
        if n:
            self.lbl_check_all.setText("Checking… %d left" % n)
        else:
            if self.lbl_check_all.text().startswith("Checking"):
                self.lbl_check_all.setText("All done ✓")
                QTimer.singleShot(3000, lambda: self.lbl_check_all.setText(""))
            self.btn_check_all.setEnabled(True)

    def _watches(self):
        return self.win.settings.setdefault("page_watches", [])

    def _reload(self):
        self.listw.clear()
        for w in self._watches():
            if w.get("error"):
                status = "⚠ error"
            elif w.get("changed"):
                status = "🔴 CHANGED"
            elif w.get("baseline"):
                status = "🟢 ok"
            else:
                status = "… new"
            when = (time.strftime("%Y-%m-%d %H:%M", time.localtime(w["last_checked"]))
                    if w.get("last_checked") else "never")
            extra = "every %s" % self.win._interval_label(w.get("interval_min", 360))
            if w.get("ignore_numbers"):
                extra += " · ignore numbers"
            extra += " · ≥%d chars" % int(w.get("min_change", 1))
            it = QListWidgetItem("%s   %s\n        %s · checked %s"
                                 % (status, (w.get("title") or w.get("url", ""))[:60],
                                    extra, when))
            it.setToolTip(w.get("url", "") + (("\n" + w["error"]) if w.get("error") else ""))
            self.listw.addItem(it)

    def _cur(self):
        i = self.listw.currentRow()
        ws = self._watches()
        return ws[i] if 0 <= i < len(ws) else None

    def _open(self):
        w = self._cur()
        if w and w.get("url"):
            w["changed"] = False
            save_json(SETTINGS_FILE, self.win.settings)
            self.win._update_watch_badge()
            self.win.add_tab(w["url"], switch=True)
            self.accept()

    def _check_now(self):
        w = self._cur()
        if w:
            w["last_checked"] = int(time.time())
            self.win._watcher.check(w["url"])
            show_toast(self.win, "Checking now…")

    def _edit_options(self):
        w = self._cur()
        if not w:
            return
        opts = WatchOptionsDialog(self.win, w).get()
        if opts is not None:
            re_baseline = (opts["ignore_numbers"] != w.get("ignore_numbers"))
            w.update(opts)
            if re_baseline:                          # normalisation changed -> re-baseline
                self.win._watch_cache.pop(w.get("url"), None)
                save_json(WATCH_CACHE_FILE, self.win._watch_cache)
                w["baseline"] = False
                w["changed"] = False
                self.win._watcher.check(w["url"])
            save_json(SETTINGS_FILE, self.win.settings)
            self.win._update_watch_badge()
            self._reload()

    def _clear_changed(self):
        w = self._cur()
        if w:
            w["changed"] = False
            save_json(SETTINGS_FILE, self.win.settings)
            self.win._update_watch_badge()
            self._reload()

    def _remove(self):
        i = self.listw.currentRow()
        ws = self._watches()
        if 0 <= i < len(ws):
            url = ws[i].get("url")
            del ws[i]
            self.win._watch_cache.pop(url, None)         # drop its cached text too
            save_json(WATCH_CACHE_FILE, self.win._watch_cache)
            save_json(SETTINGS_FILE, self.win.settings)
            self.win._update_watch_badge()
            self._reload()

    def keyPressEvent(self, e):
        if e.key() == Qt.Key.Key_Escape:
            self.accept()
        else:
            super().keyPressEvent(e)


# ============================================================================
#  FEATURE INDEX  — searched by FeatureSearchDialog
#  Each entry: (display_name, where_to_find, description, search_keywords)
# ============================================================================
FEATURE_INDEX = [
    # ── Settings ──────────────────────────────────────────────────────────
    ("Search engine",
     "⚙ Settings → Startup & tabs",
     "Choose which search engine is used when you type words (not a URL) in the address bar. Presets include Google, Bing, DuckDuckGo, Brave, Kagi and more. Pick 'Custom URL…' to use any engine — put {} where the query goes.",
     "search engine google bing duckduckgo brave kagi startpage yahoo perplexity custom url query"),

    ("Home page",
     "⚙ Settings → Startup & tabs",
     "The URL that the ⌂ Home button and 'On launch: home' use. You can also set it via ☰ → Set current page as home.",
     "home homepage start page url default"),

    ("On launch — startup mode",
     "⚙ Settings → Startup & tabs",
     "What happens when WhyBrowse starts: 'restore' re-opens last session's tabs, 'home' opens the home page, 'blank' opens an empty tab.",
     "startup launch start restore session mode blank home"),

    ("New tab — what opens",
     "⚙ Settings → Startup & tabs",
     "When you press Ctrl+T or click +, the new tab can open as a blank page or with your home page.",
     "new tab open blank home ctrl t"),

    ("Default 'Open link' action",
     "⚙ Settings → Startup & tabs",
     "Your favourite open-link choice (stay here or go there) shown in the middle and bottom of the right-click menu for quick one-click access.",
     "open link default action new tab stay go favourite right click menu"),

    ("Temp tab  🕒",
     "⚙ Settings → The temp tab  ·  right-click a link → 🕒 Open link in the TEMP tab  ·  right-click the address bar",
     "One tab set aside for pages you only want to look at. Opening something \"in temp\" REUSES that tab instead of making a new one, so you don't end up with twenty tabs. It sits at the top of the tab strip, right under the pinned tabs, marked 🕒. Nothing lands there by itself: only a bookmark you set to Temp, the page menu's \"Open link in the temp tab\", the address bar's right-click menu, or a \"same tab\" open that a locked/pinned tab would otherwise have turned into yet another tab — so clicking through items on Tradera or Vinted can never queue up there and overwrite each other. Set how many temp tabs take turns (1-9) in Settings. A temp tab you PIN or LOCK is never reused, which is how you rescue one you want to keep; you can also un-tick \"Temp tab\" in its right-click menu.",
     "temp tab temporary reuse reused one tab scratch look at later overwrite recycle 🕒 slots keep rescue"),

    ("How a bookmark opens (same / new / temp tab)",
     "⚙ Settings → The temp tab  ·  right-click the address bar  ·  right-click a bookmark on the bar",
     "Choose what a click on a bookmark does: open it in the SAME tab, a NEW tab, or the TEMP tab. There is a global default (Settings, or right-click the address bar → \"Bookmarks open, by default…\") and every single bookmark can override it — right-click it on the bar → \"⚙ A plain click on this one opens…\". The same right-click menu also has one-off \"Open in the same / a new / the temp tab\". If the tab you are standing on is LOCKED or pinned, an \"open in the same tab\" cannot navigate it, so it goes to the temp tab instead of spawning another tab (switchable in Settings).",
     "bookmark open same new temp tab default per bookmark override address bar right click locked pinned"),

    ("Arrange the page right-click menu",
     "⚙ Settings → The page right-click menu  ·  right-click page → ⚙ Arrange this menu…",
     "Put the page right-click menu in YOUR order. Drag any entry up or down, make your own sub-menus (📁 New sub-menu) and drag entries into them, add or remove separator lines, and park entries you never use in the Hidden bin. Preview shows the result before you save. ↺ Factory order puts everything back. Entries that only apply sometimes (link actions, 'un-hide elements', …) keep the place you gave them and simply stay out of the menu when they don't apply; the separators around them close up on their own. A new entry added by a later version of WhyBrowse is appended at the bottom instead of disappearing, and 'Arrange this menu…' itself can be moved but never hidden, so there is always a way back. Saved in Helpfiles/WhyBrowse/page_menu.json.",
     "arrange right click menu order drag reorder custom submenu folder categories hide entries separator layout context menu rearrange organise organize personalise page menu"),

    ("Ad blocker",
     "⚙ Settings → Privacy & blocking  ·  right-click page → 🎛 Features",
     "Blocks ads and trackers using a built-in filter list. You can add extra domains to block, or turn it off per-site via 'Exceptions for this site'.",
     "ad adblock ads tracker block blocker filter"),

    ("Extra domains to block",
     "⚙ Settings → Privacy & blocking",
     "Additional hostnames to block (one per line) on top of the built-in ad-block list.",
     "extra block domain custom list hosts ad tracker"),

    ("Block third-party cookies",
     "⚙ Settings → Privacy & blocking  ·  right-click page → 🎛 Features",
     "Stops cross-site tracking cookies. Can break single sign-on — disable per-site via 'Exceptions' or use the Stay signed in toggle.",
     "cookie cookies third party tracking cross-site block privacy"),

    ("Stay signed in (Google / Microsoft)",
     "⚙ Settings → Privacy & blocking",
     "While a Google or Microsoft tab is open, their third-party cookies are not blocked — keeps Google Sheets, Drive and Microsoft 365 working.",
     "google microsoft signed login sheets drive office 365 cookie"),

    ("Hide search results from domains",
     "⚙ Settings → Privacy & blocking",
     "Domains listed here are hidden from Google / Bing result pages. Useful for spammy or low-quality sites.",
     "search result block domain hide google bing spam site filter"),

    ("Native find-on-page (per domain)",
     "⚙ Settings → Privacy & blocking",
     "Sites where Ctrl+F is passed through to the page's own search (Google Docs, Notion, Figma…) instead of WhyBrowse's find bar.",
     "find ctrl f native page search docs notion figma site"),

    ("Hide cookie banners / nag bars",
     "⚙ Settings → Anti-annoyance  ·  right-click page → 🎛 Features",
     "Hides GDPR cookie consent popups, donation nag bars, and newsletter subscribe overlays across all sites.",
     "cookie banner nag gdpr popup subscribe donate hide"),

    ("Auto-accept cookies",
     "⚙ Settings → Anti-annoyance  ·  right-click page → 🎛 Features",
     "Automatically clicks 'Accept all' on cookie consent dialogs. Also unlocks scroll-blocked pages.",
     "cookie accept auto gdpr consent popup scroll"),

    ("YouTube ad blocker",
     "⚙ Settings → Anti-annoyance  ·  right-click page → 🎛 Features",
     "Skips and hides YouTube ads. If YouTube's anti-adblock wall appears, temporarily disable via the right-click menu on any YouTube page.",
     "youtube ads block skip video anti-adblock"),

    ("IMDb reference layout",
     "⚙ Settings → Anti-annoyance",
     "Rewrites IMDb movie/series pages to the cleaner 'reference' view with all info on one page.",
     "imdb movie film series reference layout"),

    ("Disable passkeys (use passwords)",
     "⚙ Settings → Anti-annoyance  ·  right-click page → 🎛 Features",
     "Forces sites that offer passkeys to fall back to the standard password login.",
     "passkey password login webauthn fido key"),

    ("Spoof location / fake city",
     "⚙ Settings → Pretend to be in another city",
     "Overrides the browser's geolocation API to report a chosen city's coordinates. Useful for weather sites, local news, or geo-restricted content.",
     "location gps city spoof fake geolocation coordinates"),

    ("Bookmarks bar position",
     "⚙ Settings → Bookmarks  ·  ☰ menu → Layout",
     "Place the bookmarks bar as a horizontal row at the top or a vertical panel on the right side.",
     "bookmark bar position top right panel layout"),

    ("Bookmark duplicate mode",
     "⚙ Settings → Bookmarks",
     "What to do when you bookmark a page already saved: ask, silently add a duplicate, or silently skip.",
     "bookmark duplicate already exists ask skip add"),

    ("Theme / colors / appearance",
     "⚙ Settings → Appearance",
     "Switch between Dark, Light, and White presets, or fine-tune every individual color (toolbar, tabs, address bar, accent).",
     "theme color colour dark light white appearance style background"),

    ("Tab auto-sleep (memory saving)",
     "⚙ Settings → Performance  ·  right-click tab → Not auto-sleep",
     "Every idle background tab is unloaded automatically to save memory - including the tabs of profiles you are not in. Opt a single tab or domain OUT by right-clicking it. Adjust the idle delay here.",
     "sleep auto tab memory idle background suspend discard performance"),

    ("Auto-refresh tabs",
     "⚙ Settings → Performance  ·  right-click tab → Auto-refresh",
     "Tabs marked 'Auto-refresh' reload themselves the moment you come back to them - switching tabs OR switching profiles - once their delay has passed. Good for dashboards and live data; never reloads while it's just sitting on screen in front of you.",
     "refresh auto reload tab live dashboard timer interval"),

    ("Scroll speed",
     "⚙ Settings → Performance",
     "Multiplier for the mouse-wheel scroll distance. 1.0 = browser default, 1.5 = 50% faster.",
     "scroll speed wheel mouse fast slow"),

    ("Per-site scroll speed",
     "Right-click a page → Exceptions → 🖱 Scroll speed here",
     "An extra multiplier for THIS site only, stacked on top of the global Settings → Performance speed (e.g. global 1.3x × 2.4x here = 3.12x). Choose Off to fall back to the global speed.",
     "scroll speed per site wheel mouse fast slow multiplier exception"),

    ("Per-site browser identity (user agent)",
     "Right-click a page → 🌐 Exceptions for <site> → 🧭 Browser identity here",
     "Makes ONE site see a different browser (Firefox, Chrome, Edge or your own user-agent text) while every other site keeps the automatic identity from Settings. Use it when a site works in Firefox but not here. The page reloads when you pick. 'Clear exceptions for this site' puts the site back to automatic. Limit: Chromium's own client-hint headers (Sec-CH-UA) are still sent, so a site that cross-checks those can still tell. Amazon shops (amazon.se, .com, .de ...) are set to 'Engine default' automatically, because Amazon often showed its error page ('Ett oväntat fel har inträffat') for the cleaned-up Chrome identity; pick Chrome, Firefox or Edge here to override that.",
     "user agent identity firefox chrome edge per-site site browser works in firefox exception spoof ua amazon error page unexpected error engine default"),

    ("Form memory / auto-fill fields",
     "⚙ Settings → Performance  ·  right-click a field → 💾 Remember this field",
     "Auto-save form field values as you type (global). Turn off and use right-click → Remember per-field instead.",
     "form field memory autofill auto fill remember input"),

    ("Google Sheets — remember last cell",
     "⚙ Settings → Performance",
     "Returns to the last active cell when you reload or switch back to a Google Sheets tab.",
     "sheets google cell row remember position"),

    ("Download folder",
     "⚙ Profile settings  ·  ☰ → Downloads",
     "Default folder for downloaded files, set per profile. Add favourite quick-save folders via right-click page → ⬇ Quick-download.",
     "download save folder directory path file profile"),

    ("Stuck page - no scrollbar, wheel does nothing",
     "Right-click the page → 🔓 Get scrolling back  ·  Settings → Performance",
     "A site stops the page behind a pop-up from scrolling, and if that pop-up is "
     "hidden or removed by anything other than the site's own close button, the "
     "lock is never lifted - no scrollbar, dead mouse wheel, only a reload fixes "
     "it. WhyBrowse now watches for that and releases the lock by itself, but "
     "only when nothing visible is actually covering the page (a real dialog is "
     "SUPPOSED to stop the page behind it). If one still sticks, right-click → "
     "🔓 Get scrolling back releases it at once, with no reload. Turn the "
     "automatic part off globally in Settings → Performance, or for one site "
     "under 🌐 Exceptions for this site.",
     "scroll scrollbar stuck frozen locked wheel mouse cannot scroll overflow "
     "hidden modal popup tradera refresh reload"),

    ("Save image / Save image as",
     "Right-click a picture on the page",
     "Right-clicking a picture gives \U0001f5bc Copy image, \U0001f4be Save image, "
     "\U0001f4be Save image as\u2026, \u2398 Copy image address and \u2197 Open image in "
     "a new tab. Save image drops it straight into your download folder under its own "
     "name, no pop-up; Save image as\u2026 opens the pop-up, where the name is split "
     "into a name box (focused, ready to type) and a small extension box left untouched "
     "(change it only when you want to, e.g. jpeg \u2192 jpg). Right-clicking a video "
     "or a sound gives its address too. The folder and the same-name choice below apply "
     "to a saved image. Move or hide any of these in \u2699 Arrange this menu\u2026",
     "image picture photo copy save download img address url canvas video audio "
     "extension jpeg jpg rename right click context menu"),

    ("Same name already there  (backup old / overwrite)",
     "⚙ Settings → Downloads  ·  and the pop-up itself",
     "What happens when a download clashes with a file you already have. "
     "\"Back up the old one\" renames the old file to Backup<CODE>-name (the same "
     "convention and the same code list File_manager uses) and lets the new file "
     "take the clean name — so saving the same program over and over stops piling "
     "up Foo (1), Foo (2), Foo (3). A file that ARRIVES already numbered counts as "
     "the same file too: \"Foo (3).py\" landing next to \"Foo.py\" is recognised as "
     "another copy of it. The other choices are the old behaviour (save with a "
     "number) and overwrite without a backup. Nothing is deleted until the download "
     "has actually finished — if it fails, your old file is put back.",
     "duplicate same name exists overwrite backup old replace copy suffix "
     "brackets number download clash conflict already"),

    # ── Toolbar ───────────────────────────────────────────────────────────
    ("Address bar",
     "Toolbar — main address field",
     "Shows and edits the current page address. Type a URL or search query and press Enter. Ctrl+L focuses it. The 🅰 icon selects all; 🅲 copies.",
     "address bar url navigate location toolbar ctrl l"),

    ("Quick-navigate ('This tab →')",
     "Toolbar — 'This tab →' box",
     "Always-empty navigation box: type and press Enter to load in the current tab. Clears after each use — no need to select the old URL first.",
     "quick navigate this tab field address type box"),

    ("New-tab field ('New tab ↗')",
     "Toolbar — 'New tab ↗' box",
     "Type and press Enter to open a URL in a brand-new tab directly — skipping the Ctrl+T + type step.",
     "new tab open field address navigate box"),

    ("Profile badge / profiles",
     "Toolbar — numbered circle (1 / 2 / 3…)",
     "Each profile has its own cookies, logins, history and tabs. Click the badge for a quick-switch; hover for the full profile menu (add, rename, delete).",
     "profile account switch badge cookie session login multiple"),

    ("Container tabs (separate logins, no profile switch)",
     "Right-click a tab → 🫙 Containers (separate logins)",
     "Have several accounts of the SAME site open at once in ONE window — e.g. two Gmail or two ChatGPT accounts as two tabs, each staying logged in on its own. A container is its own cookie store; unlike profiles you don't switch away to use it. Right-click a tab → 🫙 Containers to make a new container tab, open the current page in a container, or rename/colour/delete containers. Container tabs are marked with the container name and come back logged in after a restart.",
     "container containers separate login logins multiple accounts same site gmail chatgpt second account without switching profile cookie jar isolation multi-account"),

    ("Mute / volume",
     "Toolbar — 🔊 speaker button",
     "Left-click mutes/unmutes the current tab. Right-click shows a per-tab volume slider and mute-all buttons.",
     "mute volume sound audio speaker unmute tab"),

    ("Clean / plain mode (🧹)",
     "Toolbar — 🧹 button",
     "Temporarily turns off all WhyBrowse features for the current tab. Button turns coloured when active; click again to restore.",
     "clean plain mode off disable features temporary tab"),

    ("Tab list / search all tabs (🗂)",
     "Toolbar — 🗂 button  ·  Ctrl+Shift+A",
     "Shows all open tabs in a searchable list. Type to filter by title or URL. Handy when you have many tabs open.",
     "tab list search all switch find overview ctrl shift a"),

    ("Print / Save as PDF (🖨)",
     "Ctrl+P  ·  ☰ menu  ·  right-click page → 🖨 Print / Save as PDF",
     "Save the current page as a PDF file. Pick where to save; the default name is the page title and the default folder is this profile's download folder.",
     "print pdf save export ctrl p paper document"),

    ("Fix stuck mouse-wheel scrolling (🖱)",
     "right-click page → 🌐 Exceptions for <site> → 🖱 Fix stuck mouse-wheel scrolling here",
     "For pages where the mouse wheel won't scroll an inner panel (e.g. Tradera invoices), this makes WhyBrowse drive the scroll of the element under the cursor for that site.",
     "scroll wheel mouse stuck fix tradera invoice inner panel"),

    ("Low-vision / zoom (🔎)",
     "Toolbar — 🔎 button",
     "Toggle large-zoom + minimum-font mode. Scroll the button to adjust zoom; Shift+scroll adjusts font size; right-click resets to defaults.",
     "zoom size font low vision accessibility big large text"),

    ("CP — Copy-Paste field memory",
     "Toolbar — CP button",
     "Click a field, click CP, type a value, click CP again to save. Next time: click the field and CP — it fills automatically. Works on any field.",
     "cp copy paste field fill memory autofill"),

    ("Translate (🌍)",
     "Toolbar — 🌍 button  ·  right-click page → 🌍 Translate",
     "Left-click: translate the current page via Google Translate. Right-click: translate selected text, or change the target language.",
     "translate translation language google foreign text page"),

    ("Virtual keyboard (⌨)",
     "Toolbar — ⌨ icon  ·  Ctrl+Shift+K",
     "On-screen keyboard for mouse-only typing. Supports multiple layouts. Drop .json layout files in the keyboard_layouts folder.",
     "keyboard virtual on-screen osk mouse type layout ctrl shift k"),

    # ── Right-click on page ───────────────────────────────────────────────
    ("Snippets / saved words",
     "Toolbar 📝  ·  right-click page → 📝 Saved words / snippets",
     "Store text you type often (per-domain, per-profile, or all sites). The toolbar 📝 button opens a menu with this page's words and all-site words at the top - click one to drop it into the focused field - plus 'Save a new word…' and 'Manage saved words…'. You can also right-click a field to paste a snippet, or select text and right-click to save it.",
     "snippet snippets saved words text paste fill quick clip domain toolbar button"),

    ("Remember field value",
     "Right-click a field → 💾 Remember this field's value",
     "Manually save the value of any form field for auto-fill on your next visit. Per-field opt-in alternative to global Form memory.",
     "field remember autofill form value save fill input"),

    ("Freeze element (stop moving)",
     "Right-click page → 🧊 Stop an element from moving",
     "Click any page element to lock it in place. Useful for floating buttons or sticky bars that cover content.",
     "freeze element stop moving lock sticky fixed overlay"),

    ("Hide / zap element",
     "Right-click page → ✂ Hide an element",
     "Click any element to permanently hide it on this site. Un-hide via right-click → Show hidden.",
     "hide zap element remove block cosmetic ad widget"),

    ("Sticky section (pin to top)",
     "Right-click page → 📌 Freeze a section to the top",
     "Pins any page section to stay fixed at the top while you scroll. Good for disappearing navigation bars.",
     "sticky pin top section freeze header fixed scroll"),

    ("Site macro (record & replay)",
     "Right-click page → 🎬 Site macro",
     "Record a series of clicks and text inputs and replay them with one click. Can auto-run on every visit.",
     "macro record replay automate click sequence auto site"),

    ("Watch page for changes",
     "Right-click page → 🔭 Watch this page",
     "Monitors a page and shows a notification when its content changes.",
     "watch monitor change alert notify update page"),

    ("Download video / audio",
     "Right-click page → ⬇  ·  ☰ menu → Download video/audio",
     "Built-in media downloader (yt-dlp). Works with YouTube, Vimeo and hundreds of other sites. Right-click a link to download from that specific URL.",
     "download video audio youtube mp4 mp3 media yt-dlp"),

    ("Torrents & magnet links",
     "☰ menu → 🧲 Torrents  ·  Settings → Torrents & magnet links",
     "Clicking, pasting or COPYING a magnet: link (or a .torrent address) is "
     "acted on instead of ignored: download the files with the built-in engine "
     "(libtorrent), save the link as a .magnet file in your torrent folder, or "
     "hand it to your own torrent program. Separate torrent folder, ask/auto/"
     "ignore, speed limits, resume after a restart.",
     "torrent magnet bittorrent libtorrent .torrent seed peer swarm download "
     "clipboard x: folder qbittorrent"),

    ("Split view",
     "Right-click page → ⊞ Split view",
     "Opens a second address bar and page view beside the current one. Close with right-click → ⊟ Close split view.",
     "split view side two panel dual second screen"),

    ("View page source",
     "Right-click page → 🔍 View page source",
     "Opens the raw HTML of the current page in a new tab (view-source: URL).",
     "source html code view inspect raw"),

    ("Feature toggles (global / per-site)",
     "Right-click page → 🎛 Features  ·  right-click page → 🌐 Exceptions for <site>",
     "Toggle all WhyBrowse features on/off globally (🎛 Features), or override them for just the current site (🌐 Exceptions).",
     "feature toggle site exception override per-site disable global"),

    ("Troubleshoot — page not loading",
     "Right-click page → 🔧 Troubleshoot",
     "Three tools in one submenu: 'Why isn't this page loading?' shows active features that could block the page; 'Find what's breaking' disables features one at a time to isolate the cause; 'Open in system browser' bypasses WhyBrowse entirely.",
     "troubleshoot broken loading fix debug diagnose system browser"),

    ("Stuck on \"Verify you are human\"",
     "Right-click page → 🔧 Troubleshoot → 🤖 Stuck on \"Verify you are human\"  ·  Settings → Privacy & blocking",
     "Cloudflare / hCaptcha checks need their own (third-party) cookie, unblocked network requests and an unfrozen page — the ad blocker, cookie block and animation freeze each break one, so the check loops forever. Verification providers are now always exempt, navigator.userAgentData is kept in step with the reported user-agent, and the first time a site shows such a wall the blocking features are turned off for that site and the page reloads once.",
     "captcha cloudflare turnstile hcaptcha recaptcha verify human bot check loop stuck predb datadome arkose"),

    ("Password vault / login autofill",
     "Right-click page → 🔑 Passwords  ·  ☰ menu",
     "Stores and auto-fills login credentials. Lock/unlock with a PIN. The ⌨ toolbar key icon fills your saved login into the last-clicked field.",
     "password vault login credential autofill pin secure key"),

    ("User add-ons (scripts / CSS)",
     "Right-click page → 🧩 User add-ons  ·  ☰ menu",
     "Drop .js or .css files into the add-ons folder to inject them on matching sites. Enable/disable per script without restarting.",
     "addon add-on userscript script css inject custom js"),

    # ── Tab right-click ───────────────────────────────────────────────────
    ("Rename tab",
     "Right-click a tab → Rename",
     "Give a tab a custom title that sticks across reloads, saved per URL or per site.",
     "rename tab name title custom"),

    ("Lock tab",
     "Right-click a tab → Lock",
     "Prevents the tab from being closed or accidentally navigated away.",
     "lock tab protect prevent close navigate"),

    ("Pop out — floating window",
     "Right-click a tab → 🪟 Pop out to floating window",
     "Opens the tab in a small always-on-top floating window. Great for video or quick-reference content.",
     "pop float window tab detach overlay top picture-in-picture"),

    ("Not auto-sleep (keep one tab loaded)",
     "Right-click a tab → ☕ Not auto-sleep",
     "Auto-sleep is ON for every idle background tab. Tick this to leave one tab - or a whole domain - out of it, so it stays loaded. Starts off on every new tab.",
     "awake keep tab sleep prevent media live nosleep exempt"),

    ("Sleep delay for one tab or domain",
     "Right-click a tab → 💤 Sleep delay",
     "Give one tab, or a whole domain, its own idle delay instead of the general one - e.g. claude.ai an hour while everything else sleeps after 5 minutes. A delay set by hand also lets a built-in never-sleep site sleep after all.",
     "sleep delay minutes per domain site override idle timeout claude"),

    ("Auto-refresh a tab",
     "Right-click a tab → Auto-refresh",
     "The tab reloads itself when you switch back to it (after the minimum delay set in Settings).",
     "refresh auto reload tab live dashboard"),

    ("Go to row / cell (Google Sheets)",
     "Right-click a Sheets tab → 📊 Go to row / cell",
     "Jump directly to a row number or cell reference (e.g. B42) in Google Sheets without scrolling.",
     "sheets google row cell jump go navigate"),

    ("Upload folder for this site (per-site upload start folder)",
     "Right-click a tab → THIS DOMAIN → 📤 Upload folder for this site…  ·  Settings → Uploads",
     "When a site asks you to pick a file to UPLOAD, browsers open in whatever folder you last picked a file in ANYWHERE — so a site whose files live on another drive (e.g. B:) keeps starting on C:. This gives each site its own start folder. A pop-up offers your favourite folders as a one-click list (add/remove them right there), plus 'Browse the computer…' for a one-off, and a tick to make the picked folder that site's folder from then on. Choose when the pop-up shows in Settings → Uploads (only when a site has no folder / every time / never). The picker opens in the folder you last picked from on that site (for 3 hours) and its left column holds your pinned folders (the Pin this folder button; same as favourites), the site's folder, your last 12 upload folders, Desktop/Documents/Pictures/Downloads and the drives; Remove this folder from the list unpins it and drops it from the recent list; Settings → Uploads can switch back to the Windows picker. Downloads are separate and still all go to your one download folder.",
     "upload folder per site send file picker start directory bandcamp b: drive favourite folders wrong folder attach browse"),

    ("Jump to a word on this site",
     "Right-click a tab → THIS DOMAIN → 🔎 Jump to a word on this site…",
     "Save a word or phrase per site; every time a page there opens, WhyBrowse scrolls to the first place that word appears (and briefly highlights it). Choose to land on the row above, exactly on, or below the word. Read-only DOM search — it never types anything, and it scrolls inner panels too. For Google Sheets use its own Ctrl+F instead (the grid is a canvas the browser can't read).",
     "jump word find scroll to text phrase land row above below remember position content search per site"),

    # ── ☰ Menu + general ─────────────────────────────────────────────────
    ("Bookmarks",
     "☰ menu → 🔖 Bookmarks  ·  bookmarks bar",
     "Add, manage and browse bookmarks. Import from Firefox. View or import from other profiles. The bar can be horizontal (top) or vertical (right).",
     "bookmark favourite favorite save star folder bar import firefox"),

    ("Google won't let this profile sign in (\"browser may not be secure\")",
     "☰ menu → 🔑 Bring a Google sign-in over from Firefox…  ·  Settings → Privacy & blocking",
     "Two fixes. Settings → Privacy & blocking → \"Present a complete Chrome identity\" makes the engine stop contradicting its own user-agent (it sent \"Chromium\" in Sec-CH-UA while claiming to be Chrome, had an empty window.chrome and no Accept-Language at all) — that mismatch is what Google's sign-in reads as an unsafe browser. If Google still refuses, sign in to Google in Firefox and use the menu item to copy that finished session into one chosen profile; it skips Google's check entirely.",
     "google drive sign in login secure browser app may not be secure "
     "cannot log in couldnt sign you in try again cookies import firefox "
     "session profile gmail sheets docs chrome identity sec-ch-ua user agent"),

    ("Favourites (shared list, each link keeps its own login)",
     "⭐ Favourites button on the bookmarks bar  ·  Ctrl+Shift+B  ·  ☰ menu → ⭐ Favourites",
     "WHERE THEY ARE: the ⭐ Favourites button at the left end of the bookmarks bar, or Ctrl+Shift+B for the full window (search, rename, reorder, change which login a link opens with, remove) — plus the ☰ menu as before. Hide the bar button by right-clicking the bookmarks bar. One global starred list shared by EVERY profile (unlike normal bookmarks, which are per-profile) where each favourite remembers WHICH login it opens with. Right-click any bookmark or page → 'Add to Favourites' to save it under your current profile's login, or 'Add … using login…' to bind it to another profile or a container. Open/remove from ☰ menu → ⭐ Favourites (grouped by login). Because each entry carries its own login you can star the same site under two accounts — e.g. two Gmail accounts — and open both in the same window at once without switching profiles; a favourite bound to a different login opens as a tab labelled with that account's name.",
     "favourite favorite favourites favorites star shared global all profiles collection curated login account gmail multiple accounts container same window"),

    ("Help mode (❓ hover anything and it explains itself)",
     "F1  ·  ❓ button in the toolbar  ·  Esc to leave",
     "Turns the browser into its own manual. With help mode on, moving the mouse over a toolbar button, menu entry, bookmark or field shows a panel naming what it is, where it lives and what it does, with a 'More' button for the full explanation — which stays expanded as you move along, so you can read your way down a row of buttons. The panel never takes focus, so browsing keeps working while it is up. It shows the control's own tooltip and looks up the matching entry from this same feature list, so the two can never drift apart. Known toolbar controls are mapped exactly; everything else is matched on wording.",
     "help mode hover explain what is this f1 question mark tooltip guide manual learn discover hjälp hovra förklara"),

    # ---- Entries added after an audit of what the index was missing ----
    ("Profile 99 “Favourites” (all starred links as one profile)",
     "Profile badge → ⭐ Show the “99 Favourites” profile  ·  switch to profile 99",
     "A profile whose bookmarks bar IS your whole starred list, each link painted in the colour of the account it belongs to and each one still opening AS that account — so two logins on the same site sit side by side in one window. It holds no logins itself: a profile IS a cookie jar, and two accounts on one site cannot share a jar, so instead each link is lent the jar it came from. Its bookmarks are generated from favourites.json on every rebuild and never written to disk, so right-clicking one edits the FAVOURITE. A new address typed while in profile 99 has no account to guess and opens signed out. Toggle it in the profile menu; removing it never touches your favourites.",
     "profile 99 favourites favorites all accounts logins one place cookie jar star bookmarks bar generated lend login"),

    ("Pin a tab (it never drifts to another page)",
     "Right-click a tab → 📌 Pin",
     "A pinned tab always keeps the page you pinned. Clicking a link there, or the site navigating itself to a different document, opens a NEW tab instead of taking the pinned page away — which is why a pinned Vinted or Google Sheets stays put. Pinning is strictly per tab: nothing auto-unpins it. A same-document move (only the #fragment or ?query changing, e.g. switching sheet tabs by gid) stays in place and works normally.",
     "pin pinned tab keep page fixed stays lock drift vinted sheets"),

    ("Tookmarks (see another profile's bookmarks, live)",
     "☰ menu → Tookmarks  ·  👻 Tookmarks folder on the bookmarks bar",
     "An opt-in, read-only folder on your bookmarks bar showing ONE other profile's bookmarks live, without copying anything. Per profile: pick which profile it mirrors in the menu or Settings. Use it when an account's links are filed under a different profile than the one you are working in.",
     "tookmarks other profile bookmarks live mirror read-only shared see across profiles"),

    ("Copymarks (physically copy other profiles' bookmarks here)",
     "☰ menu → Bookmarks → Copymarks",
     "Physically COPIES every other profile's bookmarks into the current profile, each under its own 'Copymarks: <name>' folder. Unlike Tookmarks (which shows them live without copying) this duplicates them, which is useful as a backup before you tidy up elsewhere but can get messy. It asks first.",
     "copymarks copy bookmarks from other profiles duplicate backup merge"),

    ("Quick links / saved sub-pages (per site)",
     "Right-click page → 🔗 Quick links / saved sub-pages",
     "Save any sub-page of a site — a finished search URL, a filtered list, a particular section — and jump straight back to it later from the page's right-click menu. Better than a macro for anything that ends at a fixed address, because it survives the site changing its layout.",
     "quick links saved sub-pages search url shortcut per site jump bookmark section"),

    ("Address shortcuts (type a keyword, land on a site)",
     "Right-click the address bar → ⌨ Address shortcuts",
     "Bind a short keyword to one site — 'b' for boardgamegeek.com, 'bl' for blocket.se, 't' for tradera.com. Type it in the New tab box, the This tab box, or the main address bar and it inline-completes the site the instant the keyword matches, with the completed part pre-selected so Enter accepts it and typing on replaces it. Different from the ordinary address suggestions, which are a fuzzy match over your whole history and bookmarks rather than one deterministic site per keyword.",
     "address shortcuts keyword nickname bookmarklet jump letter type site new tab this tab autocomplete inline complete"),

    ("Phone sync (the Android app Issu's WhyBrowse)",
     "☰ menu → 📱 Phone sync...  ·  🔖 button → 📱 Phone sync...",
     "Share profiles, bookmarks and address shortcuts with the phone app through a small relay server of your own. You choose what goes: tick a profile "
     "(only its name, colour and badge are shared - never logins or cookies), then tick 'Share ALL bookmarks' or single folders / links, and tick the "
     "shortcuts. 'Server...' takes a code, or the relay.json made by the relay installer; 'Copy code for the phone' puts a code on the clipboard that "
     "you paste in the app (Settings > Sync > Paste code) - no typing of addresses or keys. What you add on the phone comes back: a profile made on "
     "the phone becomes a profile of its own here, bookmarks added on the phone land in the profile they were added to, shortcuts added on the phone "
     "appear here. The phone is subordinate: a bookmark that came FROM here and is deleted on the phone is only hidden from the phone (the PC copy "
     "stays; 'Show them on the phone again' brings them back); a bookmark the phone made and later deletes is deleted here too. Deleting or unticking "
     "something here removes it from the phone. Sync runs by itself a few seconds after start and every 10 minutes.",
     "phone sync android app mobile bookmarks profiles shortcuts relay code paste server share"),

    ("Back to the first page  ◀  /  a copy of this page  ▶",
     "Right-click the ◀ Back arrow  ·  right-click the ▶ Forward arrow",
     "Right-click ◀ Back and you jump all the way to the FIRST page of this tab "
     "instead of stepping back one page at a time — the bookmark you opened, the "
     "search results you came in through, the page that started the tab. Blank/new-tab "
     "pages are skipped, so you never land on an empty page. Right-click ▶ Forward "
     "and you get a COPY of the page you are on in a new tab beside this one, and you "
     "land in the copy — click on from there and the original stays where it was. "
     "The Forward arrow is greyed out when there is nothing forward, but it stays "
     "clickable so its right-click always works.",
     "back first page start of tab origin beginning all the way back forward duplicate "
     "copy same page new tab clone right click arrow nav history"),

    ("Keep my place (a page may not scroll you back)",
     "⚙ Settings → Performance  ·  right-click page → 🌐 Exceptions for this site",
     "You open a page, start scrolling, and a second later it drags itself to one "
     "particular spot. The page was not finished: late adverts, fonts and lazy images "
     "keep arriving for seconds and bring scroll calls with them — a saved position "
     "restored, a #fragment applied late, a banner scrolling itself into view. With "
     "Keep my place on, the moment YOU scroll a page it is yours and the page cannot "
     "move you again. Jumps you ask for still happen (a link, a back-to-top button, an "
     "in-page anchor, a new view in a web app), only the main page scroll is guarded "
     "— never an inner panel such as a chat list or a spreadsheet grid — and it "
     "gives up rather than flicker against a site that insists. On by default; per-site "
     "switch under Exceptions for this site.",
     "scroll jump jumps back snaps top page moves me while loading keep my place hold "
     "position anchor fragment lazy images annoying yanked reading"),

    ("Remember scroll position (“go to last position”)",
     "Right-click page → “go to last position” for this site  ·  Settings",
     "Opt-in per site: WhyBrowse remembers where you had scrolled to and returns you there the next time you open that page. Meant for long pages you work down over time rather than read once.",
     "scroll position remember last place resume where i was long page continue reading"),

    ("Recover typed text after a crash",
     "☰ menu → 💾 Recover typed text...  ·  ✉ Recover message drafts...",
     "Everything you type into web pages is auto-saved every few seconds, so a crash or an accidental close doesn't lose it. The previous session's text survives one restart and is then cleaned up about an hour later. Messages you were writing are kept separately under 'Recover message drafts'. Passwords and hidden fields are never saved.",
     "crash recovery recover typed text lost form message draft autosave restore what i wrote"),

    ("What this page sees about me (bot-check report)",
     "Right-click page → 🔧 Troubleshoot → 🕵 What this page sees about me",
     "Shows what the site can actually detect: user agent, client hints, the engine's real version, whether cookies can be set, WebGL and time zone — and names anything that looks inconsistent. Use it when a site rejects you and you need to know WHY rather than guess: a user agent that disagrees with the engine's real feature set is a hard fail for bot checks.",
     "fingerprint bot check what site sees user agent client hints webgl detection blocked rejected why"),

    ("Browser engine version / update it",
     "☰ menu → 🌐 Browser engine version...",
     "Shows the Chromium engine version behind WhyBrowse and offers the pip command to update it — in a selectable field with a Copy button, plus a 'Create updater (.bat)' button that writes a double-clickable Update_engine.bat. The .bat is the route that actually works: Windows will not let pip replace the engine's DLLs while the running program has them open, which is why an in-app update usually failed.",
     "engine version chromium update pip qtwebengine upgrade outdated bat updater"),

    ("Set WhyBrowse as the default browser",
     "Settings → default browser  ·  Windows Settings → Apps → Default apps",
     "Registers WhyBrowse with Windows so links clicked in other programs open here. Windows protects the final choice itself, so the last step is made in Windows Settings → Apps → Default apps. A link from another program opens in the ALREADY-RUNNING WhyBrowse as a new tab rather than starting a second copy.",
     "default browser windows apps register links from other programs mailto open in"),

    ("Custom page size (zoom saved per page or domain)",
     "Right-click page → 🔍 Custom size for this page/domain...",
     "Set a zoom level that is remembered for just this page or for the whole domain, dragging to preview before you save. Separate from the low-vision dial, which is a temporary whole-browser magnifier.",
     "custom size zoom per domain per page remember magnify text bigger smaller"),

    ("Links from other programs open in the running WhyBrowse",
     "automatic (single instance)",
     "Clicking a link in another program hands the address to the WhyBrowse you already have open — it appears as a new tab in profile 1 — instead of launching a second copy with its own separate cookies. If a crash ever leaves the connection stale it is cleared automatically on the next start.",
     "single instance already running second copy link from another app pipe new tab default browser"),

    ("Links from other programs now open INSTANTLY",
     "automatic  ·  Helpfiles/WhyBrowse/ipc.json",
     "The hand-off above used to start a whole second WhyBrowse — loading Qt and Chromium (and, as a one-file .exe, unpacking ~200 MB to a temp folder) purely to pass four words to the window already on screen. That is where the several-second wait came from. The address is now passed over before any of that is loaded, so it costs milliseconds. Other programs can skip the launch entirely: while WhyBrowse runs it writes the name of its local pipe into Helpfiles/WhyBrowse/ipc.json, and anything that writes \"url\" — or \"profile<TAB>url\" — into that pipe gets a new tab at once. F(re)email opens mail links this way. Both programs must run at the same privilege level: a browser started as administrator will not accept a link from a program that was not.",
     "slow link click takes seconds instant fast handoff ipc.json pipe freemail email link opens slowly speed"),

    ("File sets — the same few files for every upload",
     "Toolbar 📎 (between 📝 snippets and CP)",
     "Like saved words, but for files. When you give the same three instruction files to several AI chats you no longer have to switch to the file manager each time: save them once as a set (e.g. 'Instruction - Paperdoll'), then pick the set from the 📎 drop-down. A small always-on-top panel opens with a drag handle: drag all the files (or select some in its list and drag just those) onto the page, which is how you give files to a plain chat box that has no paperclip, like ChatGPT. The panel closes itself once the files are dropped (untick the box in the panel to keep it open for several tabs). For sites that DO have an attach button, the panel's Attach-button mode skips the file dialog instead: the whole set goes in at once (an input that takes only one file at a time gets them one after another, like Bulk upload). That mode stays armed for ANY site until used; a 📤 button shows it and can cancel. The drop-down also copies a set to the clipboard so Ctrl+V pastes the files into a chat box, and 'Manage file sets' adds files, renames, reorders and removes sets. Removing only takes a set off WhyBrowse's list - the files on the disk are never touched. A file that has since been moved or deleted is marked '⚠ missing' and skipped.",
     "file files set sets group collection attach attachment upload instruction paperclip ai chat claude chatgpt gemini same files again filsamling bifoga ladda upp"),

    ("Bulk upload — several pictures on a one-at-a-time site (BGG adverts)",
     "Right-click page → 📤📤 Upload SEVERAL files here…  ·  📤 button in the toolbar",
     "For sites that only accept one image per upload, such as posting adverts on BoardGameGeek. The clicking was never the real cost — the file dialog restarts from scratch every time, so the same folder must be found and the next picture picked out of it, over and over. Pick every picture ONCE and the file dialog never opens again: each time the page asks for a file, the next one in the queue is handed over by the completely normal route, so the site cannot tell the difference. WhyBrowse also presses the site's own 'add image' control between files so a whole batch runs unattended (a scripted click is ignored by browsers for file dialogs, so a real mouse event is posted to the render widget instead — it works with a visible file input, with a hidden input behind a <label>, and with a wrapper button). If no control can be found the queue just waits for your click; you still never see the file dialog. If the input accepts several files at once, the whole queue goes in one step. A 📤 3/8 button shows progress: list what's queued, send the next now, skip one, change the wait between files (raise it if pictures arrive half-uploaded), or stop. The queue is tied to the site it started on and is never saved to disk.",
     "upload uploads bulk multiple many images pictures batch queue one at a time boardgamegeek bgg geekmarket advert annons ladda upp flera bilder kö"),

    ("A page keeps crashing (crash loop breaker)",
     "Automatic  ·  log lines start with \"crash-ladder\" in Helpfiles\\0---Empty\\whybrowse_log.txt",
     "When a page's Chromium process dies, WhyBrowse reloads it once. If it dies again within 30 seconds the page cache is emptied and the page reloaded (a stale or corrupt cache entry was the cause of the 2026-11 boardgamegeek.com crash loop); a third crash retries the site with EVERYTHING WhyBrowse adds to it switched off (injected scripts, post-load JavaScript, header rewriting, scroll memory) - for this run only. After five crashes in a row it stops reloading, shows a plain page with Try again, Clear cache and try again and Try without... links and asks whether to open the site in your system browser. Try without... lists your saved HIDE rules for the site (each one separately, or all) and the features WhyBrowse puts on pages (cosmetic script, pop-up kill rules, animation freezing, scroll guard, browser identity, add-ons, after-load helpers, ad blocker, third-party-cookie blocking, header rewriting); tick one or several, press Try now, and if the page stays up the log and a message name what was off. Nothing is saved - it all comes back when you restart. The log says which case it was: HELD = the page stayed up without WhyBrowse's additions (so something WhyBrowse adds is the cause), STILL CRASHED = the engine or the site itself. If a newer browser engine exists the page says so; update it with Helpfiles\\WhyBrowse\\Update_engine.bat while WhyBrowse is closed. WhyBrowse_Chromium_log.bat starts WhyBrowse with Chromium's own log, which names the file and line of an internal assertion.",
     "crash crashes crashed crashing loop reload flicker boardgamegeek bgg geekmail render process terminated engine update krasch krasar omladdning"),

    ("Kill a pop-up box INSIDE the page (Vinted advert, video box)",
     "Right-click page → 🗯 Kill a pop-up box on this page (click it)…",
     "For the advert box drawn inside the page — the one Vinted throws up after a shipping label, or the video box on a subtitle site. Different from the popup guard, which only stops new TABS: no new-tab rule can touch a box drawn inside the page. Click the offending box and choose: REMOVE IT (never appears again on that site) or CLICK ITS OWN X FOR ME (it still appears for a blink, but its close button is pressed for you — safer, because the page runs its own tidy-up, so anything depending on it closing properly still works). Two things a plain element-hide gets wrong and this handles: an overlay is usually a full-screen backdrop with the box inside it and it locks page scrolling, so hiding just the box leaves a dark sheet over a page you cannot scroll — removing takes the whole overlay and unlocks scrolling; and these boxes appear long after load, on an action, so rules are re-applied continuously instead of once at load. SAFETY: if what you clicked matches more than one thing on the page, removing is refused and only 'click its X' is offered, so a sloppy match cannot take your shipping label's QR code with it. Every rule is listed in the same right-click menu with one-click undo, per rule or for the whole site.",
     "popup box inside page overlay modal advert ad vinted shipping label subdl video box close x auto dismiss banner interstitial reklamruta stäng ruta"),

    ("Click a button for me every time (remember a choice)",
     "Right-click page → 👆 Click a button for me every time (remember a choice)…",
     "For a MANDATORY box that only closes once you choose something — 1177's 'Välj region' being the classic case, where remove breaks the page and clicking its X just makes it blink back. Point at your choice (e.g. Västra Götaland) once; WhyBrowse remembers it per site and presses that same button whenever the box reappears, so it makes its choice and closes itself. Only a target it can pin to exactly one element is accepted, and the same give-up guard stops any endless flashing. Undo it in the 🗯 Pop-up rules here menu (marked 'auto-clicked').",
     "auto click autoclick remember choice region välj region 1177 mandatory required dialog button select preset default blink flashing stäng val kom ihåg västra götaland"),

    ("Junk sites & popup guard (forced advert tabs)",
     "🚫 button in the toolbar  ·  right-click page → 🔧 Troubleshoot → 🚫 Popups & junk sites",
     "Stops sites that force a new tab full of nonsense on you — the classic being a video box that won't close whose 'Close' button opens an advert. Chromium's own popup blocker doesn't stop it, because a popup opened from a CLICK counts as user-requested. Two tools: (1) JUNK SITES — a listed address is refused everywhere and the tab closes itself if it was opened just for that; add one while standing on the junk page and it blocks + closes in one go; subdomains included (togglevpn.org covers ads.togglevpn.org) but lookalikes like nottogglevpn.org are not touched. (2) NO NEW TABS FROM THIS SITE — set on the site you are reading (e.g. subdl.com) so the junk tab is never created whatever address it would use; stronger, since it survives the advertiser changing domain. Blocks are never silent: a 🚫 button appears in the toolbar with a per-tab count, listing WHERE each blocked popup wanted to go, with 'open it anyway', 'junk that address', and 'allow popups on this site' — so a page that genuinely needed the popup can be excepted. The address is learned by asking the blocked page where it was going and refusing in the same breath, so the junk site never gets a request. Can also block popups everywhere by default with per-site exceptions.",
     "popup popups blocker block new tab advert ads junk spam forced redirect close button subdl togglevpn window.open target blank stänga popup skräp reklam"),

    ("Auction clock (Tradera / eBay) — don't lose a late bid",
     "Automatic on auction pages  ·  right-click page → 🔧 Troubleshoot → ⏱ Auction clock",
     "A site's own countdown runs on YOUR computer's clock and can be wrong without showing it — clock drift against the seller's server, a page restored from cache that starts counting from an old 'now', or a tick-based timer that loses time whenever the browser is busy. That is how a bid at '8 seconds left' bounces as 'auction already closed'. WhyBrowse shows its own panel bottom-right: it takes the auction's ABSOLUTE end time from the page's embedded data (tied to the item id in the address, so a related item in the sidebar is never picked by mistake), measures the offset to the auction site's OWN server clock, and shows the real time left plus 'Bid before HH:MM:SS' — the end time minus your safety margin minus the measured round-trip, because the bid has to travel there. It spells out the end time it chose (sites often display 22:10 when the auction really ends 22:10:38) and warns in red how many seconds the page's own countdown is out. Margin is 20 s by default; per-site on/off.",
     "auction clock countdown tradera ebay bid late lost closed ended timer server time drift clock skew sniping last second buda auktion klocka"),

    ("History",
     "☰ menu → History",
     "Browse and search your browsing history (stored per profile).",
     "history visited previous log browse"),

    ("Downloads",
     "☰ menu → Downloads",
     "View and manage downloaded files. Each profile has its own download list and default save folder.",
     "download file save history list"),

    ("Backup & Restore",
     "☰ menu → 💾 Backup & Restore",
     "Export all WhyBrowse data (settings, bookmarks, history, passwords, add-ons) to a zip file, or restore from one.",
     "backup restore export import zip data settings"),

    ("Find on page",
     "Ctrl+F  ·  ☰ menu → Find on page",
     "Search for text on the current page. A bar appears at the top; Esc closes it.",
     "find search text ctrl f on page highlight"),

    ("Full screen",
     "F11  ·  ☰ menu → Toggle full screen",
     "Toggle full-screen mode. Move the mouse to the top to temporarily reveal the toolbar and tab strip.",
     "full screen fullscreen f11 maximize hide toolbar"),

    ("Keyboard shortcuts",
     "☰ menu → ❓ Help → shortcuts table",
     "Ctrl+T new tab · Ctrl+W close tab · Ctrl+L address bar · Ctrl+F find on page · F5 reload · F11 full screen · Alt+← back · Alt+→ forward · Ctrl+Shift+K virtual keyboard · Ctrl+Shift+A tab list · Ctrl+Shift+F feature search.",
     "shortcut keyboard hotkey ctrl alt key f5 f11 list all"),
]


# ============================================================================
#  DEL 14A3 - FEATURE SEARCH DIALOG
# ============================================================================
class FeatureSearchDialog(QDialog):
    """Type a keyword and instantly find which WhyBrowse setting or feature matches."""

    def __init__(self, parent, initial=""):
        super().__init__(parent)
        self.win = parent
        self.setWindowTitle(APP_NAME + "  —  🔍 Find a feature or setting")
        self.setModal(True)
        self.resize(820, 520)
        self.setStyleSheet(dialog_qss())
        apply_window_icon(self)
        QShortcut(QKeySequence("Esc"), self, self.reject)

        outer = QVBoxLayout(self)

        # ── search box ────────────────────────────────────────────────────
        self.ed = QLineEdit()
        self.ed.setPlaceholderText(
            "Type a keyword — e.g.   search   snippet   zoom   cookie   download   translate …")
        self.ed.textChanged.connect(self._refresh)
        self.ed.returnPressed.connect(self._activate)
        outer.addWidget(self.ed)

        hint = QLabel("Double-click or press Enter to open Settings for that item.")
        hint.setStyleSheet("color:%s; font-size:8pt;" % C_STATUS_FG)
        outer.addWidget(hint)

        # ── splitter: list left · description right ───────────────────────
        spl = QSplitter(Qt.Orientation.Horizontal)
        spl.setChildrenCollapsible(False)

        self.listw = QListWidget()
        self.listw.setAlternatingRowColors(True)
        self.listw.setSpacing(2)
        self.listw.currentItemChanged.connect(self._on_sel)
        self.listw.itemDoubleClicked.connect(self._activate)
        spl.addWidget(self.listw)

        right = QWidget()
        rl = QVBoxLayout(right)
        rl.setContentsMargins(12, 6, 4, 4)
        self.lbl_name = QLabel()
        self.lbl_name.setWordWrap(True)
        self.lbl_name.setStyleSheet(
            "font-size:11pt; font-weight:bold; color:%s;" % C_ACCENT)
        self.lbl_where = QLabel()
        self.lbl_where.setWordWrap(True)
        self.lbl_where.setStyleSheet(
            "font-size:9pt; color:%s; margin-bottom:8px;" % C_STATUS_FG)
        self.lbl_desc = QLabel()
        self.lbl_desc.setWordWrap(True)
        self.lbl_desc.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.lbl_desc.setStyleSheet("font-size:9pt; line-height:140%;")
        rl.addWidget(self.lbl_name)
        rl.addWidget(self.lbl_where)
        rl.addWidget(self.lbl_desc, 1)
        spl.addWidget(right)
        spl.setSizes([330, 480])
        outer.addWidget(spl, 1)

        # ── bottom row ────────────────────────────────────────────────────
        row = QHBoxLayout()
        self.btn_settings = QPushButton("⚙  Open Settings")
        self.btn_settings.setEnabled(False)
        self.btn_settings.clicked.connect(self._open_settings)
        row.addWidget(self.btn_settings)
        row.addStretch()
        cb = QPushButton("Close")
        cb.clicked.connect(self.reject)
        row.addWidget(cb)
        outer.addLayout(row)

        if initial:
            self.ed.setText(initial)
        else:
            self._refresh()
        self.ed.setFocus()
        self.ed.selectAll()

    # ── internal ──────────────────────────────────────────────────────────
    def _refresh(self):
        q = self.ed.text().strip().lower()
        self.listw.clear()
        for name, where, desc, keys in FEATURE_INDEX:
            haystack = " ".join((name, where, desc, keys)).lower()
            if not q or q in haystack:
                it = QListWidgetItem("%s\n  %s" % (name, where))
                it.setData(Qt.ItemDataRole.UserRole, (name, where, desc))
                self.listw.addItem(it)
        if self.listw.count():
            self.listw.setCurrentRow(0)
        else:
            self.lbl_name.setText("No results")
            self.lbl_where.setText("")
            self.lbl_desc.setText("Try a different keyword.")
            self.btn_settings.setEnabled(False)

    def _on_sel(self, item):
        if not item:
            return
        name, where, desc = item.data(Qt.ItemDataRole.UserRole)
        self.lbl_name.setText(name)
        self.lbl_where.setText("📍  " + where)
        self.lbl_desc.setText(desc)
        self.btn_settings.setEnabled("⚙ Settings" in where)

    def _activate(self):
        if self.btn_settings.isEnabled():
            self._open_settings()
        else:
            self.reject()

    def _open_settings(self):
        self.accept()
        self.win.open_settings()

    def keyPressEvent(self, e):
        if e.key() == Qt.Key.Key_Down and self.ed.hasFocus():
            self.listw.setFocus()
        else:
            super().keyPressEvent(e)


# ============================================================================
#  DEL 14A4 - ENGINE UPDATE PANEL  (pip command you can copy + .bat updater)
# ============================================================================
#  Replaces two near-identical, both-broken pip runners (one here in Settings,
#  one in the Browser-engine dialog). What was wrong with them:
#
#   1. The worker thread signalled the GUI back with QTimer.singleShot(0, ...).
#      A QTimer started on a plain Python thread has no event loop to run on,
#      so the callback frequently never fired: pip finished, but the label sat
#      on "Running pip install, please wait…" forever. That is the hang.
#   2. No timeout, so a pip that stopped to ask something waited for ever.
#   3. The command was only ever painted onto a button, so it could not be
#      selected or copied.
#   4. The deeper problem: pip cannot replace PyQt6's DLLs WHILE those DLLs are
#      loaded by the running program. On Windows the files are locked, so an
#      in-app upgrade usually fails ("Access is denied") or half-applies. This
#      is why the reliable route is a small .bat you run with WhyBrowse closed.
#
#  So: the command is shown in a selectable field with a Copy button, the
#  primary action writes a double-clickable updater .bat, and the in-app run
#  (kept, but honestly labelled) now reports back over a Qt signal, which is
#  thread-safe and always delivered.

PIP_PACKAGES = ["PyQt6", "PyQt6-WebEngine"]


def pip_command_argv():
    """The engine-update command as an argv list.

    _real_python(), never sys.executable: in a build that is WhyBrowse.exe,
    so the in-app run would start another browser - and the .bat written from
    pip_command_display() would do it again on every double-click.  Raising
    is deliberate; the caller already turns it into "Could not start pip: …".
    """
    py = _real_python()
    if not py:
        raise RuntimeError(
            "no Python installation was found on this machine, so pip cannot "
            "be run - install Python, or update the engine on the machine "
            "where WhyBrowse was built")
    return [py, "-m", "pip", "install", "--upgrade"] + PIP_PACKAGES


def pip_command_display():
    """The same command as one copy-pasteable line (quoted for a shell)."""
    exe = _real_python()
    if not exe:
        return "(no Python installation was found on this machine)"
    if " " in exe:
        exe = '"%s"' % exe
    return "%s -m pip install --upgrade %s" % (exe, " ".join(PIP_PACKAGES))


class PipWorker(QObject):
    """Runs the pip upgrade off the GUI thread and reports back with a SIGNAL.

    Qt delivers a signal emitted on a worker thread to the receiver's own
    thread automatically, so this always arrives - unlike the QTimer that was
    used before."""

    done = pyqtSignal(int, str)          # (exit code, output tail); -1 = failed

    def run(self):
        def worker():
            try:
                proc = subprocess.run(
                    pip_command_argv() + ["--disable-pip-version-check"],
                    capture_output=True, text=True,
                    timeout=900,                   # never hang for ever
                    creationflags=(subprocess.CREATE_NO_WINDOW
                                   if platform.system() == "Windows" else 0))
                out = (proc.stdout + proc.stderr).strip().splitlines()
                self.done.emit(proc.returncode, "\n".join(out[-12:]))
            except subprocess.TimeoutExpired:
                self.done.emit(-1, "pip did not finish within 15 minutes and was "
                                   "stopped. Use the .bat updater instead.")
            except Exception as exc:
                self.done.emit(-1, "Could not start pip: %s" % exc)

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


class EngineUpdatePanel(QWidget):
    """Copyable pip command + .bat updater + (optional) in-app run."""

    def __init__(self, parent=None):
        super().__init__(parent)
        lay = QVBoxLayout(self)
        lay.setContentsMargins(0, 0, 0, 0)

        frozen = bool(getattr(sys, "frozen", False))
        note = QLabel(
            "WhyBrowse renders pages with Chromium, bundled inside the PyQt6-"
            "WebEngine package. Updating that package updates the engine.\n\n"
            + ("This is a compiled .exe, so pip cannot update it — rebuild the "
               ".exe after updating the packages in your Python installation."
               if frozen else
               "Windows locks files that are in use, so pip usually CANNOT "
               "replace the engine while WhyBrowse is running. Use the .bat "
               "below (it waits until you have closed WhyBrowse) — that is the "
               "route that actually works."))
        note.setWordWrap(True)
        lay.addWidget(note)

        lay.addWidget(QLabel("Command (select it, or press Copy):"))
        row_cmd = QHBoxLayout()
        self.ed_cmd = QLineEdit(pip_command_display())
        self.ed_cmd.setReadOnly(True)                 # selectable and copyable
        self.ed_cmd.setCursorPosition(0)
        self.ed_cmd.setStyleSheet("font-family:monospace;")
        row_cmd.addWidget(self.ed_cmd, 1)
        b_copy = QPushButton("⎘  Copy")
        b_copy.clicked.connect(self._copy_cmd)
        row_cmd.addWidget(b_copy)
        lay.addLayout(row_cmd)

        row_btn = QHBoxLayout()
        self.btn_bat = QPushButton("📄  Create updater (.bat) and open the folder")
        self.btn_bat.setStyleSheet(
            "QPushButton{background:%s; color:%s; border:none; padding:6px 14px;"
            " border-radius:6px; font-weight:bold;}QPushButton:hover{background:%s;}"
            % (C_ACCENT, C_ACCENT_FG, C_ACCENT_HOV))
        self.btn_bat.clicked.connect(self._make_bat)
        row_btn.addWidget(self.btn_bat)

        self.btn_pip = QPushButton("⟳  Try updating now (often blocked while running)")
        self.btn_pip.setStyleSheet(
            "QPushButton{background:%s; color:%s; border:none; padding:6px 14px;"
            " border-radius:6px;}QPushButton:hover{background:%s;}"
            % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
        self.btn_pip.setEnabled(not frozen)
        self.btn_pip.clicked.connect(self._run_pip)
        row_btn.addWidget(self.btn_pip)
        row_btn.addStretch(1)
        lay.addLayout(row_btn)

        self.lbl = QLabel("")
        self.lbl.setWordWrap(True)
        self.lbl.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
        self.lbl.setStyleSheet("color:%s; font-size:9pt; font-family:monospace;"
                               % C_STATUS_FG)
        lay.addWidget(self.lbl)

        self._worker = PipWorker(self)
        self._worker.done.connect(self._pip_done)

    # ---- actions ----
    def _copy_cmd(self):
        QApplication.clipboard().setText(self.ed_cmd.text())
        self.lbl.setText("Command copied. Close WhyBrowse, then paste it into "
                         "a Command Prompt or PowerShell window.")

    def _bat_path(self):
        return os.path.join(DATA_DIR, "Update_engine.bat")

    def _make_bat(self):
        """Write a double-clickable updater that runs with WhyBrowse closed."""
        path = self._bat_path()
        try:
            os.makedirs(DATA_DIR, exist_ok=True)
            body = (
                "@echo off\n"
                # UTF-8 codepage: the interpreter path below may contain a, a
                # or o with diacritics, and the default console codepage would
                # mangle it into a "file not found".
                "chcp 65001 >nul\n"
                "title Update the WhyBrowse browser engine\n"
                "echo.\n"
                "echo  Updating: %s\n"
                "echo.\n"
                "echo  IMPORTANT: close WhyBrowse first. Windows will not let\n"
                "echo  pip replace the engine while the program is using it.\n"
                "echo.\n"
                "pause\n"
                "%s\n"
                "echo.\n"
                "if errorlevel 1 (echo  FAILED - see the messages above.)"
                " else (echo  Done. Start WhyBrowse again.)\n"
                "echo.\n"
                "pause\n" % (" ".join(PIP_PACKAGES), pip_command_display()))
            # newline="\r\n" explicitly: writing "\r\n" in the text above would
            # be translated a SECOND time on Windows, giving "\r\r\n".
            with open(path, "w", encoding="utf-8", newline="\r\n") as f:
                f.write(body)
        except Exception as exc:
            self.lbl.setText("Could not write the .bat: %s" % exc)
            return
        self.lbl.setText("Created:  %s\nClose WhyBrowse, then double-click it."
                         % path)
        try:
            open_path(DATA_DIR)                  # Windows file explorer
        except Exception:
            pass

    def _run_pip(self):
        self.btn_pip.setEnabled(False)
        self.lbl.setText("Running pip… (this can take a few minutes)")
        self._worker.run()

    def _pip_done(self, code, tail):
        if code == 0:
            self.lbl.setText("Done ✓  Restart WhyBrowse to use the new engine.\n"
                             + tail)
        else:
            hint = ""
            low = (tail or "").lower()
            if "access is denied" in low or "winerror 5" in low or "in use" in low:
                hint = ("\n\nThat is the file lock described above — the engine "
                        "is in use by this running program. Use the .bat "
                        "updater with WhyBrowse closed.")
            self.lbl.setText("pip exited with code %s\n%s%s" % (code, tail, hint))
        self.btn_pip.setEnabled(True)


# ============================================================================
#  DEL 14B - SETTINGS DIALOG  (all toggles and lists; ESC closes)
# ============================================================================
class SettingsDialog(QDialog):
    def __init__(self, parent):
        super().__init__(parent)
        self.win = parent
        self._s = dict(parent.settings)            # work on a copy
        self.setWindowTitle(APP_NAME + " - Settings")
        self.setModal(True)
        # 700 is chosen, not guessed: after wrap_wide_controls() the widest row
        # left in this page measures 638 px, so at 700 nothing needs sideways
        # scrolling and the horizontal bar stays away.
        self.resize(700, 760)
        self.setStyleSheet(dialog_qss())
        apply_window_icon(self)

        outer = QVBoxLayout(self)
        scroll = QScrollArea()
        self._scroll = scroll
        scroll.setWidgetResizable(True)
        # ---- A scrollbar you cannot miss ----------------------------------
        # Reported: "I still change settings by accident when I scroll with the
        # mouse — I can't see a scrollbar." Two separate faults, both fixed.
        # This is the first one: the shared scrollbar style draws a dark handle
        # on a transparent groove, which on this crowded page is genuinely hard
        # to spot, and it was only there WHILE scrolling. Here it is always
        # visible, wider, sitting in a groove you can see, with the accent
        # colour on the handle - so the page announces that it scrolls.
        # (The second fault - the wheel changing whatever control it passes
        # over - is handled by WheelGuard, installed at the end of __init__.)
        scroll.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOn)
        scroll.setStyleSheet(
            "QScrollArea{border:none;}"
            "QScrollBar:vertical{background:%s;width:18px;margin:0;"
            "border-radius:9px;}"
            "QScrollBar::handle:vertical{background:%s;min-height:44px;"
            "border-radius:7px;border:2px solid transparent;"
            "background-clip:padding;}"
            "QScrollBar::handle:vertical:hover{background:%s;}"
            "QScrollBar::add-line:vertical,QScrollBar::sub-line:vertical{height:0;}"
            "QScrollBar::add-page:vertical,QScrollBar::sub-page:vertical"
            "{background:transparent;}"
            % (shade(C_ADDR_BG, 22), C_ACCENT, C_ACCENT_HOV))
        # Scrollbar on the LEFT. A right-to-left scroll area puts its
        # vertical bar on the left edge; the body is forced back to
        # left-to-right so nothing inside it is mirrored.
        scroll.setLayoutDirection(Qt.LayoutDirection.RightToLeft)
        host = QWidget()
        host.setLayoutDirection(Qt.LayoutDirection.LeftToRight)
        scroll.setWidget(host)
        outer.addWidget(scroll, 1)
        lay = QVBoxLayout(host)
        lay.setSpacing(8)

        def header(text):
            l = QLabel(text)
            l.setStyleSheet("color:%s; font-size:12pt; font-weight:bold; "
                            "margin-top:8px;" % C_ACCENT)
            lay.addWidget(l)

        # ---- Startup ----
        header("Startup & tabs")
        self.cmb_startup = QComboBox()
        self.cmb_startup.addItems(["restore", "home", "blank"])
        self.cmb_startup.setCurrentText(self._s.get("startup_mode", "restore"))
        lay.addWidget(QLabel("On launch:"))
        lay.addWidget(self.cmb_startup)

        self.cmb_newtab = QComboBox()
        self.cmb_newtab.addItems(["blank", "home"])
        self.cmb_newtab.setCurrentText(self._s.get("new_tab_mode", "blank"))
        lay.addWidget(QLabel("New tab opens:"))
        lay.addWidget(self.cmb_newtab)

        lay.addWidget(QLabel(
            "Default \"Open link\" action  (shown in the middle and bottom of the right-click menu):"))
        self.cmb_open_link = QComboBox()
        self.cmb_open_link.addItem("↗  Open in new tab — stay here", "new_tab_stay")
        self.cmb_open_link.addItem("➡  Open in new tab — go there",  "new_tab_go")
        saved_ol = self._s.get("open_link_default", "new_tab_stay")
        idx_ol = self.cmb_open_link.findData(saved_ol)
        if idx_ol >= 0:
            self.cmb_open_link.setCurrentIndex(idx_ol)
        lay.addWidget(self.cmb_open_link)
        ol_hint = QLabel(
            "Both alternatives are always available at the top of the menu when "
            "you right-click a link. Your favourite is repeated in the middle and "
            "at the bottom so you never have to scroll."
        )
        ol_hint.setWordWrap(True)
        ol_hint.setStyleSheet("color:%s; font-size:8pt;" % C_STATUS_FG)
        lay.addWidget(ol_hint)

        # ---- Links open in a NEW tab by default (DEL 42, rev91) ----
        self.chk_links_new = QCheckBox(
            "Left-clicking an ordinary link opens a NEW tab")
        self.chk_links_new.setChecked(
            bool(self._s.get("links_open_new_tab", False)))
        lay.addWidget(self.chk_links_new)
        ln_hint = QLabel(
            "OFF (normal browser behaviour, and the default): a link you "
            "click loads in the tab you are already in. Turn it ON only if "
            "you want EVERY link to spawn a tab - on a site you click your "
            "way through (Vinted, Tradera, an inbox) that is half a dozen "
            "tabs before you reach the page you were after.\n\n"
            "This is about a plain left-click only. \"Open in new tab\" from "
            "the right-click menu, middle-click, a bookmark set to open in a "
            "new tab and a LOCKED or pinned tab all keep making new tabs "
            "whatever this says - that is the whole point of them.")
        ln_hint.setWordWrap(True)
        ln_hint.setStyleSheet("color:%s; font-size:8pt;" % C_STATUS_FG)
        lay.addWidget(ln_hint)

        # ---- The temp tab (DEL 44) ----
        header("The temp tab  🕒")
        tt_hint = QLabel(
            "One tab set aside for pages you only want to LOOK at: opening "
            "something \"in temp\" reuses that tab instead of making a new one, "
            "so you don't end up with twenty tabs.\n\n"
            "Nothing lands there by itself. Only a bookmark you set to Temp, the "
            "page menu's \"🕒 Open link in the temp tab\", the address bar's "
            "right-click, or a \"same tab\" open that a locked/pinned tab would "
            "otherwise have turned into yet another tab. Clicking your way "
            "through items on Tradera or Vinted follows the normal rules, so "
            "those can never queue up in the temp tab and overwrite each other.\n\n"
            "A temp tab you PIN or LOCK is never reused — that is how you keep "
            "one you decided you want (or un-tick \"Temp tab\" in its right-click "
            "menu).")
        tt_hint.setWordWrap(True)
        tt_hint.setStyleSheet("color:%s; font-size:8pt;" % C_STATUS_FG)
        lay.addWidget(tt_hint)

        self.chk_temp = QCheckBox("Use a temp tab")
        self.chk_temp.setChecked(bool(self._s.get("temp_tab_enabled", True)))
        lay.addWidget(self.chk_temp)

        row_tt = QHBoxLayout()
        row_tt.addWidget(QLabel("How many temp tabs before the oldest is reused:"))
        self.spin_temp = QSpinBox()
        self.spin_temp.setRange(1, 9)
        self.spin_temp.setValue(int(self._s.get("temp_tab_slots", 1) or 1))
        self.spin_temp.setToolTip("1 = one single temp tab, always reused. "
                                  "3 = three take turns, so the last three are "
                                  "still there.")
        row_tt.addWidget(self.spin_temp)
        row_tt.addStretch(1)
        lay.addLayout(row_tt)

        self.chk_temp_restore = QCheckBox(
            "Keep temp tabs when WhyBrowse restarts (off = they are dropped, "
            "which is what \"temporary\" normally means)")
        self.chk_temp_restore.setChecked(bool(self._s.get("temp_tab_restore", True)))
        lay.addWidget(self.chk_temp_restore)

        self.chk_temp_locked = QCheckBox(
            "On a LOCKED or pinned tab, an \"open in the same tab\" goes to the "
            "temp tab (instead of opening yet another tab)")
        self.chk_temp_locked.setChecked(bool(self._s.get("temp_locked_override", True)))
        lay.addWidget(self.chk_temp_locked)

        lay.addWidget(QLabel("When I open a bookmark, use by default:"))
        self.cmb_bm_open = QComboBox()
        self.cmb_bm_open.addItem("🆕  A new tab",       "new")
        self.cmb_bm_open.addItem("↩  The same tab",     "same")
        self.cmb_bm_open.addItem("🕒  The temp tab",    "temp")
        _bm_cur = (self._s.get("open_bookmark_default") or "").strip().lower()
        if _bm_cur not in ("new", "same", "temp"):
            _bm_cur = "new" if self._s.get("bar_open_new_tab", True) else "same"
        _bm_idx = self.cmb_bm_open.findData(_bm_cur)
        if _bm_idx >= 0:
            self.cmb_bm_open.setCurrentIndex(_bm_idx)
        lay.addWidget(self.cmb_bm_open)
        bm_hint = QLabel(
            "Any single bookmark can override this — right-click it on the bar → "
            "\"⚙ A plain click on this one opens…\". The same choice sits on the "
            "address bar's right-click menu.")
        bm_hint.setWordWrap(True)
        bm_hint.setStyleSheet("color:%s; font-size:8pt;" % C_STATUS_FG)
        lay.addWidget(bm_hint)

        lay.addWidget(QLabel("Home page URL:"))
        self.ed_home = QLineEdit(self._s.get("home_url", DEFAULT_HOME))
        lay.addWidget(self.ed_home)

        lay.addWidget(QLabel("Search engine:"))
        self.cmb_search = QComboBox()
        current_se = self._s.get("search_engine", SEARCH_URL)
        _se_urls = [url for _, url in SEARCH_ENGINES]
        for name, url in SEARCH_ENGINES:
            self.cmb_search.addItem(name, url)
        self.cmb_search.addItem("(Custom URL…)", "__custom__")
        # pre-select the saved engine, or fall back to Custom
        _se_idx = next((i for i, (_, u) in enumerate(SEARCH_ENGINES)
                        if u == current_se), -1)
        if _se_idx >= 0:
            self.cmb_search.setCurrentIndex(_se_idx)
        else:
            self.cmb_search.setCurrentIndex(self.cmb_search.count() - 1)
        lay.addWidget(self.cmb_search)
        # custom URL field — shown only when "(Custom URL…)" is selected
        self.ed_search = QLineEdit(current_se)
        self.ed_search.setPlaceholderText("Custom URL — use {} where the query goes")
        _is_custom = current_se not in _se_urls
        self.ed_search.setVisible(_is_custom)
        lay.addWidget(self.ed_search)
        def _on_search_engine_changed(idx):
            is_custom = self.cmb_search.itemData(idx) == "__custom__"
            self.ed_search.setVisible(is_custom)
            if not is_custom:
                self.ed_search.setText(self.cmb_search.itemData(idx))
        self.cmb_search.currentIndexChanged.connect(_on_search_engine_changed)

        # ---- Privacy ----
        header("Privacy & blocking")
        self.chk_adblock = QCheckBox("Enable ad / tracker blocker")
        self.chk_adblock.setChecked(bool(self._s.get("adblock_enabled", True)))
        lay.addWidget(self.chk_adblock)

        self.chk_cookies = QCheckBox("Block third-party cookies (reduces cross-site tracking)")
        self.chk_cookies.setChecked(bool(self._s.get("block_third_party_cookies", True)))
        lay.addWidget(self.chk_cookies)

        self.chk_signedin = QCheckBox(
            "Stay signed in to Google / Microsoft (don't block 3rd-party cookies "
            "while one of their tabs is open — fixes blank Google Sheets / re-login)")
        self.chk_signedin.setChecked(bool(self._s.get("stay_signed_in", True)))
        lay.addWidget(self.chk_signedin)

        self.chk_challenge = QCheckBox(
            "Let \"Verify you are human\" checks through (when a site shows a "
            "Cloudflare / hCaptcha wall, turn the blocking features off for THAT "
            "site once and reload — otherwise the check can loop forever)")
        self.chk_challenge.setChecked(bool(self._s.get("challenge_auto_relax", True)))
        lay.addWidget(self.chk_challenge)

        self.chk_chrome_id = QCheckBox(
            "Present a complete Chrome identity (fixes Google sign-in's \"this "
            "browser or app may not be secure\"). The engine sent \"Chromium\" in "
            "its Sec-CH-UA header while its user-agent said \"Chrome\", had an "
            "empty window.chrome and no Accept-Language header at all — this "
            "makes all three agree. Ignored if you set a custom user agent below.")
        self.chk_chrome_id.setChecked(bool(self._s.get("chrome_identity", True)))
        lay.addWidget(self.chk_chrome_id)

        # ---- User agent -----------------------------------------------------
        # Worth exposing: the UA is the single value most likely to be behind a
        # site rejecting this browser, and trying another one is a 5-second test
        # that beats a round of guesswork. Empty = automatic.
        lay.addWidget(QLabel(
            "User agent (what this browser reports itself as). Leave EMPTY for "
            "automatic — that reports this engine's real Chrome version, which "
            "is what human-verification checks expect:"))
        self.ed_ua = QLineEdit(self._s.get("user_agent", "") or "")
        self.ed_ua.setPlaceholderText("empty = automatic (recommended)")
        lay.addWidget(self.ed_ua)
        ua_row = QHBoxLayout()
        b_ua_auto = QPushButton("Use automatic")
        b_ua_auto.clicked.connect(lambda: self.ed_ua.setText(""))
        ua_row.addWidget(b_ua_auto)
        if self.win is not None:
            b_ua_now = QPushButton("Show what is sent now")
            b_ua_now.clicked.connect(
                lambda: self.ed_ua.setPlaceholderText(
                    self.win._effective_user_agent(
                        self.win._get_engine(self.win._valid_active_id()))))
            ua_row.addWidget(b_ua_now)
        ua_row.addStretch(1)
        lay.addLayout(ua_row)

        lay.addWidget(QLabel("Extra domains to block (one per line):"))
        self.txt_adblock = QPlainTextEdit("\n".join(self._s.get("adblock_extra", [])))
        self.txt_adblock.setFixedHeight(70)
        lay.addWidget(self.txt_adblock)

        # ---- Anti-annoyance ----
        header("Anti-annoyance")
        self.chk_freeze = QCheckBox("Freeze blinking carets, animations and GIFs/video")
        self.chk_freeze.setChecked(bool(self._s.get("freeze_animations", False)))
        lay.addWidget(self.chk_freeze)

        self.chk_nags = QCheckBox("Hide cookie banners & donation / nag bars")
        self.chk_nags.setChecked(bool(self._s.get("hide_nag_banners", True)))
        lay.addWidget(self.chk_nags)

        self.chk_ytads = QCheckBox("Block YouTube ads (skip & hide ads on youtube.com)")
        self.chk_ytads.setChecked(bool(self._s.get("youtube_adblock", True)))
        lay.addWidget(self.chk_ytads)

        self.chk_imdb = QCheckBox("IMDb: always open the cleaner 'reference' layout")
        self.chk_imdb.setChecked(bool(self._s.get("imdb_reference", True)))
        lay.addWidget(self.chk_imdb)

        lay.addWidget(QLabel("Hide these domains from search results (one per line):"))
        self.txt_searchblock = QPlainTextEdit("\n".join(self._s.get("search_block_domains", [])))
        self.txt_searchblock.setFixedHeight(70)
        lay.addWidget(self.txt_searchblock)

        lay.addWidget(QLabel(
            "Sites where Ctrl+F opens the page's OWN search (one domain per line)\n"
            "e.g. docs.google.com  — the browser find-bar is skipped on these:"))
        self.txt_native_find = QPlainTextEdit(
            "\n".join(self._s.get("native_find_domains", [])))
        self.txt_native_find.setFixedHeight(80)
        lay.addWidget(self.txt_native_find)

        lay.addWidget(QLabel("Element-hide rules  (format:  domain##css-selector ):"))
        rules = self._s.get("element_hide_rules", [])
        rule_lines = "\n".join("{}##{}".format(r.get("domain", ""), r.get("selector", ""))
                               for r in rules)
        self.txt_elemhide = QPlainTextEdit(rule_lines)
        self.txt_elemhide.setFixedHeight(80)
        lay.addWidget(self.txt_elemhide)

        # ---- Location spoof (keeps your 10 most recent places; uses the latest) ----
        header("Pretend to be in another city")
        sp = self._s.get("spoof_location", {}) or {}
        self.chk_spoof = QCheckBox("Spoof my location (websites/stores see the chosen city)")
        self.chk_spoof.setChecked(bool(sp.get("enabled", False)))
        lay.addWidget(self.chk_spoof)

        # Recents (most recent first) + built-in presets in the dropdown
        self._recents = list(self._s.get("location_recents", []))
        self._recent_map = {r.get("name"): (r.get("lat"), r.get("lon")) for r in self._recents}

        row = QHBoxLayout()
        row.addWidget(QLabel("Place:"))
        self.cmb_city = QComboBox()
        # Default to the most-recently used place (recents[0]); fall back to the
        # saved city only if it is actually one of the recents.
        saved_city = sp.get("city")
        self._refill_city_combo(select=saved_city if saved_city in self._recent_map else None)
        self.cmb_city.currentTextChanged.connect(self._city_changed)
        row.addWidget(self.cmb_city, 1)
        lay.addLayout(row)

        # Type any city/address and look it up (fills lat/lon automatically)
        rowL = QHBoxLayout()
        self.ed_lookup = QLineEdit()
        self.ed_lookup.setPlaceholderText("Type a city or address, e.g. Götene")
        self.ed_lookup.returnPressed.connect(self._do_lookup)
        rowL.addWidget(self.ed_lookup, 1)
        self.btn_lookup = QPushButton("Look up")
        self.btn_lookup.setStyleSheet(
            "QPushButton{background:%s; color:%s; border:none; padding:6px 14px; "
            "border-radius:6px; font-weight:bold;}QPushButton:hover{background:%s;}"
            % (C_ACCENT, C_ACCENT_FG, C_ACCENT_HOV))
        self.btn_lookup.clicked.connect(self._do_lookup)
        rowL.addWidget(self.btn_lookup)
        lay.addLayout(rowL)

        self.lbl_lookup = QLabel("")
        self.lbl_lookup.setStyleSheet("color:%s; font-size:9pt;" % C_STATUS_FG)
        lay.addWidget(self.lbl_lookup)

        row2 = QHBoxLayout()
        row2.addWidget(QLabel("Lat:"))
        self.ed_lat = QLineEdit(str(sp.get("lat", 58.5256)))
        row2.addWidget(self.ed_lat)
        row2.addWidget(QLabel("Lon:"))
        self.ed_lon = QLineEdit(str(sp.get("lon", 13.4926)))
        row2.addWidget(self.ed_lon)
        lay.addLayout(row2)
        # Sync lat/lon to whatever place the dropdown defaulted to
        self._city_changed(self.cmb_city.currentText())

        # ---- Bookmarks ----
        # ---- Right-click menu arrangement (DEL 43) ----
        header("The page right-click menu")
        pm_hint = QLabel(
            "The menu you get when you right-click a web page has grown long. "
            "Arrange it the way you want: drag entries into a new order, make "
            "your own sub-menus and drop entries into them, and park the ones "
            "you never use in the Hidden bin. The same button sits at the "
            "bottom of that menu itself.")
        pm_hint.setWordWrap(True)
        pm_hint.setStyleSheet("color:%s; font-size:9pt;" % C_STATUS_FG)
        lay.addWidget(pm_hint)
        self.btn_page_menu = QPushButton("🖱  Arrange the page right-click menu…")
        self.btn_page_menu.setStyleSheet(
            "QPushButton{background:%s; color:%s; border:none; padding:6px 14px; "
            "border-radius:6px;}QPushButton:hover{background:%s;}"
            % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
        self.btn_page_menu.clicked.connect(
            lambda: PageMenuLayoutDialog(self.win).exec())
        lay.addWidget(self.btn_page_menu)

        header("Bookmarks")
        lay.addWidget(QLabel("When bookmarking a page that is already saved:"))
        self.cmb_dup_mode = QComboBox()
        self.cmb_dup_mode.addItem("Ask — show a popup with options",          "ask")
        self.cmb_dup_mode.addItem("Allow — silently add a duplicate to bar",  "allow")
        self.cmb_dup_mode.addItem("Deny — silently do nothing",               "deny")
        saved_dup = self._s.get("bookmark_duplicate_mode", "ask")
        idx = self.cmb_dup_mode.findData(saved_dup)
        if idx >= 0:
            self.cmb_dup_mode.setCurrentIndex(idx)
        lay.addWidget(self.cmb_dup_mode)
        dup_hint = QLabel(
            "\"Ask\" opens a small dialog that tells you where the bookmark already is "
            "and lets you add a duplicate, move it to the bar root, or cancel."
        )
        dup_hint.setWordWrap(True)
        dup_hint.setStyleSheet("color:%s; font-size:8pt;" % C_STATUS_FG)
        lay.addWidget(dup_hint)

        # ---- Bookmarks from other profiles: Tookmarks (live) / Copymarks (copy) ----
        header("Bookmarks from other profiles")
        self.chk_tookmarks = QCheckBox(
            "Tookmarks — show another profile's bookmarks as a live folder "
            "(\"Tookmarks\") in the bookmarks bar  (this profile only)")
        self.chk_tookmarks.setChecked(bool(self.win._active_profile().get("tookmarks_enabled")))
        # Per-profile + applied live (like Copymarks), so it is NOT in result_settings.
        self.chk_tookmarks.toggled.connect(self.win._toggle_tookmarks)
        lay.addWidget(self.chk_tookmarks)
        t_hint = QLabel("Per profile — each profile chooses its own (or none); turning it on "
                        "here affects only the ACTIVE profile. Live view of ONE other profile "
                        "(nothing is copied), shown next to your 📚 Bookmarks folder. Choose / "
                        "change which profile it mirrors in Menu → 👻 Tookmarks.")
        t_hint.setWordWrap(True)
        t_hint.setStyleSheet("color:%s; font-size:8pt;" % C_STATUS_FG)
        lay.addWidget(t_hint)

        self.chk_copymarks = QCheckBox(
            "Copymarks — physically COPY all other profiles' bookmarks into this "
            "profile (asks first)")
        self.chk_copymarks.setChecked(False)
        self.chk_copymarks.toggled.connect(self._copymarks_toggled)
        lay.addWidget(self.chk_copymarks)
        c_hint = QLabel("Usually unnecessary — Tookmarks already shows them live. Use this only "
                        "to keep a real copy here, e.g. as a backup before you delete the "
                        "originals in another profile.")
        c_hint.setWordWrap(True)
        c_hint.setStyleSheet("color:%s; font-size:8pt;" % C_STATUS_FG)
        lay.addWidget(c_hint)

        # ---- Appearance ----
        header("Appearance (colors)")
        self._theme = dict(current_theme())
        saved_theme = self._s.get("theme") or {}
        if isinstance(saved_theme, dict):
            self._theme.update({k: v for k, v in saved_theme.items() if k in THEME_KEYS})

        rowT = QHBoxLayout()
        rowT.addWidget(QLabel("Preset:"))
        self.cmb_theme = QComboBox()
        self.cmb_theme.addItems(list(THEME_PRESETS.keys()) + ["(custom)"])
        # Show the theme that is ACTUALLY active (was always "(custom)" before,
        # so picking a preset looked like it never stuck).
        self.cmb_theme.setCurrentText(self._preset_name(self._theme))
        self.cmb_theme.currentTextChanged.connect(self._theme_preset_changed)
        rowT.addWidget(self.cmb_theme, 1)
        lay.addLayout(rowT)

        rowC = QHBoxLayout()
        self.btn_bgcolor = QPushButton("Background color...")
        self.btn_bgcolor.clicked.connect(self._pick_bg_color)
        self.btn_accentcolor = QPushButton("Accent color...")
        self.btn_accentcolor.clicked.connect(self._pick_accent_color)
        for b in (self.btn_bgcolor, self.btn_accentcolor):
            b.setStyleSheet(
                "QPushButton{background:%s; color:%s; border:none; padding:6px 14px; "
                "border-radius:6px;}QPushButton:hover{background:%s;}"
                % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
            rowC.addWidget(b)
        lay.addLayout(rowC)

        self.lbl_theme = QLabel("Tip: 'White' preset gives a white background.")
        self.lbl_theme.setStyleSheet("color:%s; font-size:9pt;" % C_STATUS_FG)
        lay.addWidget(self.lbl_theme)

        # ---- Performance / profiles ----
        header("Performance")
        self.chk_keepalive = QCheckBox(
            "Keep other profiles' tabs loaded (no reload + keeps scroll position "
            "when you switch profiles; uses more memory — since rev87 those tabs "
            "auto-sleep on the same idle clock as the ones you can see)")
        self.chk_keepalive.setChecked(bool(self._s.get("keep_profile_tabs_alive", True)))
        lay.addWidget(self.chk_keepalive)

        self.chk_engine_update = QCheckBox(
            "At startup, check online for a newer browser engine (PyQt6-WebEngine) "
            "and notify me if one is available")
        self.chk_engine_update.setChecked(bool(self._s.get("check_engine_updates", True)))
        lay.addWidget(self.chk_engine_update)

        self.chk_sleepall = QCheckBox(
            "Auto-sleep idle background tabs to save memory — ON for EVERY tab, "
            "including other profiles' tabs kept loaded above. Exempt one with "
            "right-click a tab → Not auto-sleep. (Still skipped on their own: a "
            "tab making sound, chat/mail and video sites.)")
        self.chk_sleepall.setChecked(bool(self._s.get("auto_sleep_all", True)))
        lay.addWidget(self.chk_sleepall)

        self.chk_sleeppinned = QCheckBox(
            "…including pinned tabs (a slept pinned tab reloads to the page you "
            "pinned when you come back)")
        self.chk_sleeppinned.setChecked(bool(self._s.get("sleep_pinned_too", True)))
        lay.addWidget(self.chk_sleeppinned)

        row_sl = QHBoxLayout()
        row_sl.addWidget(QLabel("Auto-sleep after this many idle minutes:"))
        self.spin_sleep = QSpinBox()
        self.spin_sleep.setRange(1, 240)
        self.spin_sleep.setValue(int(self._s.get("tab_autosleep_min", 5) or 5))
        self.spin_sleep.setSuffix(" min")
        self.spin_sleep.setFixedWidth(90)
        row_sl.addWidget(self.spin_sleep)
        row_sl.addStretch(1)
        lay.addLayout(row_sl)

        row_ar = QHBoxLayout()
        row_ar.addWidget(QLabel(
            "Auto-refresh tabs: don't reload again until at least this many "
            "minutes have passed:"))
        self.spin_autorefresh = QSpinBox()
        self.spin_autorefresh.setRange(1, 240)
        self.spin_autorefresh.setValue(int(self._s.get("tab_autorefresh_min", 5) or 5))
        self.spin_autorefresh.setSuffix(" min")
        self.spin_autorefresh.setFixedWidth(90)
        row_ar.addWidget(self.spin_autorefresh)
        row_ar.addStretch(1)
        lay.addLayout(row_ar)

        self.chk_keepbg = QCheckBox(
            "Keep background tabs fully active — switches OFF Chromium's own memory "
            "and timer throttling for every hidden tab. Heavy Sheets stay instant, "
            "but this is the single biggest reason a long session climbs into "
            "gigabytes. OFF is recommended now that auto-sleep is on by default "
            "(needs a restart)")
        self.chk_keepbg.setChecked(bool(self._s.get("keep_bg_active", False)))
        lay.addWidget(self.chk_keepbg)

        self.chk_sheetcell = QCheckBox(
            "Google Sheets: return to my last cell on reload/auto-refresh (unless I "
            "set an auto-go for that tab)")
        self.chk_sheetcell.setChecked(bool(self._s.get("sheet_remember_cell", True)))
        lay.addWidget(self.chk_sheetcell)

        row_fm = QHBoxLayout()
        self.chk_formmem = QCheckBox(
            "AUTO-remember form fields (off = only fields you save by hand via "
            "right-click → 'Remember this field'; never passwords/search/messages)")
        self.chk_formmem.setChecked(bool(self._s.get("form_memory", False)))
        row_fm.addWidget(self.chk_formmem, 1)
        btn_fmclear = QPushButton("Clear saved form data")
        btn_fmclear.setStyleSheet(
            "QPushButton{background:%s; color:%s; border:none; padding:5px 12px;"
            " border-radius:6px;}QPushButton:hover{background:%s;}"
            % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
        btn_fmclear.clicked.connect(lambda: self.win._clear_form_memory())
        row_fm.addWidget(btn_fmclear)
        lay.addLayout(row_fm)

        # Mouse-wheel scroll speed (how far each notch scrolls). 100% = native.
        row_ss = QHBoxLayout()
        row_ss.addWidget(QLabel("Mouse-wheel scroll speed:"))
        self.sld_scroll = QSlider(Qt.Orientation.Horizontal)
        self.sld_scroll.setRange(30, 400)              # 30% .. 400%
        self.sld_scroll.setValue(int(round(float(self._s.get("scroll_speed", 1.0)) * 100)))
        self.sld_scroll.setFixedWidth(200)
        self.lbl_scroll = QLabel("%d%%" % self.sld_scroll.value())
        self.sld_scroll.valueChanged.connect(
            lambda val: self.lbl_scroll.setText("%d%%" % val))
        row_ss.addWidget(self.sld_scroll)
        row_ss.addWidget(self.lbl_scroll)
        row_ss.addStretch(1)
        lay.addLayout(row_ss)
        ss_hint = QLabel("100% = normal. Higher = each wheel notch scrolls further. "
                         "(Applies to normal page scrolling; spreadsheet grids keep "
                         "their own scrolling.)")
        ss_hint.setWordWrap(True)
        ss_hint.setStyleSheet("color:%s; font-size:8pt;" % C_STATUS_FG)
        lay.addWidget(ss_hint)

        # ---- DEL 48: release a page left with no scrollbar / a dead wheel ----
        self.chk_scroll_guard = QCheckBox(
            "\U0001f513  Release a page that gets stuck with no scrollbar")
        self.chk_scroll_guard.setChecked(bool(self._s.get("scroll_guard", True)))
        lay.addWidget(self.chk_scroll_guard)
        sg_hint = QLabel(
            "Sites stop the page behind a pop-up from scrolling and lift that "
            "again when you close it. If the pop-up is hidden or removed by "
            "something else \u2014 the cookie/nag hider, the pop-up killer, an "
            "element you zapped \u2014 nobody lifts the lock, and the page stays "
            "frozen until you reload. This notices and releases it, but only when "
            "the page really is longer than the window AND nothing visible is "
            "covering it (a real dialog is supposed to stop the page behind it). "
            "If one still sticks, right-click the page \u2192 \U0001f513 Get "
            "scrolling back releases it at once. Per-site switch: \U0001f310 "
            "Exceptions for this site."
        )
        sg_hint.setWordWrap(True)
        sg_hint.setStyleSheet("color:%s; font-size:8pt;" % C_STATUS_FG)
        lay.addWidget(sg_hint)

        # ---- DEL 51: a page may not scroll you back once YOU have scrolled ----
        self.chk_keep_scroll = QCheckBox(
            "🔒  Keep my place - a page may not scroll me back while it loads")
        self.chk_keep_scroll.setChecked(bool(self._s.get("keep_scroll", True)))
        lay.addWidget(self.chk_keep_scroll)
        ks_hint = QLabel(
            "A page is not finished when it first appears: late adverts, fonts "
            "and lazy images keep arriving for several seconds, and with them "
            "come scroll calls — a saved position being restored, a "
            "#fragment applied late, a banner scrolling itself into view. They "
            "land AFTER you started reading, which is why a page you are "
            "already scrolling suddenly snaps to one particular spot. With this "
            "on, the moment YOU scroll a page it is yours: the page cannot move "
            "you again. Anything you ask for still works — a link, a "
            "“back to top” button, an in-page anchor, a new view in a "
            "web app — and only the main page scroll is guarded, never an "
            "inner panel like a chat list or a spreadsheet grid. Per-site "
            "switch: 🌐 Exceptions for this site."
        )
        ks_hint.setWordWrap(True)
        ks_hint.setStyleSheet("color:%s; font-size:8pt;" % C_STATUS_FG)
        lay.addWidget(ks_hint)

        # ---- Downloads ----
        header("Downloads")
        dl_hint = QLabel(
            "Default folder for downloaded files (used as the starting folder in "
            "the Save dialog). This is saved for the ACTIVE profile and remembered "
            "between sessions. Leave empty to use your system Downloads folder."
        )
        dl_hint.setWordWrap(True)
        dl_hint.setStyleSheet("color:%s; font-size:9pt;" % C_STATUS_FG)
        lay.addWidget(dl_hint)

        _prof_dl = self.win._active_profile().get("save_dir", "")
        row_dl = QHBoxLayout()
        self.ed_download = QLineEdit(_prof_dl)
        self.ed_download.setPlaceholderText("e.g. C:\\0---Temp   (empty = ~/Downloads)")
        row_dl.addWidget(self.ed_download, 1)
        btn_dlbrowse = QPushButton("Browse…")
        btn_dlbrowse.setStyleSheet(
            "QPushButton{background:%s; color:%s; border:none; padding:5px 12px;"
            " border-radius:6px;}QPushButton:hover{background:%s;}"
            % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
        btn_dlbrowse.clicked.connect(self._browse_download_dir)
        row_dl.addWidget(btn_dlbrowse)
        btn_dlopen = QPushButton("📂 Open folder")
        btn_dlopen.setStyleSheet(
            "QPushButton{background:%s; color:%s; border:none; padding:5px 12px;"
            " border-radius:6px;}QPushButton:hover{background:%s;}"
            % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
        btn_dlopen.clicked.connect(self._open_download_dir)
        row_dl.addWidget(btn_dlopen)
        lay.addLayout(row_dl)

        self.chk_quick_download = QCheckBox(
            "⚡  Quick-download (save straight to the folder above, no pop-up)")
        self.chk_quick_download.setChecked(
            bool(self.win._active_profile().get("quick_download", False)))
        lay.addWidget(self.chk_quick_download)
        qd_hint = QLabel(
            "When ON, every download is saved automatically — no pop-up. You can "
            "also turn this on directly from the Save pop-up itself, via its "
            "\"⚡ Always download to this directory\" option — this is the fastest "
            "way to stop the pop-up for good. For a one-off exception afterwards, "
            "right-click and choose \"📥 Download to temp directory\" (up to 20 "
            "favorite folders, or Browse... for something temporary), or pick "
            "\"Ask me where to save the next download\" there to get the normal "
            "Save pop-up just once."
        )
        qd_hint.setWordWrap(True)
        qd_hint.setStyleSheet("color:%s; font-size:8pt;" % C_STATUS_FG)
        lay.addWidget(qd_hint)

        # ---- DEL 46: what to do when the name is already taken -------------
        row_dupe = QHBoxLayout()
        row_dupe.addWidget(QLabel("When you already have a file with that name:"))
        self.cmb_dupe = QComboBox()
        for key, label in DUPE_CHOICES:
            self.cmb_dupe.addItem(label, key)
        _cur = self.win._active_profile().get("dupe_policy", DUPE_ASK)
        _i = self.cmb_dupe.findData(_cur)
        self.cmb_dupe.setCurrentIndex(_i if _i >= 0 else 0)
        row_dupe.addWidget(self.cmb_dupe, 1)
        lay.addLayout(row_dupe)
        dupe_hint = QLabel(
            "Saving the same program again and again used to just keep adding "
            "numbers \u2014 Foo.py, Foo (1).py, Foo (2).py \u2014 which is safe but turns "
            "into housekeeping. \"Back up the old one\" renames what is already "
            "there to Backup&lt;CODE&gt;-Foo.py (the same convention File_manager "
            "uses, sharing the same list of used codes, so two backups can never "
            "collide) and lets the new file take the clean name. A download that "
            "ARRIVES already numbered counts too: \"Foo (3).py\" landing next to "
            "\"Foo.py\" is recognised as the same file, not a new one. Nothing is "
            "deleted until the download has actually finished \u2014 if it fails, your "
            "old file is put straight back. This is saved for the ACTIVE profile."
        )
        dupe_hint.setWordWrap(True)
        dupe_hint.setStyleSheet("color:%s; font-size:8pt;" % C_STATUS_FG)
        lay.addWidget(dupe_hint)

        # ---- Torrents & magnet links (DEL 49) ------------------------------
        header("Torrents & magnet links  🧲")
        tor_hint = QLabel(
            "A magnet link is not a file — there is nothing behind it to fetch, "
            "only a fingerprint of what you want and a hint about who might "
            "have it. That is why clicking one in an ordinary browser appears "
            "to do nothing at all.\n\n"
            "WhyBrowse can do three things with one, and you pick which:\n"
            "  •  DOWNLOAD IT HERE — the built-in engine (libtorrent, the same "
            "engine qBittorrent and Deluge are built on) fetches the real files "
            "into the folder below. Progress is in ☰ menu ▸ 🧲 Torrents.\n"
            "  •  SAVE THE LINK — writes a small \"name.magnet\" file into the "
            "folder. Point your torrent program's WATCH folder at it and it "
            "picks the link up by itself, seconds later.\n"
            "  •  OPEN IN MY TORRENT PROGRAM — hands it to whichever program "
            "Windows uses for magnet: links.\n\n"
            "An ordinary https://…/something.torrent address counts as a "
            "torrent link too, so it never lands in your normal Downloads "
            "folder by mistake."
        )
        tor_hint.setWordWrap(True)
        tor_hint.setStyleSheet("color:%s; font-size:9pt;" % C_STATUS_FG)
        lay.addWidget(tor_hint)

        self.chk_torrent = QCheckBox(
            "🧲  Notice magnet: and .torrent links at all")
        self.chk_torrent.setChecked(bool(self._s.get("torrent_enabled", True)))
        lay.addWidget(self.chk_torrent)

        lay.addWidget(QLabel("When I meet a torrent link:"))
        self.cmb_torrent_mode = QComboBox()
        for key, label in TORRENT_MODES:
            self.cmb_torrent_mode.addItem(label, key)
        _i = self.cmb_torrent_mode.findData(self._s.get("torrent_mode", "ask"))
        self.cmb_torrent_mode.setCurrentIndex(_i if _i >= 0 else 0)
        lay.addWidget(self.cmb_torrent_mode)

        lay.addWidget(QLabel("…and then do this with it:"))
        self.cmb_torrent_action = QComboBox()
        for key, label in TORRENT_ACTIONS:
            self.cmb_torrent_action.addItem(label, key)
        _i = self.cmb_torrent_action.findData(self._s.get("torrent_action", "download"))
        self.cmb_torrent_action.setCurrentIndex(_i if _i >= 0 else 0)
        lay.addWidget(self.cmb_torrent_action)

        lay.addWidget(QLabel("Torrents are saved in:"))
        self.cmb_torrent_where = QComboBox()
        self.cmb_torrent_where.addItem("a separate torrent folder (below)", "custom")
        self.cmb_torrent_where.addItem("the ordinary download folder", "downloads")
        _i = self.cmb_torrent_where.findData(self._s.get("torrent_folder_mode", "custom"))
        self.cmb_torrent_where.setCurrentIndex(_i if _i >= 0 else 0)
        lay.addWidget(self.cmb_torrent_where)

        row_tor = QHBoxLayout()
        self.ed_torrent_dir = QLineEdit(self._s.get("torrent_folder", "") or "")
        self.ed_torrent_dir.setPlaceholderText("e.g. X:\\")
        row_tor.addWidget(self.ed_torrent_dir, 1)
        for _txt, _fn in (("Browse…", self._browse_torrent_dir),
                          ("📂 Open folder", self._open_torrent_dir)):
            _b = QPushButton(_txt)
            _b.setStyleSheet(
                "QPushButton{background:%s; color:%s; border:none; padding:5px 12px;"
                " border-radius:6px;}QPushButton:hover{background:%s;}"
                % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
            _b.clicked.connect(_fn)
            row_tor.addWidget(_b)
        lay.addLayout(row_tor)

        self.chk_torrent_clip = QCheckBox(
            "📋  Act the moment I COPY a magnet link, anywhere  (this is the "
            "\"I just copied a torrent link\" case)")
        self.chk_torrent_clip.setChecked(
            bool(self._s.get("torrent_watch_clipboard", True)))
        lay.addWidget(self.chk_torrent_clip)
        clip_hint = QLabel(
            "Only magnet links are picked up from the clipboard — an ordinary "
            "web address that ends in .torrent is copied for all kinds of "
            "reasons, a magnet link only ever for one. The same link is never "
            "asked about twice within two minutes, however many times it is "
            "copied.")
        clip_hint.setWordWrap(True)
        clip_hint.setStyleSheet("color:%s; font-size:8pt;" % C_STATUS_FG)
        lay.addWidget(clip_hint)

        self.chk_torrent_autoclose = QCheckBox(
            "✖  Close the Torrents window by itself when everything has finished")
        self.chk_torrent_autoclose.setChecked(
            bool(self._s.get("torrent_autoclose", False)))
        lay.addWidget(self.chk_torrent_autoclose)
        ac_hint = QLabel(
            "The same tick-box sits in the Torrents window itself. It only "
            "closes a window that had something RUNNING in it, so opening the "
            "list of finished torrents never makes it shut in your face. The "
            "Torrents window is an ordinary window, by the way — it can go "
            "behind WhyBrowse and has its own taskbar button.")
        ac_hint.setWordWrap(True)
        ac_hint.setStyleSheet("color:%s; font-size:8pt;" % C_STATUS_FG)
        lay.addWidget(ac_hint)

        self.chk_torrent_resume = QCheckBox(
            "▶  Continue unfinished torrents when WhyBrowse starts")
        self.chk_torrent_resume.setChecked(
            bool(self._s.get("torrent_resume_on_start", True)))
        lay.addWidget(self.chk_torrent_resume)

        self.chk_torrent_seed = QCheckBox(
            "⬆  Keep uploading (seeding) after a download has finished")
        self.chk_torrent_seed.setChecked(bool(self._s.get("torrent_seed_after", False)))
        lay.addWidget(self.chk_torrent_seed)
        seed_hint = QLabel(
            "Off means a finished torrent is PAUSED — nothing keeps uploading "
            "from your computer without you knowing. Turn it on if you want to "
            "give back to the swarm.")
        seed_hint.setWordWrap(True)
        seed_hint.setStyleSheet("color:%s; font-size:8pt;" % C_STATUS_FG)
        lay.addWidget(seed_hint)

        self.chk_torrent_upnp = QCheckBox(
            "🔌  Ask the router to open a port (UPnP) — MAKES CLOSING WhyBrowse "
            "TAKE ~20 SECONDS")
        self.chk_torrent_upnp.setChecked(bool(self._s.get("torrent_upnp", False)))
        lay.addWidget(self.chk_torrent_upnp)
        upnp_hint = QLabel(
            "Measured, not guessed: libtorrent's UPnP shutdown waits for the "
            "router to confirm that the port mapping is gone, and that wait "
            "blocks the whole program — so closing the browser would take "
            "about 20 seconds. Downloads work perfectly well without it; it "
            "only lets MORE peers connect to you.")
        upnp_hint.setWordWrap(True)
        upnp_hint.setStyleSheet("color:%s; font-size:8pt;" % C_STATUS_FG)
        lay.addWidget(upnp_hint)

        row_lim = QHBoxLayout()
        row_lim.addWidget(QLabel("Speed limits (KB/s, 0 = no limit).  Down:"))
        self.spin_tor_dl = QSpinBox()
        self.spin_tor_dl.setRange(0, 1000000)
        self.spin_tor_dl.setValue(int(self._s.get("torrent_dl_limit_kbs", 0) or 0))
        row_lim.addWidget(self.spin_tor_dl)
        row_lim.addWidget(QLabel("Up:"))
        self.spin_tor_ul = QSpinBox()
        self.spin_tor_ul.setRange(0, 1000000)
        self.spin_tor_ul.setValue(int(self._s.get("torrent_ul_limit_kbs", 0) or 0))
        row_lim.addWidget(self.spin_tor_ul)
        row_lim.addWidget(QLabel("Port:"))
        self.spin_tor_port = QSpinBox()
        self.spin_tor_port.setRange(1024, 65535)
        self.spin_tor_port.setValue(int(self._s.get("torrent_port", 6881) or 6881))
        row_lim.addWidget(self.spin_tor_port)
        row_lim.addStretch(1)
        lay.addLayout(row_lim)

        _v = libtorrent_version()
        lbl_eng = QLabel(
            ("Built-in engine: libtorrent %s — ready." % _v) if _v else
            ("The built-in engine is NOT installed, so \"download the files "
             "here\" cannot run. Install it once with:   pip install libtorrent"
             "   ·  Saving the link and handing it to your own torrent program "
             "work without it."))
        lbl_eng.setWordWrap(True)
        lbl_eng.setStyleSheet("color:%s; font-size:9pt;"
                              % (C_ACCENT if _v else "#c0392b"))
        lay.addWidget(lbl_eng)

        # ---- Uploads (the opposite of downloads: per-site folders) ----
        header("Uploads  (picking files to SEND to a site)")
        up_hint = QLabel(
            "Downloads all go to the one folder above. Uploads are the opposite — "
            "every site wants a different folder, and a normal browser just opens "
            "wherever you last picked a file, which is why a site whose files live "
            "on another drive keeps starting in the wrong place. Give a site its "
            "own upload folder from: right-click its tab → THIS DOMAIN → "
            "\"📤 Upload folder for this site…\". Your favourite folders are "
            "offered as a one-click list in the pop-up."
        )
        up_hint.setWordWrap(True)
        up_hint.setStyleSheet("color:%s; font-size:9pt;" % C_STATUS_FG)
        lay.addWidget(up_hint)

        row_up = QHBoxLayout()
        row_up.addWidget(QLabel("Show the folder pop-up:"))
        self.cmb_upload_ask = QComboBox()
        for label, key in (
                ("Only when the site has no folder yet  (recommended)", "unset"),
                ("Every time I upload", "always"),
                ("Never — go straight to the file picker", "never")):
            self.cmb_upload_ask.addItem(label, key)
        _cur_ask = self.win.settings.get("upload_ask", "unset")
        _idx = self.cmb_upload_ask.findData(_cur_ask)
        self.cmb_upload_ask.setCurrentIndex(_idx if _idx >= 0 else 0)
        row_up.addWidget(self.cmb_upload_ask, 1)
        lay.addLayout(row_up)

        row_pk = QHBoxLayout()
        row_pk.addWidget(QLabel("File picker:"))
        self.cmb_upload_picker = QComboBox()
        for label, key in (
                ("WhyBrowse picker - recent folders in the left column  (recommended)", "own"),
                ("The Windows picker", "windows")):
            self.cmb_upload_picker.addItem(label, key)
        _ipk = self.cmb_upload_picker.findData(
            self.win.settings.get("upload_picker", "own"))
        self.cmb_upload_picker.setCurrentIndex(_ipk if _ipk >= 0 else 0)
        row_pk.addWidget(self.cmb_upload_picker, 1)
        lay.addLayout(row_pk)

        row_st = QHBoxLayout()
        row_st.addWidget(QLabel("The picker opens in:"))
        self.cmb_upload_start = QComboBox()
        for label, key in (
                ("This profile's default folder  (recommended - opens at once)", "profile"),
                ("The folder last used on the site, else the site's folder", "site")):
            self.cmb_upload_start.addItem(label, key)
        _ist = self.cmb_upload_start.findData(
            self.win.settings.get("upload_start", "profile"))
        self.cmb_upload_start.setCurrentIndex(_ist if _ist >= 0 else 0)
        row_st.addWidget(self.cmb_upload_start, 1)
        lay.addLayout(row_st)

        pk_hint = QLabel(
            "Default: the picker opens in this profile's default folder (set under "
            "Profiles -> download folder, e.g. C:\\0---Temp), so a folder full of "
            "pictures is not loaded every time. With the other choice it opens in the "
            "folder you last picked from on that site (for 3 hours). Either way its "
            "left column keeps your pinned folders and the last "
            "12 you picked from (buttons Pin / Remove under the list).")
        pk_hint.setWordWrap(True)
        pk_hint.setStyleSheet("color:%s; font-size:8pt;" % C_STATUS_FG)
        lay.addWidget(pk_hint)

        _nfav = len(self.win.settings.get("upload_favs", []) or [])
        _nsite = len(self.win.settings.get("upload_dirs", {}) or {})
        up_stat = QLabel("Currently: %d favourite folder(s), %d site(s) with their "
                         "own upload folder." % (_nfav, _nsite))
        up_stat.setStyleSheet("color:%s; font-size:8pt;" % C_STATUS_FG)
        lay.addWidget(up_stat)

        # ---- Engine / Dependencies ----
        header("Engine & dependencies")
        lay.addWidget(EngineUpdatePanel(self))

        if platform.system() == "Windows":
            default_hint = QLabel(
                "Register WhyBrowse as the default browser so that links in "
                "other apps open here. Writes to your user registry (HKCU) — "
                "no admin rights needed. After clicking, finish in "
                "Windows Settings → Apps → Default apps."
            )
            default_hint.setWordWrap(True)
            default_hint.setStyleSheet("color:%s; font-size:9pt;" % C_STATUS_FG)
            lay.addWidget(default_hint)

            row_def = QHBoxLayout()
            self.btn_set_default = QPushButton("Set WhyBrowse as default browser")
            self.btn_set_default.setStyleSheet(
                "QPushButton{background:%s; color:%s; border:none; padding:6px 14px; "
                "border-radius:6px; font-weight:bold;}QPushButton:hover{background:%s;}"
                % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
            self.btn_set_default.clicked.connect(self._set_as_default)
            row_def.addWidget(self.btn_set_default)
            row_def.addStretch(1)
            lay.addLayout(row_def)

            self.lbl_default = QLabel("")
            self.lbl_default.setWordWrap(True)
            self.lbl_default.setStyleSheet(
                "color:%s; font-size:9pt; font-family:monospace;" % C_STATUS_FG)
            lay.addWidget(self.lbl_default)

        lay.addStretch(1)

        # ---- Buttons ----
        btns = QHBoxLayout()
        btns.addStretch(1)
        for txt, fn, col in (("Save", self.accept, C_ACCENT),
                             ("Cancel", self.reject, C_BTN_BG)):
            b = QPushButton(txt)
            fg = C_ACCENT_FG if col == C_ACCENT else C_BTN_FG
            b.setStyleSheet(
                "QPushButton{background:%s; color:%s; border:none; padding:7px 20px; "
                "border-radius:6px; font-weight:bold;}QPushButton:hover{background:%s;}"
                % (col, fg, C_BTN_BG_HOV))
            b.clicked.connect(fn)
            btns.addWidget(b)
        outer.addLayout(btns)

        # Built last, on purpose: every row exists by now, so nothing is
        # left demanding more width than the window has.
        wrap_wide_controls(host, max_px=560)

        # The wheel scrolls this page and changes nothing on the way past.
        # Installed LAST, so it catches every control built above - including
        # any added later without anyone remembering this line exists.
        self._wheel_guard = WheelGuard(scroll).protect(host)

    # ---- Location helpers ----
    def _refill_city_combo(self, select=None):
        self.cmb_city.blockSignals(True)
        self.cmb_city.clear()
        names = [r.get("name") for r in self._recents]          # recents first
        for p in CITY_PRESETS:                                   # then presets
            if p not in names:
                names.append(p)
        self.cmb_city.addItems(names)
        if select and select in names:
            self.cmb_city.setCurrentText(select)
        elif self._recents:
            self.cmb_city.setCurrentText(self._recents[0].get("name"))  # most recent
        self.cmb_city.blockSignals(False)

    def _city_changed(self, name):
        if name in self._recent_map:
            lat, lon = self._recent_map[name]
        elif name in CITY_PRESETS:
            lat, lon = CITY_PRESETS[name]
        else:
            return
        self.ed_lat.setText(str(lat))
        self.ed_lon.setText(str(lon))

    def _do_lookup(self):
        q = self.ed_lookup.text().strip()
        if not q:
            return
        self.lbl_lookup.setText("Looking up '%s'..." % q)
        QApplication.processEvents()
        res = geocode_place(q)
        if not res:
            self.lbl_lookup.setText("Could not find '%s' (check spelling / connection)." % q)
            return
        lat, lon, display = res
        self.ed_lat.setText(str(lat))
        self.ed_lon.setText(str(lon))
        # Add to recents (front, deduped, max 10) and select it
        name = q
        self._recents = [r for r in self._recents if r.get("name") != name]
        self._recents.insert(0, {"name": name, "lat": lat, "lon": lon})
        self._recents = self._recents[:10]
        self._recent_map = {r.get("name"): (r.get("lat"), r.get("lon")) for r in self._recents}
        self._refill_city_combo(select=name)
        self.lbl_lookup.setText("Found: %s" % display[:70])

    # ---- Copymarks is an ACTION, not a saved state: run it, then reset the box ----
    def _copymarks_toggled(self, on):
        if not on:
            return
        self.chk_copymarks.blockSignals(True)
        self.chk_copymarks.setChecked(False)
        self.chk_copymarks.blockSignals(False)
        self.win.copy_all_other_bookmarks()

    # ---- Appearance helpers ----
    @staticmethod
    def _preset_name(theme):
        """Which preset (if any) the current theme colours match - else custom."""
        for name, preset in THEME_PRESETS.items():
            if all(theme.get(k) == preset.get(k) for k in THEME_KEYS):
                return name
        return "(custom)"

    def _theme_preset_changed(self, name):
        if name in THEME_PRESETS:
            self._theme = dict(THEME_PRESETS[name])
            self.lbl_theme.setText("Preset '%s' will be applied when you Save." % name)

    def _pick_bg_color(self):
        col = QColorDialog.getColor(parent=self, title="Choose background color")
        if col.isValid():
            hexc = col.name()
            fg = contrast_fg(hexc)
            # Apply the chosen background across the chrome + blank page
            self._theme.update({
                "C_BAR_BG": hexc, "C_TAB_BG": hexc, "C_TAB_SEL": hexc,
                "C_ADDR_BG": hexc, "C_NEWTAB_BG": hexc, "C_BTN_BG": hexc,
                "C_BAR_FG": fg, "C_BTN_FG": fg, "C_ADDR_FG": fg,
                "C_TAB_FG": fg, "C_TAB_FG_SEL": fg, "C_NEWTAB_FG": fg,
            })
            self.cmb_theme.setCurrentText("(custom)")
            self.lbl_theme.setText("Custom background %s will be applied on Save." % hexc)

    def _pick_accent_color(self):
        col = QColorDialog.getColor(parent=self, title="Choose accent color")
        if col.isValid():
            hexc = col.name()
            self._theme.update({"C_ACCENT": hexc, "C_ACCENT_FG": contrast_fg(hexc)})
            self.cmb_theme.setCurrentText("(custom)")
            self.lbl_theme.setText("Custom accent %s will be applied on Save." % hexc)

    # ---- Default download folder (active profile) ----
    def _browse_download_dir(self):
        start = self.ed_download.text().strip() or os.path.expanduser("~")
        d = QFileDialog.getExistingDirectory(self, "Choose default download folder", start)
        if d:
            self.ed_download.setText(d)

    # ---- Torrent folder (DEL 49) ----
    def _browse_torrent_dir(self):
        start = self.ed_torrent_dir.text().strip() or os.path.expanduser("~")
        d = QFileDialog.getExistingDirectory(self, "Choose the torrent folder", start)
        if d:
            self.ed_torrent_dir.setText(d)

    def _open_torrent_dir(self):
        path = self.ed_torrent_dir.text().strip()
        if not os.path.isdir(path):
            show_toast(self.win, "Not there (yet): %s" % (path or "-"))
            return
        try:
            open_path(path)
        except Exception:
            show_toast(self.win, "Torrent folder: %s" % path)

    def _open_download_dir(self):
        path = self.ed_download.text().strip() or os.path.join(
            os.path.expanduser("~"), "Downloads")
        if not os.path.isdir(path):
            path = os.path.expanduser("~")
        try:
            open_path(path)               # Windows file explorer
        except Exception:
            show_toast(self.win, "Download folder: %s" % path)

    def _set_as_default(self):
        ok, msg = set_default_browser_windows()
        self.lbl_default.setText(msg)
        if ok:
            self.lbl_default.setStyleSheet(
                "color:#1f8a4c; font-size:9pt; font-weight:bold;")
            # Also open Windows "Default apps" settings so the user can finish
            # with one click (ms-settings: URI works on Win 10/11).
            try:
                import subprocess as _sp
                _sp.Popen(["cmd", "/c", "start", "",
                           "ms-settings:defaultapps"],
                          shell=False,
                          creationflags=0x08000000)  # CREATE_NO_WINDOW
            except Exception:
                pass
        else:
            self.lbl_default.setStyleSheet(
                "color:#c0392b; font-size:9pt; font-family:monospace;")

    def result_settings(self):
        """Collect the edited values back into a settings dict."""
        def lines(widget):
            return [x.strip() for x in widget.toPlainText().splitlines() if x.strip()]

        # element-hide rules: parse "domain##selector"
        rules = []
        for ln in lines(self.txt_elemhide):
            if "##" in ln:
                dom, sel = ln.split("##", 1)
                if dom.strip() and sel.strip():
                    rules.append({"domain": dom.strip(), "selector": sel.strip()})

        try:
            lat = float(self.ed_lat.text().strip())
            lon = float(self.ed_lon.text().strip())
        except Exception:
            lat, lon = 58.5256, 13.4926

        # The chosen place becomes the most-recent entry
        city = self.cmb_city.currentText()
        recents = [r for r in self._recents if r.get("name") != city]
        recents.insert(0, {"name": city, "lat": lat, "lon": lon})
        recents = recents[:10]

        return {
            "startup_mode": self.cmb_startup.currentText(),
            "new_tab_mode": self.cmb_newtab.currentText(),
            "home_url": self.ed_home.text().strip() or DEFAULT_HOME,
            "search_engine": (
                self.ed_search.text().strip() or SEARCH_URL
                if self.cmb_search.currentData() == "__custom__"
                else self.cmb_search.currentData()
            ),
            "adblock_enabled": self.chk_adblock.isChecked(),
            "block_third_party_cookies": self.chk_cookies.isChecked(),
            "stay_signed_in": self.chk_signedin.isChecked(),
            "challenge_auto_relax": self.chk_challenge.isChecked(),
            "user_agent": self.ed_ua.text().strip(),
            "chrome_identity": self.chk_chrome_id.isChecked(),
            "hide_nag_banners": self.chk_nags.isChecked(),
            "youtube_adblock": self.chk_ytads.isChecked(),
            "imdb_reference": self.chk_imdb.isChecked(),
            "keep_profile_tabs_alive": self.chk_keepalive.isChecked(),
            "check_engine_updates": self.chk_engine_update.isChecked(),
            "auto_sleep_all": self.chk_sleepall.isChecked(),
            "sleep_pinned_too": self.chk_sleeppinned.isChecked(),
            "tab_autosleep_min": int(self.spin_sleep.value()),
            "tab_autorefresh_min": int(self.spin_autorefresh.value()),
            "keep_bg_active": self.chk_keepbg.isChecked(),
            "sheet_remember_cell": self.chk_sheetcell.isChecked(),
            "form_memory": self.chk_formmem.isChecked(),
            "scroll_speed": round(self.sld_scroll.value() / 100.0, 2),
            "scroll_guard": self.chk_scroll_guard.isChecked(),
            "keep_scroll": self.chk_keep_scroll.isChecked(),
            "adblock_extra": lines(self.txt_adblock),
            "freeze_animations": self.chk_freeze.isChecked(),
            "search_block_domains": lines(self.txt_searchblock),
            "native_find_domains": lines(self.txt_native_find),
            "upload_ask": (self.cmb_upload_ask.currentData() or "unset"),
            "upload_picker": (self.cmb_upload_picker.currentData() or "own"),
            "upload_start": (self.cmb_upload_start.currentData() or "profile"),
            "element_hide_rules": rules,
            "spoof_location": {
                "enabled": self.chk_spoof.isChecked(),
                "city": city, "lat": lat, "lon": lon,
            },
            "location_recents": recents,
            "bookmark_duplicate_mode": self.cmb_dup_mode.currentData(),
            "open_link_default": self.cmb_open_link.currentData(),
            "links_open_new_tab": self.chk_links_new.isChecked(),
            # ---- The temp tab (DEL 44) ----
            "temp_tab_enabled": self.chk_temp.isChecked(),
            "temp_tab_slots": int(self.spin_temp.value()),
            "temp_tab_restore": self.chk_temp_restore.isChecked(),
            "temp_locked_override": self.chk_temp_locked.isChecked(),
            "open_bookmark_default": self.cmb_bm_open.currentData(),
            # ---- Torrents & magnet links (DEL 49) ----
            "torrent_enabled": self.chk_torrent.isChecked(),
            "torrent_mode": self.cmb_torrent_mode.currentData() or "ask",
            "torrent_action": self.cmb_torrent_action.currentData() or "download",
            "torrent_folder_mode": self.cmb_torrent_where.currentData() or "custom",
            "torrent_folder": self.ed_torrent_dir.text().strip(),
            "torrent_watch_clipboard": self.chk_torrent_clip.isChecked(),
            "torrent_resume_on_start": self.chk_torrent_resume.isChecked(),
            "torrent_seed_after": self.chk_torrent_seed.isChecked(),
            "torrent_autoclose": self.chk_torrent_autoclose.isChecked(),
            "torrent_upnp": self.chk_torrent_upnp.isChecked(),
            "torrent_dl_limit_kbs": int(self.spin_tor_dl.value()),
            "torrent_ul_limit_kbs": int(self.spin_tor_ul.value()),
            "torrent_port": int(self.spin_tor_port.value()),
            # keep the older flag in step so anything still reading it agrees
            "bar_open_new_tab": self.cmb_bm_open.currentData() != "same",
            "theme": self._theme,
        }

    def keyPressEvent(self, e):
        if e.key() == Qt.Key.Key_Escape:
            self.reject()
        else:
            super().keyPressEvent(e)


# ============================================================================
#  DEL 14E - VAULT DIALOG  (manage saved logins + autofill; ESC closes)
# ============================================================================
class GoogleLoginImportDialog(QDialog):
    """Carry a finished Google sign-in over from Firefox (DEL 50, route B).

    The escape hatch for the profile Google's sign-in will not let in. It copies
    the session cookies of a Firefox profile that IS signed in, into ONE chosen
    WhyBrowse profile - which is why the target profile is named in full on the
    button: the other profiles' logins must not be touched by a mis-click."""

    def __init__(self, window):
        super().__init__(window)
        self.win = window
        self.setWindowTitle(APP_NAME + " - Bring a Google sign-in over from Firefox")
        self.setModal(True)
        self.resize(680, 500)
        self.setStyleSheet(dialog_qss())
        apply_window_icon(self)
        lay = QVBoxLayout(self)

        lay.addWidget(QLabel(
            "<b>For a profile Google will not let you sign in to.</b><br>"
            "If Google answers \"Couldn't sign you in - this browser or app may "
            "not be secure\", this copies a sign-in you already have in Firefox "
            "instead of fighting that check. Sign in to Google in Firefox first, "
            "then pick that Firefox profile below."))

        lay.addWidget(QLabel("<b>1. Firefox profile to copy FROM:</b>"))
        self.cmb_ff = QComboBox()
        # Years of Firefox profiles pile up (17 on this machine, most of them
        # long dead), so read every one ONCE up front and say in the list itself
        # which are signed in. Picking blind through seventeen identical hex
        # names is not a choice anyone can make. The cache also means switching
        # entries in the dropdown costs nothing.
        self._ff_cache = {}
        self._ff = firefox_profile_list()
        for label, folder in self._ff:
            try:
                rows = read_firefox_cookies(folder)
            except Exception:
                rows = []
            self._ff_cache[folder] = rows
            names = set(r["name"] for r in rows)
            if any(n in names for n in GOOGLE_SESSION_COOKIES):
                mark = "  ✔ signed in to Google"
            elif rows:
                mark = "  – visited Google, not signed in"
            else:
                mark = "  – nothing from Google"
            self.cmb_ff.addItem(label + mark, folder)
        if not self._ff:
            self.cmb_ff.addItem("(no Firefox profile with cookies was found)", None)
            self.cmb_ff.setEnabled(False)
        else:
            # Land on a profile that can actually be used, not merely the newest.
            for i in range(self.cmb_ff.count()):
                if "✔" in self.cmb_ff.itemText(i):
                    self.cmb_ff.setCurrentIndex(i)
                    break
        lay.addWidget(self.cmb_ff)

        lay.addWidget(QLabel("<b>2. WhyBrowse profile to copy INTO:</b>"))
        self.cmb_target = QComboBox()
        for p in self.win.settings.get("profiles", []):
            if not p.get("enabled", True):
                continue
            mark = "  ← the one you are using now" if p["id"] == self.win.active_id else ""
            self.cmb_target.addItem("%s%s" % (p.get("name", p["id"]), mark), p["id"])
        idx = self.cmb_target.findData(self.win.active_id)
        if idx >= 0:
            self.cmb_target.setCurrentIndex(idx)
        lay.addWidget(self.cmb_target)

        self.chk_youtube = QCheckBox("Bring YouTube's cookies over too")
        self.chk_youtube.setChecked(True)
        lay.addWidget(self.chk_youtube)

        self.info = QTextBrowser()
        self.info.setMinimumHeight(150)
        lay.addWidget(self.info, 1)

        row = QHBoxLayout()
        self.b_import = QPushButton("Import")
        self.b_import.clicked.connect(self._do_import)
        b_close = QPushButton("Close")
        b_close.clicked.connect(self.reject)
        row.addStretch(1)
        row.addWidget(self.b_import)
        row.addWidget(b_close)
        lay.addLayout(row)

        self.cmb_ff.currentIndexChanged.connect(self._scan)
        self.cmb_target.currentIndexChanged.connect(self._update_button)
        self.chk_youtube.toggled.connect(self._scan)
        self._scan()

    # ---------------------------------------------------------------- scan ----
    def _hosts(self):
        return FF_COOKIE_HOSTS if self.chk_youtube.isChecked() else ("google.com",)

    def _scan(self):
        """Report what the chosen Firefox profile actually holds.

        Counting cookies is not enough to say "signed in": a Firefox that has
        only ever visited google.com still has a dozen preference cookies. Only
        the session cookies in GOOGLE_SESSION_COOKIES mean a real login."""
        folder = self.cmb_ff.currentData()
        self._rows = []
        if not folder:
            self.info.setHtml("<p>No Firefox profile found.</p>")
            self._update_button()
            return
        try:
            if self.chk_youtube.isChecked() and folder in self._ff_cache:
                self._rows = self._ff_cache[folder]      # already read at build
            else:
                self._rows = read_firefox_cookies(folder, self._hosts())
        except Exception as e:
            self.info.setHtml("<p><b>Could not read that profile's cookies:</b><br>%s</p>"
                              % html_escape(str(e)))
            self._update_button()
            return
        names = set(r["name"] for r in self._rows)
        found = [n for n in GOOGLE_SESSION_COOKIES if n in names]
        google = [r for r in self._rows if "google.com" in r["host"]]
        yt = [r for r in self._rows if "youtube.com" in r["host"]]
        parts = ["<p><b>%d cookies</b> for google.com" % len(google)]
        if yt:
            parts.append(" and <b>%d</b> for youtube.com" % len(yt))
        parts.append(".</p>")
        if found:
            parts.append("<p style='color:#7ddc7d'><b>This Firefox profile is "
                         "signed in to Google.</b><br>Session cookies present: %s</p>"
                         % html_escape(", ".join(found)))
            parts.append("<p>It will bring over <b>whichever Google account that "
                         "Firefox is signed in as</b> — WhyBrowse cannot read the "
                         "address from a cookie, so open Drive afterwards and "
                         "check the account picture is the one you wanted.</p>")
        else:
            parts.append("<p style='color:#e8a33d'><b>No Google session cookies "
                         "here</b> — this Firefox profile is not signed in, so "
                         "there is nothing to carry over. Open Firefox with this "
                         "profile, sign in to Google, close Firefox, then come "
                         "back.</p>")
        parts.append("<p><i>The chosen WhyBrowse profile's current Google "
                     "session is replaced. Other profiles are untouched.</i></p>")
        self.info.setHtml("".join(parts))
        self._has_session = bool(found)
        self._update_button()

    def _update_button(self):
        ok = bool(getattr(self, "_rows", None)) and getattr(self, "_has_session", False)
        self.b_import.setEnabled(ok)
        name = self.cmb_target.currentText().split("  ←")[0]
        self.b_import.setText("Import into \"%s\"" % name if ok else "Import")

    # -------------------------------------------------------------- import ----
    def _do_import(self):
        pid = self.cmb_target.currentData()
        name = self.cmb_target.currentText().split("  ←")[0]
        if QMessageBox.question(
                self, "Import Google sign-in",
                "Copy this Firefox Google session into the profile \"%s\"?\n\n"
                "That profile's current Google login is replaced." % name,
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
                QMessageBox.StandardButton.No) != QMessageBox.StandardButton.Yes:
            return
        self.b_import.setEnabled(False)
        self.b_import.setText("Importing…")
        self.win.install_google_cookies(
            pid, self._rows, lambda ok, bad: self._imported(pid, name, ok, bad))

    def _imported(self, pid, name, ok, bad):
        """install_google_cookies() calls this back once the store has answered."""
        if not ok:
            QMessageBox.warning(
                self, "Import Google sign-in",
                "Nothing was stored — the profile \"%s\" rejected every cookie.\n\n"
                "See Helpfiles\\0---Empty\\whybrowse_log.txt for the reason." % name)
            self.b_import.setEnabled(True)
            self._update_button()
            return
        msg = "Stored %d cookies in \"%s\"." % (ok, name)
        if bad:
            msg += "\n%d were not accepted." % bad
        msg += "\n\nOpen drive.google.com now to check it worked?"
        ans = QMessageBox.question(
            self, "Import Google sign-in", msg,
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            QMessageBox.StandardButton.Yes)
        self.accept()
        if ans == QMessageBox.StandardButton.Yes:
            self.win.open_google_drive_check(pid)


class VaultDialog(QDialog):
    def __init__(self, window):
        super().__init__(window)
        self.win = window
        self.v = window._vault
        self.setWindowTitle(APP_NAME + " - Passwords & autofill")
        self.setModal(True)
        self.resize(620, 600)
        self.setStyleSheet(dialog_qss())
        apply_window_icon(self)
        lay = QVBoxLayout(self)

        af = self.v.setdefault("autofill", {})
        lay.addWidget(self._hdr("Autofill (Ctrl+click the profile tag = address)"))
        grid = QGridLayout()
        self.ed = {}
        for r, (key, label) in enumerate((("email", "E-mail / login"), ("name", "Full name"),
                                          ("address", "Address"), ("phone", "Phone"))):
            grid.addWidget(QLabel(label + ":"), r, 0)
            e = QLineEdit(af.get(key, ""))
            self.ed[key] = e
            grid.addWidget(e, r, 1)
        lay.addLayout(grid)

        lay.addWidget(self._hdr("Saved logins (Shift+click the profile tag = password)"))
        self.listw = QListWidget()
        self.listw.itemDoubleClicked.connect(lambda _i: self._edit())
        lay.addWidget(self.listw, 1)
        self._reload()

        row = QHBoxLayout()
        for txt, fn in (("Add", self._add), ("Edit", self._edit), ("Delete", self._delete),
                        ("Save", self._save), ("Close", self.accept)):
            b = QPushButton(txt)
            b.setStyleSheet("QPushButton{background:%s; color:%s; border:none; padding:6px 14px;"
                            "border-radius:6px;}QPushButton:hover{background:%s;}"
                            % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
            b.clicked.connect(fn)
            row.addWidget(b)
        lay.addLayout(row)
        note = QLabel("Stored encrypted with Windows DPAPI" +
                      (" + your PIN." if window.settings.get("vault_pin_enabled", True)
                       else ". (No PIN - enable 'Extra security' in the menu for a PIN.)"))
        note.setStyleSheet("color:%s; font-size:9pt;" % C_STATUS_FG)
        lay.addWidget(note)

    def _hdr(self, t):
        l = QLabel(t)
        l.setStyleSheet("color:%s; font-weight:bold; margin-top:8px;" % C_ACCENT)
        return l

    def _reload(self):
        self.listw.clear()
        for dom, rec in sorted(self.v.get("logins", {}).items()):
            it = QListWidgetItem("%s   —   %s" % (dom, rec.get("user", "")))
            it.setData(Qt.ItemDataRole.UserRole, dom)
            self.listw.addItem(it)

    def _cur_domain(self):
        it = self.listw.currentItem()
        return it.data(Qt.ItemDataRole.UserRole) if it else None

    def _login_form(self, dom="", user="", pw=""):
        d = QDialog(self)
        d.setWindowTitle("Login")
        d.setStyleSheet(self.styleSheet())
        gl = QGridLayout(d)
        eD, eU, eP = QLineEdit(dom), QLineEdit(user), QLineEdit(pw)
        for r, (lab, e) in enumerate((("Domain (e.g. tradera.com)", eD),
                                      ("Username / e-mail", eU), ("Password", eP))):
            gl.addWidget(QLabel(lab + ":"), r, 0)
            gl.addWidget(e, r, 1)
        ok = QPushButton("OK")
        ok.clicked.connect(d.accept)
        gl.addWidget(ok, 3, 1)
        if d.exec():
            dd = clean_host(eD.text())          # accept full URLs too -> bare host
            if dd:
                return dd, eU.text().strip(), eP.text()
        return None

    def _add(self):
        r = self._login_form()
        if r:
            self.v.setdefault("logins", {})[r[0]] = {"user": r[1], "pass": r[2]}
            self._reload()

    def _edit(self):
        dom = self._cur_domain()
        if not dom:
            return
        rec = self.v["logins"][dom]
        r = self._login_form(dom, rec.get("user", ""), rec.get("pass", ""))
        if r:
            if r[0] != dom:
                self.v["logins"].pop(dom, None)
            self.v["logins"][r[0]] = {"user": r[1], "pass": r[2]}
            self._reload()

    def _delete(self):
        dom = self._cur_domain()
        if dom:
            self.v["logins"].pop(dom, None)
            self._reload()

    def _save(self):
        for key, e in self.ed.items():
            self.v.setdefault("autofill", {})[key] = e.text().strip()
        self.win._save_vault()
        show_toast(self.win, "Vault saved")

    def accept(self):
        self._save()
        super().accept()

    def keyPressEvent(self, e):
        if e.key() == Qt.Key.Key_Escape:
            self._save()
            super().accept()
        else:
            super().keyPressEvent(e)


# ============================================================================
#  DEL 14D - HISTORY DIALOG  (open / protect / remove; ESC closes)
# ============================================================================
class SheetJumpsDialog(QDialog):
    """Manage Google Sheets jumps for one spreadsheet: list / Go / Add / Edit /
    Delete. A jump target is 'Tab:Cell' (e.g. Sold:D260) or just a cell. Tick
    'Auto' to jump there automatically when you open/switch to that tab (● dot)."""
    def __init__(self, window, view, sid):
        super().__init__(window)
        self.win = window
        self.view = view
        self.sid = sid
        self.setWindowTitle(APP_NAME + " - Google Sheets jumps")
        self.setModal(True)
        self.resize(580, 470)
        self.setStyleSheet(dialog_qss())
        apply_window_icon(self)
        lay = QVBoxLayout(self)
        lay.addWidget(QLabel(
            "Jumps for THIS spreadsheet (● = auto-go when you open that tab).\n"
            "Target = Tab:Cell — e.g.  Sold:D260  — or just a cell (D260 / 260) on "
            "the current tab.\n"
            "You can tick Auto on several jumps for DIFFERENT tabs in this same "
            "spreadsheet (e.g. Games:D260 + Sold:D2075) — no need to switch to "
            "that tab first, it's picked up the first time you actually land on it."))
        self.listw = QListWidget()
        self.listw.currentRowChanged.connect(self._select)
        lay.addWidget(self.listw, 1)
        form = QHBoxLayout()
        form.addWidget(QLabel("Name:"))
        self.ed_name = QLineEdit()
        form.addWidget(self.ed_name, 1)
        form.addWidget(QLabel("Target:"))
        self.ed_target = QLineEdit()
        self.ed_target.setPlaceholderText("Sold:D260  or  D260  or  260")
        form.addWidget(self.ed_target, 1)
        self.chk_auto = QCheckBox("Auto")
        self.chk_auto.setToolTip("Go here automatically when you open/switch to this tab")
        form.addWidget(self.chk_auto)
        lay.addLayout(form)
        row = QHBoxLayout()
        for txt, fn in (("➡  Go", self._go), ("➕  Add new", self._add),
                        ("💾  Save changes", self._save), ("🗑  Delete", self._delete)):
            b = QPushButton(txt)
            b.clicked.connect(fn)
            row.addWidget(b)
        row.addStretch(1)
        bc = QPushButton("Close")
        bc.clicked.connect(self.accept)
        row.addWidget(bc)
        lay.addLayout(row)
        QShortcut(QKeySequence("Esc"), self, self.accept)
        self._reload()

    def _jumps(self):
        return self.win._sheet_jumps(self.sid)

    def _reload(self, sel=-1):
        self.listw.clear()
        self._rows = list(self._jumps())
        for j in self._rows:
            dot = "●  " if j.get("auto") else "    "
            self.listw.addItem("%s%s  —  %s" % (dot, j.get("name", "?"),
                                                self.win._sheet_target_str(j)))
        if 0 <= sel < len(self._rows):
            self.listw.setCurrentRow(sel)

    def _cur(self):
        i = self.listw.currentRow()
        return self._rows[i] if 0 <= i < len(self._rows) else None

    def _select(self, _=None):
        j = self._cur()
        if j:
            self.ed_name.setText(j.get("name", ""))
            self.ed_target.setText(self.win._sheet_target_str(j))
            self.chk_auto.setChecked(bool(j.get("auto")))

    def _form_to_jump(self, j):
        tab, cell = self.win._sheet_parse_target(self.ed_target.text())
        j["name"] = self.ed_name.text().strip() or cell
        j["tab"] = tab
        j["cell"] = cell
        j["auto"] = self.chk_auto.isChecked()
        info = self.win._sheet_info(self.view)     # remember which tab (gid) we're on
        if info:
            # Only stamp THIS tab's gid when the target means "the current
            # tab" (no explicit "Tab:" prefix). A target that NAMES a
            # different tab (e.g. typing "Sold:D2075" while sitting on
            # "Games") must NOT get Games' gid - leave it unresolved and let
            # WhyBrowse learn the real gid automatically the first time you
            # actually land on "Sold" (see _sheet_resolve_active_tab_name).
            # This is what lets several auto-jumps for different tabs in the
            # SAME spreadsheet (Games:D260 + Sold:D2075) coexist correctly.
            if not tab:
                j["gid"] = info[1]
            else:
                j.setdefault("gid", "")
        return j

    def _add(self):
        if not self.ed_target.text().strip():
            show_toast(self.win, "Type a target first (e.g. Sold:D260)")
            return
        self._jumps().append(self._form_to_jump({}))
        save_json(SETTINGS_FILE, self.win.settings)
        self._reload(len(self._rows))
        show_toast(self.win, "Jump added")

    def _save(self):
        j = self._cur()
        if not j:
            self._add()
            return
        i = self.listw.currentRow()
        self._form_to_jump(j)
        save_json(SETTINGS_FILE, self.win.settings)
        self._reload(i)
        show_toast(self.win, "Saved")

    def _delete(self):
        j = self._cur()
        if j and j in self._jumps():
            self._jumps().remove(j)
            save_json(SETTINGS_FILE, self.win.settings)
            self._reload()

    def _go(self):
        j = self._cur()
        if j:
            self.win._sheet_go_jump(self.view, j)


class DraftsDialog(QDialog):
    """View / recover live-saved message drafts (Vinted, Tradera, etc.). Drafts are
    kept 7 days. Click one to copy its text; open its page; or delete it."""
    def __init__(self, window):
        super().__init__(window)
        self.win = window
        self.setWindowTitle(APP_NAME + " - Recover message drafts")
        self.setModal(True)
        self.resize(680, 520)
        self.setStyleSheet(dialog_qss())
        apply_window_icon(self)
        lay = QVBoxLayout(self)
        lay.addWidget(QLabel("Your saved message drafts (kept 7 days). Click one to "
                             "see it; 'Copy' puts it on the clipboard; 'Open page' "
                             "goes back to where you wrote it."))
        self.listw = QListWidget()
        lay.addWidget(self.listw, 1)
        self.preview = QPlainTextEdit()
        self.preview.setReadOnly(True)
        self.preview.setFixedHeight(140)
        lay.addWidget(self.preview)
        self.listw.currentRowChanged.connect(self._show_preview)
        row = QHBoxLayout()
        for txt, fn in (("📋 Copy", self._copy), ("🌐 Open page", self._open),
                        ("🗑 Delete", self._delete),
                        ("🗑 Delete all", self._delete_all)):
            b = QPushButton(txt)
            b.clicked.connect(fn)
            row.addWidget(b)
        row.addStretch(1)
        bclose = QPushButton("Close")
        bclose.clicked.connect(self.accept)
        row.addWidget(bclose)
        lay.addLayout(row)
        QShortcut(QKeySequence("Esc"), self, self.accept)
        self._reload()

    def _drafts_sorted(self):
        return sorted(self.win._drafts, key=lambda d: d.get("ts", 0), reverse=True)

    def _reload(self):
        self.listw.clear()
        self._rows = self._drafts_sorted()
        import datetime
        for d in self._rows:
            when = datetime.datetime.fromtimestamp(
                d.get("ts", 0)).strftime("%Y-%m-%d %H:%M")
            snippet = (d.get("text", "")[:50] or "").replace("\n", " ")
            self.listw.addItem("%s · %s — %s" % (when, d.get("host", ""), snippet))
        if self._rows:
            self.listw.setCurrentRow(0)
        else:
            self.preview.setPlainText("(no drafts saved)")

    def _cur(self):
        i = self.listw.currentRow()
        return self._rows[i] if 0 <= i < len(self._rows) else None

    def _show_preview(self, _=None):
        d = self._cur()
        self.preview.setPlainText(d.get("text", "") if d else "")

    def _copy(self):
        d = self._cur()
        if d:
            QApplication.clipboard().setText(d.get("text", ""))
            show_toast(self.win, "Draft copied to clipboard")

    def _open(self):
        d = self._cur()
        if d and d.get("url"):
            self.win.add_tab(d["url"], switch=True)
            self.accept()

    def _delete(self):
        d = self._cur()
        if d and d in self.win._drafts:
            self.win._drafts.remove(d)
            save_json(DRAFTS_FILE, self.win._drafts)
            self._reload()

    def _delete_all(self):
        if QMessageBox.question(self, "Delete all drafts",
                                "Delete ALL saved drafts?") == QMessageBox.StandardButton.Yes:
            self.win._drafts = []
            save_json(DRAFTS_FILE, self.win._drafts)
            self._reload()


class HistoryDialog(QDialog):
    def __init__(self, window):
        super().__init__(window)
        self.win = window
        self.setWindowTitle(APP_NAME + " - History")
        self.setModal(True)
        self.resize(640, 540)
        self.setStyleSheet(dialog_qss())
        apply_window_icon(self)
        lay = QVBoxLayout(self)
        hint = QLabel("Double-click to open in a new tab. Right-click (or the buttons) "
                      "to protect - protected entries survive Clear.")
        hint.setWordWrap(True)
        hint.setStyleSheet("color:%s; font-size:9pt;" % C_STATUS_FG)
        lay.addWidget(hint)
        self.listw = QListWidget()
        self.listw.setStyleSheet(
            "QListWidget{background:%s; border:1px solid %s; border-radius:6px;}"
            "QListWidget::item{padding:5px;}"
            "QListWidget::item:selected{background:%s; color:%s;}"
            % (C_ADDR_BG, C_BORDER, C_ACCENT, C_ACCENT_FG))
        self.listw.itemDoubleClicked.connect(lambda _it: self._open())
        self.listw.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        self.listw.customContextMenuRequested.connect(self._ctx)
        lay.addWidget(self.listw, 1)
        self._reload()
        row = QHBoxLayout()
        for txt, fn in (("Open", self._open), ("Protect / Unprotect", self._toggle),
                        ("Remove", self._remove), ("Clear (keep protected)", self._clear),
                        ("Close", self.accept)):
            b = QPushButton(txt)
            b.setStyleSheet("QPushButton{background:%s; color:%s; border:none; padding:6px 12px; "
                            "border-radius:6px;}QPushButton:hover{background:%s;}"
                            % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
            b.clicked.connect(fn)
            row.addWidget(b)
        lay.addLayout(row)

    def _reload(self):
        self.listw.clear()
        for h in self.win.history:
            it = QListWidgetItem(("🔒 " if h.get("protected") else "") +
                                 "%s    %s" % (h.get("title", "")[:55], h.get("time", "")))
            it.setToolTip(h.get("url", ""))
            self.listw.addItem(it)

    def _cur(self):
        i = self.listw.currentRow()
        return self.win.history[i] if 0 <= i < len(self.win.history) else None

    def _open(self):
        h = self._cur()
        if h and h.get("url"):
            self.win.add_tab(h["url"], switch=True)

    def _toggle(self):
        h = self._cur()
        if h:
            h["protected"] = not h.get("protected")
            self.win._save_hist()
            self._reload()

    def _remove(self):
        i = self.listw.currentRow()
        if 0 <= i < len(self.win.history):
            del self.win.history[i]
            self.win._save_hist()
            self._reload()

    def _clear(self):
        self.win.clear_history()
        self._reload()

    def _ctx(self, pos):
        m = QMenu(self)
        m.setStyleSheet(self.win._menu_style())
        m.addAction("↗  Open in new tab", self._open)
        h = self._cur()
        m.addAction("🔓  Unprotect" if (h and h.get("protected")) else "🛡  Protect",
                    self._toggle)
        m.addAction("🗑  Remove", self._remove)
        m.exec(self.listw.mapToGlobal(pos))

    def keyPressEvent(self, e):
        if e.key() == Qt.Key.Key_Escape:
            self.accept()
        else:
            super().keyPressEvent(e)


# ============================================================================
#  DEL 14B2 - SAVE LOCATION DIALOG  (pick save folder; shown on every download)
# ============================================================================
class SaveLocationDialog(QDialog):
    """Quick-pick dialog shown whenever the browser triggers a file download.

    Shows the profile's default folder pre-filled in the filename field, plus
    one button per 'often used' folder so the user can switch with one click.
    A 'Browse...' button opens the system file dialog as a fallback.

    Ticking "Always download to this directory" does more than remember the
    folder: it also turns Quick-download on for this profile, so this pop-up
    stops appearing at all from then on. For a one-off exception afterwards,
    right-click and choose "Download to temp directory" instead of coming
    back here - and the default itself can always be changed in Settings.
    """
    def __init__(self, parent, suggested_name, default_dir, often_dirs):
        super().__init__(parent)
        self.setWindowTitle(APP_NAME + " - Save file")
        self.setModal(True)
        self.resize(520, 260)
        self.setStyleSheet(dialog_qss())
        apply_window_icon(self)

        self._chosen_dir = default_dir
        self._often = often_dirs   # [{"name", "path"}, ...]

        lay = QVBoxLayout(self)
        lay.setSpacing(8)

        # ---- Filename: NAME box + EXTENSION box (split on purpose) ----
        #  Two boxes, not one: the NAME box takes focus with its text selected,
        #  so you just start typing the new name; the EXTENSION box is left
        #  untouched (no focus, nothing selected), because you rarely want to
        #  change it. It IS editable for the one case where you do - e.g. a
        #  picture that came down as ".jpeg" that you'd rather keep as ".jpg".
        base, ext = os.path.splitext(suggested_name or "")
        lay.addWidget(QLabel("File name:"))
        name_row = QHBoxLayout()
        name_row.setSpacing(4)
        self.ed_name = QLineEdit(base)
        name_row.addWidget(self.ed_name, 1)
        dot_lbl = QLabel(".")
        dot_lbl.setStyleSheet("font-weight:bold;")
        name_row.addWidget(dot_lbl)
        self.ed_ext = QLineEdit(ext.lstrip("."))
        self.ed_ext.setFixedWidth(70)
        self.ed_ext.setToolTip("File extension - usually leave this as it is")
        name_row.addWidget(self.ed_ext)
        lay.addLayout(name_row)

        # ---- Current folder display ----
        lay.addWidget(QLabel("Save to:"))
        self.lbl_dir = QLabel(default_dir)
        self.lbl_dir.setStyleSheet("color:%s; font-size:9pt;" % C_ACCENT)
        self.lbl_dir.setWordWrap(True)
        lay.addWidget(self.lbl_dir)

        # ---- Often-used folder buttons ----
        if often_dirs:
            row_of = QHBoxLayout()
            row_of.setSpacing(6)
            for entry in often_dirs:
                b = QPushButton(entry["name"])
                b.setToolTip(entry["path"])
                b.setStyleSheet(
                    "QPushButton{background:%s; color:%s; border:none; padding:5px 12px;"
                    " border-radius:6px; font-size:9pt;}"
                    "QPushButton:hover{background:%s;}"
                    % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
                b.clicked.connect(lambda _=False, p=entry["path"]: self._set_dir(p))
                row_of.addWidget(b)
            row_of.addStretch(1)
            lay.addLayout(row_of)

        # ---- "Always download here" checkbox ----
        self.chk_remember = QCheckBox(
            "⚡  Always download to this directory (stop asking - change the default anytime in Settings)")
        self.chk_remember.setStyleSheet("font-size:9pt;")
        lay.addWidget(self.chk_remember)

        # ---- Browse + Save/Cancel ----
        btns = QHBoxLayout()
        btn_browse = QPushButton("Browse...")
        btn_browse.setStyleSheet(
            "QPushButton{background:%s; color:%s; border:none; padding:6px 14px;"
            " border-radius:6px;}QPushButton:hover{background:%s;}"
            % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
        btn_browse.clicked.connect(self._browse)
        btns.addWidget(btn_browse)
        btns.addStretch(1)
        btn_save = QPushButton("Save")
        btn_save.setStyleSheet(
            "QPushButton{background:%s; color:%s; border:none; padding:6px 18px;"
            " border-radius:6px; font-weight:bold;}QPushButton:hover{background:%s;}"
            % (C_ACCENT, C_ACCENT_FG, C_ACCENT_HOV))
        btn_save.clicked.connect(self.accept)
        btn_cancel = QPushButton("Cancel")
        btn_cancel.setStyleSheet(
            "QPushButton{background:%s; color:%s; border:none; padding:6px 14px;"
            " border-radius:6px;}QPushButton:hover{background:%s;}"
            % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
        btn_cancel.clicked.connect(self.reject)
        btns.addWidget(btn_save)
        btns.addWidget(btn_cancel)
        lay.addLayout(btns)

        # Focus the NAME box and select its text, so typing replaces the name
        # right away. The extension box is deliberately left alone.
        self.ed_name.setFocus()
        self.ed_name.selectAll()

    def _set_dir(self, path):
        self._chosen_dir = path
        self.lbl_dir.setText(path)

    def _browse(self):
        d = QFileDialog.getExistingDirectory(self, "Choose save folder", self._chosen_dir)
        if d:
            self._set_dir(d)

    def chosen_path(self):
        """Return the full path (dir + filename) chosen by the user.

        The NAME box and the EXTENSION box are recombined here. An empty
        extension box just means no extension, and any stray leading dots the
        user typed into it are dropped so we never build 'name..ext'."""
        name = self.ed_name.text().strip()
        if not name:
            return ""
        ext = self.ed_ext.text().strip().lstrip(".")
        filename = name + ("." + ext if ext else "")
        return os.path.join(self._chosen_dir, filename)

    def always_download(self):
        """True if the user ticked 'Always download to this directory' -
        meaning both the folder AND Quick-download should be remembered, so
        this pop-up stops appearing for future downloads."""
        return self.chk_remember.isChecked()

    def chosen_dir(self):
        """The folder the user picked (without the filename)."""
        return self._chosen_dir

    def keyPressEvent(self, e):
        if e.key() == Qt.Key.Key_Escape:
            self.reject()
        elif e.key() in (Qt.Key.Key_Return, Qt.Key.Key_Enter):
            self.accept()
        else:
            super().keyPressEvent(e)


# ============================================================================
#  DEL 46 - "YOU ALREADY HAVE A FILE WITH THIS NAME"
# ----------------------------------------------------------------------------
#  Shown when a download would land on top of a file that is already in the
#  folder. Same three real choices File_manager offers on a copy clash, plus
#  "always do this", which stores the answer for this profile so the question
#  stops (Settings -> Downloads switches it back to asking).
#
#  TWO kinds of clash get here, and the second one is the point of DEL 46:
#    exact  - the incoming name is already taken
#    copy   - the incoming name is only a copy suffix away from one you have,
#             i.e. "WhyBrowse (3).py" arriving next to "WhyBrowse.py". Left to
#             itself the browser would keep stacking up numbered copies; here
#             it can hand you a clean WhyBrowse.py and keep the old one as
#             Backup<CODE>-WhyBrowse.py instead.
# ============================================================================
DUPE_ASK     = "ask"
DUPE_BACKUP  = "backup"
DUPE_SUFFIX  = "suffix"
DUPE_REPLACE = "replace"

DUPE_CHOICES = (
    (DUPE_ASK,     "Ask me each time  (recommended)"),
    (DUPE_BACKUP,  "Back up the old one, new file takes the clean name"),
    (DUPE_SUFFIX,  "Save with a number in brackets  \u2014  Foo (2).py"),
    (DUPE_REPLACE, "Overwrite the old one, no backup"),
)


def _file_facts(path):
    """'1.2 MB \u00b7 saved 2026-08-14 07:56' for a path, or '' if it is not there."""
    try:
        st = os.stat(path)
        size = st.st_size
        for unit in ("bytes", "KB", "MB", "GB"):
            if size < 1024 or unit == "GB":
                break
            size /= 1024.0
        shown = ("%d %s" % (size, unit)) if unit == "bytes" else ("%.1f %s" % (size, unit))
        return "%s  \u00b7  saved %s" % (
            shown, time.strftime("%Y-%m-%d %H:%M", time.localtime(st.st_mtime)))
    except Exception:
        return ""


class DuplicateDownloadDialog(QDialog):
    """Ask what to do about a name that is already taken. self.choice() is one
    of DUPE_BACKUP / DUPE_SUFFIX / DUPE_REPLACE once accepted."""

    def __init__(self, parent, directory, incoming, target, suffix_name):
        super().__init__(parent)
        self.setWindowTitle(APP_NAME + " - You already have this file")
        self.setModal(True)
        self.setStyleSheet(dialog_qss())
        apply_window_icon(self)
        self._choice = DUPE_BACKUP

        lay = QVBoxLayout(self)
        lay.setSpacing(9)

        # Every wrapping label in here gets a width ceiling. A QLabel with
        # word-wrap and no ceiling still asks the layout for the width of its
        # longest line FIRST and only wraps afterwards, so one long file path
        # is enough to open this dialog far wider than it needs to be.
        TEXT_W = 620

        head = QLabel("There is already a file called <b>%s</b> here." % target)
        head.setWordWrap(True)
        head.setMaximumWidth(TEXT_W)
        head.setStyleSheet("font-size:11pt;")
        lay.addWidget(head)

        where = QLabel(directory)
        where.setWordWrap(True)
        where.setMaximumWidth(TEXT_W)
        where.setStyleSheet("color:%s; font-size:9pt;" % C_ACCENT)
        lay.addWidget(where)

        facts = _file_facts(os.path.join(directory, target))
        if facts:
            lbl = QLabel("The file already there:  %s" % facts)
            lbl.setWordWrap(True)
            lbl.setMaximumWidth(TEXT_W)
            lbl.setStyleSheet("color:%s; font-size:9pt;" % C_STATUS_FG)
            lay.addWidget(lbl)

        if incoming != target:
            # The "copy suffix" case - say so plainly, because the browser is
            # about to treat two differently-named files as the same file.
            note = QLabel(
                "The download is called <b>%s</b>, which is the same name with a "
                "copy number on the end \u2014 so it is treated as another copy of "
                "<b>%s</b>." % (incoming, target))
            note.setWordWrap(True)
            note.setMaximumWidth(TEXT_W)
            note.setStyleSheet("color:%s; font-size:9pt;" % C_STATUS_FG)
            lay.addWidget(note)

        lay.addSpacing(4)

        grid = QGridLayout()
        grid.setHorizontalSpacing(10)
        grid.setVerticalSpacing(7)
        rows = (
            (DUPE_BACKUP,
             "\U0001f4be  Back up the old one",
             "Renames the old file to  Backup&lt;CODE&gt;-%s  and saves this one as "
             "<b>%s</b>. Nothing is lost and the name stays clean. (Same "
             "Backup&lt;CODE&gt;- convention, and the same code list, File_manager "
             "uses.)" % (target, target)),
            (DUPE_SUFFIX,
             "\U0001f522  Save with a number",
             "Keeps both, exactly as before: the new file is saved as "
             "<b>%s</b>." % suffix_name),
            (DUPE_REPLACE,
             "\u267b  Overwrite, no backup",
             "The old <b>%s</b> is thrown away and this one takes its place. The "
             "old file is only deleted once the download has actually finished \u2014 "
             "if it fails, the old one comes back." % target),
        )
        for r, (key, btn_text, caption) in enumerate(rows):
            b = QPushButton(btn_text)
            b.setMinimumWidth(210)
            accent = (key == DUPE_BACKUP)
            b.setStyleSheet(
                "QPushButton{background:%s; color:%s; border:none; padding:8px 14px;"
                " border-radius:6px; text-align:left; %s}"
                "QPushButton:hover{background:%s;}"
                % (C_ACCENT if accent else C_BTN_BG,
                   C_ACCENT_FG if accent else C_BTN_FG,
                   "font-weight:bold;" if accent else "",
                   C_ACCENT_HOV if accent else C_BTN_BG_HOV))
            b.clicked.connect(lambda _=False, k=key: self._pick(k))
            grid.addWidget(b, r, 0)
            cap = QLabel(caption)
            cap.setWordWrap(True)
            # Cap the width: a wrapped QLabel with no ceiling still asks for the
            # width of its longest line first, which is how a dialog like this
            # ends up wider than it has any need to be.
            cap.setMinimumWidth(300)
            cap.setMaximumWidth(TEXT_W - 200)
            cap.setStyleSheet("color:%s; font-size:9pt;" % C_STATUS_FG)
            grid.addWidget(cap, r, 1)
            if accent:
                self._default_btn = b
        grid.setColumnStretch(1, 1)
        lay.addLayout(grid)

        self.chk_always = QCheckBox(
            "Always do this from now on \u2014 stop asking  "
            "(Settings \u2192 Downloads turns the question back on)")
        self.chk_always.setMaximumWidth(TEXT_W)
        self.chk_always.setStyleSheet("font-size:9pt;")
        lay.addWidget(self.chk_always)

        row = QHBoxLayout()
        row.addStretch(1)
        btn_cancel = QPushButton("Cancel the download")
        btn_cancel.setStyleSheet(
            "QPushButton{background:%s; color:%s; border:none; padding:6px 14px;"
            " border-radius:6px;}QPushButton:hover{background:%s;}"
            % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
        btn_cancel.clicked.connect(self.reject)
        row.addWidget(btn_cancel)
        lay.addLayout(row)

        self.resize(660, 340)
        self.adjustSize()
        fit_to_screen(self)
        try:
            self._default_btn.setFocus()      # bare ENTER = back up the old one
        except Exception:
            pass

    def _pick(self, key):
        self._choice = key
        self.accept()

    def choice(self):
        return self._choice

    def always(self):
        return self.chk_always.isChecked()

    def keyPressEvent(self, e):
        if e.key() == Qt.Key.Key_Escape:
            self.reject()
        else:
            super().keyPressEvent(e)


# ============================================================================
#  DEL 14BK - BACKUP / RESTORE DIALOG
# ----------------------------------------------------------------------------
#  Creates a dated .zip of settings, bookmarks, history, vault files and the
#  full Chromium profile storage (cookies, logins, cache excluded).
#  Restore extracts a previously saved zip back into the same locations.
# ============================================================================
class BackupDialog(QDialog):
    """Backup and restore all WhyBrowse user data as a single .zip file."""

    def __init__(self, parent):
        super().__init__(parent)
        self.win = parent
        self.setWindowTitle(APP_NAME + " - Backup & Restore")
        self.setModal(True)
        self.resize(500, 420)
        self.setStyleSheet(dialog_qss())
        apply_window_icon(self)

        lay = QVBoxLayout(self)
        lay.setSpacing(10)

        # ---- What will be backed up ----
        info = QLabel(
            "<b>Backup includes:</b> settings, bookmarks, history, passwords (vault), "
            "profiles, snippets, userscripts, keyboard layouts, new-tab page and "
            "Chromium session data (cookies and saved passwords from web pages).<br>"
            "<b>Backup excludes:</b> browser cache (can be very large)."
        )
        info.setWordWrap(True)
        info.setStyleSheet("color:%s; font-size:9pt;" % C_BAR_FG)
        lay.addWidget(info)

        sep1 = QFrame(); sep1.setFrameShape(QFrame.Shape.HLine)
        sep1.setStyleSheet("color:%s;" % C_BORDER)
        lay.addWidget(sep1)

        # ---- BACKUP section ----
        lbl_bk = QLabel("Create backup")
        lbl_bk.setStyleSheet("font-weight:bold; color:%s; font-size:11pt;" % C_ACCENT)
        lay.addWidget(lbl_bk)

        row_dest = QHBoxLayout()
        self.ed_dest = QLineEdit()
        self.ed_dest.setPlaceholderText("Choose destination folder...")
        self.ed_dest.setText(os.path.expanduser("~"))
        row_dest.addWidget(self.ed_dest, 1)
        btn_browse = QPushButton("Browse\u2026")
        btn_browse.setStyleSheet(
            "QPushButton{background:%s;color:%s;border:none;padding:6px 12px;"
            "border-radius:6px;}QPushButton:hover{background:%s;}"
            % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
        btn_browse.clicked.connect(self._browse_dest)
        row_dest.addWidget(btn_browse)
        lay.addLayout(row_dest)

        self.lbl_zip_name = QLabel()
        self.lbl_zip_name.setStyleSheet("color:%s; font-size:8pt;" % C_STATUS_FG)
        lay.addWidget(self.lbl_zip_name)
        self._refresh_zip_name()
        self.ed_dest.textChanged.connect(lambda _: self._refresh_zip_name())

        btn_backup = QPushButton("\U0001f4be  Create backup now")
        btn_backup.setStyleSheet(
            "QPushButton{background:%s;color:%s;border:none;padding:8px 18px;"
            "border-radius:6px;font-weight:bold;}QPushButton:hover{background:%s;}"
            % (C_ACCENT, C_ACCENT_FG, C_ACCENT_HOV))
        btn_backup.clicked.connect(self._do_backup)
        lay.addWidget(btn_backup)

        self.lbl_backup_status = QLabel("")
        self.lbl_backup_status.setWordWrap(True)
        lay.addWidget(self.lbl_backup_status)

        sep2 = QFrame(); sep2.setFrameShape(QFrame.Shape.HLine)
        sep2.setStyleSheet("color:%s;" % C_BORDER)
        lay.addWidget(sep2)

        # ---- RESTORE section ----
        lbl_rs = QLabel("Restore from backup")
        lbl_rs.setStyleSheet("font-weight:bold; color:%s; font-size:11pt;" % C_ACCENT)
        lay.addWidget(lbl_rs)

        warn = QLabel(
            "\u26a0  Restoring will overwrite your current settings, bookmarks and passwords "
            "with those from the backup. The browser will close after restoring so the "
            "new data is loaded cleanly on next start."
        )
        warn.setWordWrap(True)
        warn.setStyleSheet("color:#e8a838; font-size:9pt;")
        lay.addWidget(warn)

        row_src = QHBoxLayout()
        self.ed_src = QLineEdit()
        self.ed_src.setPlaceholderText("Choose a WhyBrowse backup .zip file\u2026")
        row_src.addWidget(self.ed_src, 1)
        btn_src = QPushButton("Browse\u2026")
        btn_src.setStyleSheet(
            "QPushButton{background:%s;color:%s;border:none;padding:6px 12px;"
            "border-radius:6px;}QPushButton:hover{background:%s;}"
            % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
        btn_src.clicked.connect(self._browse_src)
        row_src.addWidget(btn_src)
        lay.addLayout(row_src)

        btn_restore = QPushButton("\u267b  Restore backup\u2026")
        btn_restore.setStyleSheet(
            "QPushButton{background:%s;color:%s;border:none;padding:8px 18px;"
            "border-radius:6px;font-weight:bold;}QPushButton:hover{background:%s;}"
            % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
        btn_restore.clicked.connect(self._do_restore)
        lay.addWidget(btn_restore)

        self.lbl_restore_status = QLabel("")
        self.lbl_restore_status.setWordWrap(True)
        lay.addWidget(self.lbl_restore_status)

        lay.addStretch(1)

        btn_close = QPushButton("Close")
        btn_close.setStyleSheet(
            "QPushButton{background:%s;color:%s;border:none;padding:7px 20px;"
            "border-radius:6px;}QPushButton:hover{background:%s;}"
            % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
        btn_close.clicked.connect(self.reject)
        row_cl = QHBoxLayout()
        row_cl.addStretch(1)
        row_cl.addWidget(btn_close)
        lay.addLayout(row_cl)

    # ------------------------------------------------------------------ helpers
    def _refresh_zip_name(self):
        stamp = time.strftime("%Y-%m-%d_%H-%M")
        dest  = self.ed_dest.text().strip() or os.path.expanduser("~")
        name  = "WhyBrowse_backup_%s.zip" % stamp
        self.lbl_zip_name.setText("File: %s" % os.path.join(dest, name))
        self._zip_name = name

    def _browse_dest(self):
        d = QFileDialog.getExistingDirectory(
            self, "Choose backup destination folder",
            self.ed_dest.text() or os.path.expanduser("~"))
        if d:
            self.ed_dest.setText(d)

    def _browse_src(self):
        path, _ = QFileDialog.getOpenFileName(
            self, "Open WhyBrowse backup",
            os.path.expanduser("~"),
            "Zip files (*.zip)")
        if path:
            self.ed_src.setText(path)

    def _status(self, label, text, color=None):
        label.setText(text)
        label.setStyleSheet("color:%s; font-size:9pt;" % (color or C_BAR_FG))
        QApplication.processEvents()

    # ------------------------------------------------------------------ backup
    def _collect_backup_paths(self):
        """Return list of (abs_path, arcname) tuples to put in the zip."""
        pairs = []

        def add_file(path, arc):
            if os.path.isfile(path):
                pairs.append((path, arc))

        def add_dir(path, arc_prefix):
            if not os.path.isdir(path):
                return
            for root, dirs, files in os.walk(path):
                # Skip Chromium cache dirs to keep the zip small
                dirs[:] = [d for d in dirs
                           if d.lower() not in ("cache", "gpucache", "code cache",
                                                 "shader_cache", "storage",
                                                 "service worker", "blob_storage")]
                for fname in files:
                    full = os.path.join(root, fname)
                    rel  = os.path.relpath(full, os.path.dirname(path))
                    pairs.append((full, os.path.join(arc_prefix, rel)))

        # Global files
        add_file(SETTINGS_FILE,    "settings.json")
        add_file(BOOKMARKS_FILE,   "bookmarks.json")
        add_file(HISTORY_FILE,     "history.json")
        add_file(SHARED_BOOKMARKS, "bookmarks_shared.json")
        add_file(FAVOURITES_FILE,  "favourites.json")
        add_file(NEWTAB_FILE,      "newtab.html")
        add_file(WATCH_CACHE_FILE, "watch_cache.json")
        add_file(SCROLL_POS_FILE,  "scroll_positions.json")

        # Default profile vault
        vault_default = os.path.join(DATA_DIR, "vault.dat")
        add_file(vault_default, "vault.dat")

        # Default profile Chromium storage (cookies, logins etc.)
        add_dir(PROFILE_DIR, "profile")

        # Per-profile dirs (all of them)
        if os.path.isdir(PROFILES_DIR):
            for pid_dir in os.listdir(PROFILES_DIR):
                full_pid = os.path.join(PROFILES_DIR, pid_dir)
                if os.path.isdir(full_pid):
                    add_dir(full_pid, os.path.join("profiles", pid_dir))

        # Userscripts and keyboard layouts
        add_dir(USERSCRIPTS_DIR,  "userscripts")
        add_dir(KBD_LAYOUTS_DIR,  "keyboard_layouts")

        return pairs

    def _do_backup(self):
        import zipfile
        self._refresh_zip_name()
        dest_dir = self.ed_dest.text().strip()
        if not dest_dir:
            self._status(self.lbl_backup_status,
                         "Please choose a destination folder.", "#e84040")
            return
        os.makedirs(dest_dir, exist_ok=True)
        zip_path = os.path.join(dest_dir, self._zip_name)

        self._status(self.lbl_backup_status, "Collecting files\u2026", C_STATUS_FG)
        try:
            pairs = self._collect_backup_paths()
            self._status(self.lbl_backup_status,
                         "Writing %d files to zip\u2026" % len(pairs), C_STATUS_FG)
            import zipfile as zfmod
            with zfmod.ZipFile(zip_path, "w", zfmod.ZIP_DEFLATED,
                               compresslevel=6) as zf:
                for src, arc in pairs:
                    try:
                        zf.write(src, arc)
                    except Exception as e:
                        log_line("backup: skipped %s: %s" % (src, e))
            size_mb = os.path.getsize(zip_path) / (1024 * 1024)
            self._status(
                self.lbl_backup_status,
                "\u2705  Backup saved (%.1f MB):\n%s" % (size_mb, zip_path),
                "#1f8a4c")
            log_line("Backup created: %s (%.1f MB)" % (zip_path, size_mb))
        except Exception as e:
            self._status(self.lbl_backup_status,
                         "\u274c  Backup failed: %s" % e, "#e84040")
            log_line("Backup failed: %s" % e)

    # ----------------------------------------------------------------- restore
    def _do_restore(self):
        import zipfile as zfmod
        src_path = self.ed_src.text().strip()
        if not src_path or not os.path.isfile(src_path):
            self._status(self.lbl_restore_status,
                         "Please choose a backup .zip file first.", "#e84040")
            return

        # Quick sanity check
        try:
            with zfmod.ZipFile(src_path, "r") as zf:
                names = zf.namelist()
        except Exception as e:
            self._status(self.lbl_restore_status,
                         "\u274c  Cannot read zip: %s" % e, "#e84040")
            return
        if "settings.json" not in names:
            self._status(self.lbl_restore_status,
                         "\u274c  This does not look like a WhyBrowse backup "
                         "(settings.json not found).", "#e84040")
            return

        ans = QMessageBox.question(
            self, "Restore backup",
            "Restore from:\n%s\n\n"
            "This will overwrite your current settings, bookmarks and vault.\n"
            "The browser will close afterwards so the data loads cleanly.\n\n"
            "Continue?" % src_path,
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.Cancel)
        if ans != QMessageBox.StandardButton.Yes:
            return

        self._status(self.lbl_restore_status, "Restoring\u2026", C_STATUS_FG)
        try:
            mapping = {
                "profile":           PROFILE_DIR,
                "profiles":          PROFILES_DIR,
                "userscripts":       USERSCRIPTS_DIR,
                "keyboard_layouts":  KBD_LAYOUTS_DIR,
            }
            root_files = {
                "settings.json", "bookmarks.json", "history.json",
                "bookmarks_shared.json", "favourites.json", "newtab.html",
                "watch_cache.json", "vault.dat",
            }
            with zfmod.ZipFile(src_path, "r") as zf:
                for member in zf.infolist():
                    name = member.filename
                    if name.endswith("/"):
                        continue
                    parts = name.replace("\\", "/").split("/")
                    if parts[0] in root_files or name in root_files:
                        out = os.path.join(DATA_DIR, parts[0])
                    else:
                        out = None
                        for prefix, real_dir in mapping.items():
                            if parts[0] == prefix:
                                rest = "/".join(parts[1:])
                                out  = os.path.join(real_dir, rest)
                                break
                        if out is None:
                            continue
                    os.makedirs(os.path.dirname(out), exist_ok=True)
                    with zf.open(member) as src_f, open(out, "wb") as dst_f:
                        dst_f.write(src_f.read())

            log_line("Restore completed from: %s" % src_path)
            QMessageBox.information(
                self, "Restore complete",
                "Restore finished successfully.\n\n"
                "WhyBrowse will now close. Please restart it to use the restored data.")
            self.win.close()

        except Exception as e:
            self._status(self.lbl_restore_status,
                         "\u274c  Restore failed: %s" % e, "#e84040")
            log_line("Restore failed: %s" % e)

    def keyPressEvent(self, e):
        if e.key() == Qt.Key.Key_Escape:
            self.reject()
        else:
            super().keyPressEvent(e)


# ============================================================================
#  DEL 14C - PROFILE EDIT DIALOG  (name, color, badge, shared bookmarks; ESC closes)
# ============================================================================
class ProfileEditDialog(QDialog):
    def __init__(self, parent, profile, is_new=False):
        super().__init__(parent)
        self._p = dict(profile)
        self.setWindowTitle(APP_NAME + (" - New profile" if is_new else " - Edit profile"))
        self.setModal(True)
        self.resize(420, 340)
        self.setStyleSheet(dialog_qss())
        apply_window_icon(self)

        # Outer layout: scroll area fills the dialog, OK/Cancel pinned at bottom.
        outer = QVBoxLayout(self)
        outer.setContentsMargins(0, 0, 0, 8)
        outer.setSpacing(0)

        scroll = QScrollArea()
        scroll.setWidgetResizable(True)
        scroll.setFrameShape(QFrame.Shape.NoFrame)
        scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        scroll.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
        inner = QWidget()
        lay = QVBoxLayout(inner)
        lay.setSpacing(8)
        lay.setContentsMargins(12, 10, 12, 4)
        scroll.setWidget(inner)
        outer.addWidget(scroll, 1)

        # ---- Show existing profiles when creating a new one ----
        if is_new:
            existing = []
            try:
                existing = parent.settings.get("profiles", [])
            except Exception:
                pass
            if existing:
                lbl_ex = QLabel("Existing profiles:")
                lbl_ex.setStyleSheet("font-weight:bold;")
                lay.addWidget(lbl_ex)
                lst_ex = QListWidget()
                lst_ex.setFixedHeight(min(28 * len(existing) + 10, 110))
                lst_ex.setSelectionMode(QAbstractItemView.SelectionMode.NoSelection)
                lst_ex.setFocusPolicy(Qt.FocusPolicy.NoFocus)
                active_id = getattr(parent, "active_id", None)
                for p in existing:
                    badge = p.get("badge", "?")
                    name  = p.get("name", p.get("id", "?"))
                    color = p.get("color", "#7c5cff")
                    marker = "  ◀ active" if p.get("id") == active_id else ""
                    item = QListWidgetItem("  %s  %s%s" % (badge, name, marker))
                    item.setForeground(QColor(color))
                    lst_ex.addItem(item)
                lay.addWidget(lst_ex)

                sep = QFrame()
                sep.setFrameShape(QFrame.Shape.HLine)
                sep.setStyleSheet("color:%s;" % C_BORDER)
                lay.addWidget(sep)

        lay.addWidget(QLabel("Profile name (e.g. your email):"))
        self.ed_name = QLineEdit(self._p.get("name", ""))
        self.ed_name.setPlaceholderText("issusbarn")
        lay.addWidget(self.ed_name)

        row = QHBoxLayout()
        row.addWidget(QLabel("Badge (one letter or number, shown before the address):"))
        self.ed_badge = QLineEdit(str(self._p.get("badge", "1"))[:1])
        self.ed_badge.setMaxLength(1)
        self.ed_badge.setFixedWidth(44)
        row.addWidget(self.ed_badge)
        lay.addLayout(row)

        rowc = QHBoxLayout()
        rowc.addWidget(QLabel("Color:"))
        self._color = self._p.get("color", "#7c5cff")
        self.btn_color = QPushButton("  Pick color  ")
        self.btn_color.clicked.connect(self._pick_color)
        rowc.addWidget(self.btn_color)
        self.swatch = QLabel()
        self.swatch.setFixedSize(40, 24)
        rowc.addWidget(self.swatch)
        rowc.addStretch(1)
        lay.addLayout(rowc)
        self._paint_swatch()

        self.chk_shared = QCheckBox("Use shared bookmarks (same bar/menu as other shared profiles)")
        self.chk_shared.setChecked(bool(self._p.get("shared_bookmarks", False)))
        lay.addWidget(self.chk_shared)

        # ---- What shows in the bookmarks bar (the profile tag) ----
        self.chk_tag = QCheckBox("Show the profile tag in the bookmarks bar")
        self.chk_tag.setChecked(self._p.get("show_tag", True))
        lay.addWidget(self.chk_tag)

        lay.addWidget(QLabel("Bookmark-bar tag text (what the tag shows):"))
        self.ed_barlabel = QLineEdit(self._p.get("bar_label", "") or self._p.get("name", ""))
        self.ed_barlabel.setPlaceholderText("leave empty to use the profile name")
        lay.addWidget(self.ed_barlabel)

        lay.addWidget(QLabel("Login to type when you click the tag (e.g. your e-mail):"))
        self.ed_login = QLineEdit(self._p.get("login", "") or self._p.get("name", ""))
        lay.addWidget(self.ed_login)

        # ---- Auto-login: one password per profile (username = the login above) ----
        lay.addWidget(QLabel("Password for auto-login (this profile's single login). "
                             "Edit it here to change it; clear it to remove it:"))
        # Pre-fill the saved password (decrypted) so you can SEE / edit / clear it.
        _saved_pw = ""
        if self._p.get("pw_enc"):
            try:
                import base64
                _saved_pw = _dpapi(base64.b64decode(self._p["pw_enc"]), False).decode("utf-8")
            except Exception:
                _saved_pw = ""
        row_pw = QHBoxLayout()
        self.ed_password = QLineEdit(_saved_pw)
        self.ed_password.setEchoMode(QLineEdit.EchoMode.Password)
        self.ed_password.setPlaceholderText("type the password")
        self._pw_had_saved = bool(self._p.get("pw_enc"))
        row_pw.addWidget(self.ed_password, 1)
        self.chk_showpw = QCheckBox("Show")
        self.chk_showpw.toggled.connect(
            lambda on: self.ed_password.setEchoMode(
                QLineEdit.EchoMode.Normal if on else QLineEdit.EchoMode.Password))
        row_pw.addWidget(self.chk_showpw)
        lay.addLayout(row_pw)
        self.chk_autologin = QCheckBox(
            "Auto-fill this login on sign-in pages (when a session has expired)")
        self.chk_autologin.setChecked(bool(self._p.get("autologin")))
        lay.addWidget(self.chk_autologin)
        self.chk_autosubmit = QCheckBox(
            "…and press the sign-in button automatically (skip if a site has 2FA)")
        self.chk_autosubmit.setChecked(bool(self._p.get("autologin_submit")))
        lay.addWidget(self.chk_autosubmit)
        _pw_hint = QLabel("Stored encrypted to your Windows account (DPAPI). Works for "
                          "normal e-mail+password forms; Google's multi-step + 2FA still "
                          "need you. Cookies usually keep you signed in anyway.")
        _pw_hint.setWordWrap(True)
        _pw_hint.setStyleSheet("color:%s; font-size:8pt;" % C_STATUS_FG)
        lay.addWidget(_pw_hint)

        # When creating a new profile, keep login in sync with profile name
        # until the user edits it manually.
        if is_new:
            self._login_synced = True
            def _sync_login(text):
                if self._login_synced:
                    self.ed_login.setText(text)
            def _unsync_login():
                self._login_synced = False
            self.ed_name.textChanged.connect(_sync_login)
            self.ed_login.textEdited.connect(lambda _: _unsync_login())

        lay.addWidget(QLabel("Home tab URL (go here when closing another tab — leave empty to use default behaviour):"))
        self.ed_home_tab = QLineEdit(self._p.get("home_tab", ""))
        self.ed_home_tab.setPlaceholderText("e.g. https://www.google.com")
        lay.addWidget(self.ed_home_tab)

        # ---- Which tab to land on when switching to this profile ----
        _fixed = self._p.get("fixed_start_tab")
        self.chk_fixed_tab = QCheckBox(
            "Always switch to a specific tab number for this profile "
            "(otherwise WhyBrowse returns you to whichever tab you were last on)")
        self.chk_fixed_tab.setChecked(_fixed is not None)
        lay.addWidget(self.chk_fixed_tab)
        row_fixed = QHBoxLayout()
        row_fixed.addWidget(QLabel("Tab number:"))
        self.sp_fixed_tab = QSpinBox()
        self.sp_fixed_tab.setRange(1, 50)
        self.sp_fixed_tab.setValue((_fixed if isinstance(_fixed, int) else 0) + 1)
        self.sp_fixed_tab.setEnabled(_fixed is not None)
        row_fixed.addWidget(self.sp_fixed_tab)
        row_fixed.addStretch(1)
        lay.addLayout(row_fixed)
        self.chk_fixed_tab.toggled.connect(self.sp_fixed_tab.setEnabled)

        # ---- Messaging profile (no e-mail needed; cross-profile notifications) ----
        self.chk_messaging = QCheckBox(
            "Messaging profile — pop a notification beside the window when its "
            "chat tabs get a new message, even from another profile")
        self.chk_messaging.setChecked(bool(self._p.get("messaging", False)))
        lay.addWidget(self.chk_messaging)
        msg_hint = QLabel(
            "Tip: make a profile (no login needed), pin web.whatsapp.com / "
            "messenger.com / messages.google.com/web, and keep \"Keep other "
            "profiles' tabs loaded\" ON in Settings so notifications arrive while "
            "you work in another profile.")
        msg_hint.setWordWrap(True)
        msg_hint.setStyleSheet("color:%s; font-size:8pt;" % C_STATUS_FG)
        lay.addWidget(msg_hint)

        # ---- Per-profile bookmarks-bar colours (empty = use the global colour) ----
        self._bar_bg = self._p.get("bar_bg") or None
        self._bar_fg = self._p.get("bar_fg") or None
        rowb = QHBoxLayout()
        rowb.addWidget(QLabel("Bookmarks bar (this profile):"))
        self.btn_barbg = QPushButton("Background...")
        self.btn_barbg.clicked.connect(lambda: self._pick_bar("_bar_bg", self.btn_barbg))
        self.btn_barfg = QPushButton("Text...")
        self.btn_barfg.clicked.connect(lambda: self._pick_bar("_bar_fg", self.btn_barfg))
        self.btn_barreset = QPushButton("Use global")
        self.btn_barreset.clicked.connect(self._reset_bar_colors)
        for b in (self.btn_barbg, self.btn_barfg, self.btn_barreset):
            b.setStyleSheet("QPushButton{background:%s; color:%s; border:none; padding:5px 10px; "
                            "border-radius:6px;}QPushButton:hover{background:%s;}"
                            % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
            rowb.addWidget(b)
        lay.addLayout(rowb)
        self._paint_bar_buttons()

        note = QLabel("Clicking the tag types this login into the web field you last "
                      "clicked. Full password autofill comes with the vault (next build).")
        note.setWordWrap(True)
        note.setStyleSheet("color:#9aa6bf; font-style:italic; font-size:9pt;")
        lay.addWidget(note)

        # ---- Per-profile save directories ----
        lay.addWidget(QLabel("Default save folder for downloads (this profile):"))
        row_sd = QHBoxLayout()
        self.ed_save_dir = QLineEdit(self._p.get("save_dir", ""))
        self.ed_save_dir.setPlaceholderText("leave empty to use ~/Downloads")
        row_sd.addWidget(self.ed_save_dir, 1)
        btn_sd = QPushButton("Browse...")
        btn_sd.setStyleSheet("QPushButton{background:%s; color:%s; border:none; padding:5px 10px;"
                             " border-radius:6px;}QPushButton:hover{background:%s;}"
                             % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
        btn_sd.clicked.connect(self._browse_save_dir)
        row_sd.addWidget(btn_sd)
        lay.addLayout(row_sd)

        lay.addWidget(QLabel("Often-used save folders (quick-pick buttons in the Save pop-up "
                             "and in the right-click \"Download to temp directory\" menu; up to 20):"))
        self._save_dirs = list(self._p.get("save_dirs", []))   # [{"name", "path"}, ...]
        self.lst_dirs = QListWidget()
        self.lst_dirs.setFixedHeight(80)
        self._refresh_dirs_list()
        lay.addWidget(self.lst_dirs)
        row_dirs = QHBoxLayout()
        for lbl, fn in (("Add...", self._add_save_dir),
                        ("Edit...", self._edit_save_dir),
                        ("Remove", self._remove_save_dir)):
            b = QPushButton(lbl)
            b.setStyleSheet("QPushButton{background:%s; color:%s; border:none; padding:5px 10px;"
                            " border-radius:6px;}QPushButton:hover{background:%s;}"
                            % (C_BTN_BG, C_BTN_FG, C_BTN_BG_HOV))
            b.clicked.connect(fn)
            row_dirs.addWidget(b)
        row_dirs.addStretch(1)
        lay.addLayout(row_dirs)

        lay.addStretch(1)

        # OK / Cancel sit OUTSIDE the scroll area so they are always visible
        # even when the dialog window is too short to show all content.
        sep2 = QFrame()
        sep2.setFrameShape(QFrame.Shape.HLine)
        sep2.setStyleSheet("color:%s;" % C_BORDER)
        outer.addWidget(sep2)
        btns = QHBoxLayout()
        btns.setContentsMargins(12, 4, 12, 0)
        btns.addStretch(1)
        for txt, fn, col in (("Save", self.accept, C_ACCENT), ("Cancel", self.reject, C_BTN_BG)):
            b = QPushButton(txt)
            fg = C_ACCENT_FG if col == C_ACCENT else C_BTN_FG
            b.setStyleSheet(
                "QPushButton{background:%s; color:%s; border:none; padding:7px 20px; "
                "border-radius:6px; font-weight:bold;}QPushButton:hover{background:%s;}"
                % (col, fg, C_BTN_BG_HOV))
            b.clicked.connect(fn)
            btns.addWidget(b)
        outer.addLayout(btns)

    def _paint_swatch(self):
        self.swatch.setStyleSheet("background:%s; border:1px solid #39456a; "
                                  "border-radius:4px;" % self._color)
        self.btn_color.setStyleSheet(
            "QPushButton{background:%s; color:%s; border:none; padding:6px 14px; "
            "border-radius:6px;}" % (C_BTN_BG, C_BTN_FG))

    def _pick_color(self):
        col = QColorDialog.getColor(parent=self, title="Profile color")
        if col.isValid():
            self._color = col.name()
            self._paint_swatch()

    def _pick_bar(self, attr, button):
        col = QColorDialog.getColor(parent=self, title="Bookmarks bar colour")
        if col.isValid():
            setattr(self, attr, col.name())
            self._paint_bar_buttons()

    def _reset_bar_colors(self):
        self._bar_bg = None
        self._bar_fg = None
        self._paint_bar_buttons()

    def _paint_bar_buttons(self):
        if self._bar_bg:
            self.btn_barbg.setStyleSheet(
                "QPushButton{background:%s; color:%s; border:1px solid #39456a; "
                "padding:5px 10px; border-radius:6px;}" % (self._bar_bg, contrast_fg(self._bar_bg)))
        if self._bar_fg:
            self.btn_barfg.setStyleSheet(
                "QPushButton{background:%s; color:%s; border:1px solid #39456a; "
                "padding:5px 10px; border-radius:6px;}"
                % (self._bar_bg or "#2b344b", self._bar_fg))

    def result_profile(self):
        self._p["name"] = self.ed_name.text().strip() or self._p.get("name", "Profile")
        self._p["badge"] = (self.ed_badge.text().strip() or self._p["name"][:1] or "?")[:1]
        self._p["color"] = self._color
        self._p["shared_bookmarks"] = self.chk_shared.isChecked()
        self._p["show_tag"] = self.chk_tag.isChecked()
        self._p["bar_label"] = self.ed_barlabel.text().strip()
        self._p["login"] = self.ed_login.text().strip()
        self._p["messaging"] = self.chk_messaging.isChecked()
        # Auto-login password (DPAPI-encrypted). The field is pre-filled with the
        # saved one, so: non-empty = (re)save it; empty = the user cleared it = remove.
        pw = self.ed_password.text()
        if pw:
            import base64
            try:
                self._p["pw_enc"] = base64.b64encode(
                    _dpapi(pw.encode("utf-8"), True)).decode("ascii")
            except Exception as e:
                log_line("profile pw encrypt error: %s" % e)
        elif getattr(self, "_pw_had_saved", False):
            self._p.pop("pw_enc", None)        # cleared on purpose
        self._p["autologin"] = self.chk_autologin.isChecked()
        self._p["autologin_submit"] = self.chk_autosubmit.isChecked()
        ht = self.ed_home_tab.text().strip()
        if ht:
            self._p["home_tab"] = ht
        else:
            self._p.pop("home_tab", None)
        if self.chk_fixed_tab.isChecked():
            self._p["fixed_start_tab"] = self.sp_fixed_tab.value() - 1   # store 0-based
        else:
            self._p.pop("fixed_start_tab", None)
        if self._bar_bg:
            self._p["bar_bg"] = self._bar_bg
        else:
            self._p.pop("bar_bg", None)
        if self._bar_fg:
            self._p["bar_fg"] = self._bar_fg
        else:
            self._p.pop("bar_fg", None)
        sd = self.ed_save_dir.text().strip()
        if sd:
            self._p["save_dir"] = sd
        else:
            self._p.pop("save_dir", None)
        self._p["save_dirs"] = list(self._save_dirs)
        self._p.setdefault("enabled", True)
        self._p.setdefault("last_tabs", [])
        return self._p

    # ---- save-folder helpers ----
    def _browse_save_dir(self):
        d = QFileDialog.getExistingDirectory(self, "Default save folder",
                                             self.ed_save_dir.text() or os.path.expanduser("~"))
        if d:
            self.ed_save_dir.setText(d)

    def _refresh_dirs_list(self):
        self.lst_dirs.clear()
        for entry in self._save_dirs:
            self.lst_dirs.addItem("%s  —  %s" % (entry["name"], entry["path"]))

    def _add_save_dir(self):
        if len(self._save_dirs) >= 20:
            QMessageBox.information(self, "Limit reached",
                                    "You can keep up to 20 favorite folders. "
                                    "Remove one first if you want to add another.")
            return
        d = QFileDialog.getExistingDirectory(self, "Choose folder", os.path.expanduser("~"))
        if not d:
            return
        name, ok = QInputDialog.getText(self, "Folder label",
                                        "Short name for this folder:",
                                        text=os.path.basename(d) or d)
        if ok and name.strip():
            self._save_dirs.append({"name": name.strip(), "path": d})
            self._refresh_dirs_list()

    def _edit_save_dir(self):
        row = self.lst_dirs.currentRow()
        if row < 0 or row >= len(self._save_dirs):
            return
        entry = self._save_dirs[row]
        d = QFileDialog.getExistingDirectory(self, "Choose folder", entry["path"])
        if d:
            entry["path"] = d
        name, ok = QInputDialog.getText(self, "Folder label",
                                        "Short name for this folder:",
                                        text=entry["name"])
        if ok and name.strip():
            entry["name"] = name.strip()
        self._refresh_dirs_list()

    def _remove_save_dir(self):
        row = self.lst_dirs.currentRow()
        if 0 <= row < len(self._save_dirs):
            del self._save_dirs[row]
            self._refresh_dirs_list()

    def keyPressEvent(self, e):
        if e.key() == Qt.Key.Key_Escape:
            self.reject()
        else:
            super().keyPressEvent(e)




# ---- Asking for the password -----------------------------------------------

class PasswordDialog(QDialog):
    """Modal password box. .value is '' when it was cancelled.

    When confirm is on it asks twice and refuses a mismatch, because a
    mistyped passphrase on an export is not discovered until the day you
    actually need the file."""

    def __init__(self, parent, title, prompt, confirm=False, ok_text="Unlock",
                 note=""):
        super().__init__(parent)
        self.value = ""
        self.setWindowTitle(title)
        self.setMinimumWidth(520)
        lay = QVBoxLayout(self)
        lay.setContentsMargins(18, 16, 18, 14)
        lay.setSpacing(8)

        head = QLabel(title)
        head.setStyleSheet("font-size:13pt;font-weight:bold;")
        lay.addWidget(head)

        lbl = QLabel(prompt)
        lbl.setWordWrap(True)
        lay.addWidget(lbl)

        if note:
            n = QLabel(note)
            n.setWordWrap(True)
            n.setStyleSheet("color:#e08a2a;")
            lay.addWidget(n)

        self.ed1 = QLineEdit()
        self.ed1.setEchoMode(QLineEdit.EchoMode.Password)
        self.ed1.setPlaceholderText("Password")
        lay.addWidget(self.ed1)

        self.ed2 = None
        if confirm:
            self.ed2 = QLineEdit()
            self.ed2.setEchoMode(QLineEdit.EchoMode.Password)
            self.ed2.setPlaceholderText("The same again")
            lay.addWidget(self.ed2)

        self.cb_show = QCheckBox("Show what I am typing")
        self.cb_show.toggled.connect(self._toggle_echo)
        lay.addWidget(self.cb_show)

        self.lbl_err = QLabel("")
        self.lbl_err.setWordWrap(True)
        self.lbl_err.setStyleSheet("color:#e84040;")
        lay.addWidget(self.lbl_err)

        row = QHBoxLayout()
        row.addStretch(1)
        btn_cancel = QPushButton("Cancel")
        btn_cancel.clicked.connect(self.reject)
        row.addWidget(btn_cancel)
        btn_ok = QPushButton(ok_text)
        btn_ok.setDefault(True)
        btn_ok.clicked.connect(self._accept)
        row.addWidget(btn_ok)
        lay.addLayout(row)

        self.ed1.returnPressed.connect(self._accept)
        if self.ed2 is not None:
            self.ed2.returnPressed.connect(self._accept)
        self.ed1.setFocus()

    def _toggle_echo(self, on):
        mode = (QLineEdit.EchoMode.Normal if on
                else QLineEdit.EchoMode.Password)
        self.ed1.setEchoMode(mode)
        if self.ed2 is not None:
            self.ed2.setEchoMode(mode)

    def _accept(self):
        pw = self.ed1.text()
        if not pw:
            self.lbl_err.setText("Type a password first.")
            return
        if self.ed2 is not None:
            if pw != self.ed2.text():
                self.lbl_err.setText("The two do not match.")
                return
            if len(pw) < 8:
                self.lbl_err.setText(
                    "Use at least 8 characters - this is the only thing "
                    "standing between the file and whoever finds it.")
                return
        self.value = pw
        self.accept()

    def keyPressEvent(self, e):
        if e.key() == Qt.Key.Key_Escape:
            self.reject()
        else:
            super().keyPressEvent(e)


def ask_password(parent, title, prompt, confirm=False, ok_text="Unlock",
                 note=""):
    dlg = PasswordDialog(parent, title, prompt, confirm, ok_text, note)
    return dlg.value if dlg.exec() else ""


def travel_startup_unlock():
    """Ask for the master password before the browser window exists.

    Three tries, then WhyBrowse closes. There is no "carry on without it"
    branch on purpose: without the password there are no bookmarks and no
    vault, so there would be nothing to carry on with."""
    name = os.path.basename(_TRAVEL_PACK)
    for attempt in range(3):
        pw = ask_password(
            None, "WhyBrowse - travel copy",
            "This is a travel copy ({}).\n\n"
            "Type the master password to unlock your bookmarks and your "
            "password vault. Nothing is left on this computer: the browser "
            "starts with an empty profile and the whole working folder is "
            "deleted when you close it.".format(name),
            ok_text="Unlock",
            note=("Wrong password {} of 3.".format(attempt)) if attempt else "")
        if not pw:
            return False
        try:
            _travel_unlock(pw)
            return True
        except PackPassword:
            log_line("Travel unlock: wrong password (attempt {})".format(
                attempt + 1))
            continue
        except PackError as e:
            QMessageBox.critical(None, "WhyBrowse - travel copy", str(e))
            return False
        except Exception as e:
            log_line("Travel unlock failed: {}".format(e))
            QMessageBox.critical(
                None, "WhyBrowse - travel copy",
                "The travel copy could not be opened:\n\n{}".format(e))
            return False
    QMessageBox.critical(
        None, "WhyBrowse - travel copy",
        "That is three wrong passwords. Nothing has been unlocked.")
    return False


def _dir_size(path):
    total = 0
    try:
        for root, dirs, files in os.walk(path):
            dirs[:] = [d for d in dirs if d.lower() not in _PACK_SKIP_DIRS]
            for fn in files:
                try:
                    total += os.path.getsize(os.path.join(root, fn))
                except Exception:
                    pass
    except Exception:
        pass
    return total


def _mb(n):
    return "{:.0f} MB".format(n / (1024.0 * 1024.0)) if n else "empty"


class MoveDialog(QDialog):
    """Move to another computer - the two modes side by side, with the
    difference between them spelled out rather than implied."""

    def __init__(self, win):
        super().__init__(win)
        self.win = win
        self.setWindowTitle("Move to another computer")
        self.setMinimumWidth(660)
        lay = QVBoxLayout(self)
        lay.setContentsMargins(18, 16, 18, 14)
        lay.setSpacing(10)

        head = QLabel("Move to another computer")
        head.setStyleSheet("font-size:14pt;font-weight:bold;")
        lay.addWidget(head)

        self.status = QLabel("")
        self.status.setWordWrap(True)

        if _TRAVEL_MODE:
            lay.addLayout(self._travel_running_box())

        lay.addLayout(self._full_box())
        lay.addLayout(self._travel_box())
        lay.addWidget(self.status)

        row = QHBoxLayout()
        row.addStretch(1)
        btn = QPushButton("Close")
        btn.clicked.connect(self.reject)
        row.addWidget(btn)
        lay.addLayout(row)

    # -------------------------------------------------------------- helpers
    def _say(self, text, colour=""):
        self.status.setText(text)
        self.status.setStyleSheet("color:{};".format(colour or "#3aa76d"))
        QApplication.processEvents()

    def _section(self, title, blurb):
        box = QVBoxLayout()
        t = QLabel(title)
        t.setStyleSheet("font-size:11pt;font-weight:bold;")
        box.addWidget(t)
        b = QLabel(blurb)
        b.setWordWrap(True)
        b.setStyleSheet("color:#8a8fa8;")
        box.addWidget(b)
        return box

    # ------------------------------------------------------- travel running
    def _travel_running_box(self):
        box = self._section(
            "⛺  You are running a travel copy",
            "{} - bookmarks, favourites, settings and the vault are held in "
            "memory and written back into that one encrypted file. Nothing is "
            "left on this computer when you close the browser.".format(
                os.path.basename(_TRAVEL_PACK)))
        row = QHBoxLayout()
        b1 = QPushButton("Save now")
        b1.clicked.connect(lambda: (_travel_reseal(),
                                    self._say("Travel copy saved.")))
        row.addWidget(b1)
        b2 = QPushButton("Change master password...")
        b2.clicked.connect(self._change_pw)
        row.addWidget(b2)
        row.addStretch(1)
        box.addLayout(row)
        return box

    def _change_pw(self):
        pw = ask_password(
            self, "New master password",
            "Choose a new master password for this travel copy. It takes "
            "effect immediately.", confirm=True, ok_text="Change")
        if not pw:
            return
        try:
            _travel_change_password(pw)
            self._say("Master password changed.")
        except Exception as e:
            self._say("Could not change it: {}".format(e), "#e84040")

    # ------------------------------------------------------------ full move
    def _full_box(self):
        box = self._section(
            "\U0001f3e0  Full move - reinstalling Windows, or your own new computer",
            "Bookmarks, favourites, history, settings, userscripts, the "
            "password vault and the browser profiles themselves - cookies "
            "included, so you arrive still signed in. The Chromium caches are "
            "left behind: they are about 3 GB of the 3.5 GB on disk and "
            "rebuild themselves. Your vault is re-locked to the new machine as "
            "it lands, which is the point - a Windows reinstall gives you a "
            "new user account and kills the old lock.")

        self.cb_profiles = QCheckBox(
            "Include the browser profiles (cookies, logins, site data)")
        self.cb_profiles.setChecked(True)
        box.addWidget(self.cb_profiles)

        self.lbl_size = QLabel("Measuring...")
        self.lbl_size.setStyleSheet("color:#8a8fa8;")
        box.addWidget(self.lbl_size)
        QTimer.singleShot(50, self._measure)

        row = QHBoxLayout()
        b1 = QPushButton("Export everything...")
        b1.clicked.connect(self._do_full_export)
        row.addWidget(b1)
        b2 = QPushButton("Import a move file...")
        b2.clicked.connect(self._do_full_import)
        row.addWidget(b2)
        row.addStretch(1)
        box.addLayout(row)
        return box

    def _measure(self):
        n = _dir_size(PROFILE_DIR) + _dir_size(PROFILES_DIR)
        self.lbl_size.setText(
            "Profiles without the caches: about {}.".format(_mb(n)))

    def _do_full_export(self):
        path, _ = QFileDialog.getSaveFileName(
            self, "Save the full move as...",
            os.path.join(os.path.expanduser("~"),
                         "WhyBrowse_full_{}.wbpack".format(
                             time.strftime("%Y-%m-%d"))),
            "WhyBrowse full move (*.wbpack)")
        if not path:
            return
        pw = ask_password(
            self, "Passphrase for this move",
            "Choose a passphrase. You will type it once more on the other "
            "computer, and there is no way to recover it - write it down "
            "somewhere that is not the file itself.",
            confirm=True, ok_text="Create")
        if not pw:
            return
        try:
            self._say("Packing... this can take a few minutes.")
            stats = _full_export(
                path, pw, {"profiles": self.cb_profiles.isChecked()},
                progress=lambda n: self._say(
                    "Packing... {} files".format(n)))
            self._say("✅  Done - {} files, {}:\n{}".format(
                stats["files"], _mb(stats["bytes"]), path))
            QMessageBox.information(
                self, "Full move",
                "Written to:\n\n{}\n\n{} files, {}.\n\nOn the other computer: "
                "put WhyBrowse.py where you want it, start it, and use "
                "☰ menu ▸ Move to another computer ▸ Import.".format(
                    path, stats["files"], _mb(stats["bytes"])))
        except Exception as e:
            log_line("Full export failed: {}".format(e))
            self._say("Failed: {}".format(e), "#e84040")

    def _do_full_import(self):
        path, _ = QFileDialog.getOpenFileName(
            self, "Open a full move file", os.path.expanduser("~"),
            "WhyBrowse full move (*.wbpack)")
        if not path:
            return
        if QMessageBox.question(
                self, "Import a full move",
                "This replaces the bookmarks, settings, vault and browser "
                "profiles on THIS computer with the ones in the file.\n\n"
                "Close and restart WhyBrowse afterwards.\n\nContinue?"
        ) != QMessageBox.StandardButton.Yes:
            return
        pw = ask_password(
            self, "Passphrase for this file",
            "Type the passphrase this move file was created with.",
            ok_text="Import")
        if not pw:
            return
        try:
            self._say("Unpacking...")
            n = _full_import(path, pw,
                             progress=lambda d, t: self._say(
                                 "Unpacking... {} of {} files".format(d, t)))
            self._say("✅  Imported {} files.".format(n))
            QMessageBox.information(
                self, "Full move",
                "{} files imported.\n\nClose WhyBrowse and start it again to "
                "use them.".format(n))
        except PackPassword:
            self._say("Wrong passphrase - nothing was changed.", "#e84040")
        except Exception as e:
            log_line("Full import failed: {}".format(e))
            self._say("Failed: {}".format(e), "#e84040")

    # ---------------------------------------------------------- travel copy
    def _travel_box(self):
        box = self._section(
            "⛺  Travel copy - a computer that is not yours",
            "Bookmarks, favourites, settings, userscripts and the password "
            "vault. No cookies and no history. QtWebEngine stores its cookies "
            "as plain text, so anyone who can see the folder could lift your "
            "live sessions with a free SQLite viewer without ever starting "
            "WhyBrowse - a password box in front of the window would protect "
            "nothing. So they do not come along: you sign in by hand over "
            "there, and the profile is deleted when you close. Without the "
            "master password there are no bookmarks at all.")
        row = QHBoxLayout()
        b = QPushButton("Create a travel copy...")
        b.clicked.connect(self._do_travel)
        row.addWidget(b)
        row.addStretch(1)
        box.addLayout(row)
        return box

    def _do_travel(self):
        path, _ = QFileDialog.getSaveFileName(
            self, "Save the travel copy as...",
            os.path.join(os.path.expanduser("~"), "WhyBrowse" + _TRAVEL_SUFFIX),
            "WhyBrowse travel copy (*{})".format(_TRAVEL_SUFFIX))
        if not path:
            return
        # A .wbtrav next to this .py would make THIS installation start in
        # travel mode next time. Refuse, and say why.
        where = os.path.normcase(os.path.dirname(os.path.abspath(path)))
        if where in (os.path.normcase(BASE_DIR), os.path.normcase(DATA_DIR)):
            QMessageBox.warning(
                self, "Not in this folder",
                "Save the travel copy somewhere else - a USB stick, or any "
                "folder outside this program's own.\n\nA travel file sitting "
                "next to WhyBrowse.py would make THIS installation start as a "
                "travel copy the next time you open it.")
            return
        pw = ask_password(
            self, "Master password for the travel copy",
            "This is typed every time the travel copy is started. Without it "
            "the file is just noise - there is no recovery and no back door.",
            confirm=True, ok_text="Create")
        if not pw:
            return
        try:
            self._say("Packing...")
            n = _travel_export(path, password=pw)
            self._say("✅  Travel copy written ({} items).".format(n))
            QMessageBox.information(
                self, "Travel copy",
                "Written to:\n\n{}\n\nPut that file and WhyBrowse.py together "
                "in one folder on the other computer, then start the .py. It "
                "will ask for the master password.\n\nAnything you change over "
                "there - a new bookmark, a setting - goes back into that same "
                "file.".format(path))
        except Exception as e:
            log_line("Travel export failed: {}".format(e))
            self._say("Failed: {}".format(e), "#e84040")

    def keyPressEvent(self, e):
        if e.key() == Qt.Key.Key_Escape:
            self.reject()
        else:
            super().keyPressEvent(e)
# *************** DEL 57 - PHONE SYNC (the Android app "Issu's WhyBrowse") - THE CORE (no Qt, so it can be tested alone) *****************
# ToDo (2026-11-15): what is shared with the phone, and how.
#   Shared: PROFILES you mark "Show on the phone" (name, colour, badge - never logins, passwords or cookies), the BOOKMARKS you mark (a whole profile,
#   a folder, or single links), and your ADDRESS SHORTCUTS (y -> youtube.com). Nothing else; no history, no tabs, no pages.
#   The phone is subordinate: the PC decides what the phone shows. What the phone makes (bookmarks, a "Phone" profile, shortcuts) comes back here:
#   a profile made on the phone becomes an ordinary profile of its own (flag phone_origin), bookmarks added on the phone land in the profile they
#   were added to. A bookmark / shortcut the PHONE made and later deletes is deleted here too; one that came FROM here and is deleted on the phone is
#   only HIDDEN from the phone (state["hidden"] / settings["phone_kw_off"]) - the PC copy is never deleted by the phone.
#   Transport: a relay (relay\whybrowse_relay.py, any small server of your own) keeps the records; both sides keep complete copies and work offline.
#   A record is {k: "p"|"b"|"k", u: change time in ms, d: 1 = deleted, s: "p" made on the phone / "c" made on the PC, ...}; the newest u wins.
#   Pull first, then push, then pull again (our own pushes echo back and are skipped because their u is not newer than what is known).
SYNC_CODE_PREFIX = "ISSUSYNC1:"
PHONE_SYNC_FILE = os.path.join(DATA_DIR, "phone_sync.json")     # PRIVATE: holds the relay key
PHONE_RELAY_JSON = os.path.join(DATA_DIR, "relay.json")          # {"url": ..., "key": ...} written by relay\make_installer.py


def sync_code_make(url, key, app="whybrowse"):
    """The text that is copied to the phone: prefix + base64url of {"a": app, "u": address, "k": key}. It contains the key."""
    raw = json.dumps({"a": app, "u": url, "k": key}, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
    return SYNC_CODE_PREFIX + base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")


def sync_code_parse(text):
    """The reverse of sync_code_make; spaces / line breaks inside the code are ignored, text around it too. None when it is not a code."""
    t = re.sub(r"\s+", "", text or "")
    i = t.find(SYNC_CODE_PREFIX)
    if i < 0:
        return None
    m = re.match(r"[A-Za-z0-9_\-]+", t[i + len(SYNC_CODE_PREFIX):])
    if not m:
        return None
    body, d = m.group(0), None
    # text that follows the code (with its spaces removed) sticks to the end of it: shorten until what is left decodes to the JSON object
    for n in range(len(body), max(len(body) - 400, 15), -1):
        try:
            d = json.loads(base64.urlsafe_b64decode(body[:n] + "=" * (-n % 4)).decode("utf-8"))
            break
        except Exception:
            d = None
    if not isinstance(d, dict):
        return None
    url, key = str(d.get("u") or ""), str(d.get("k") or "")
    if not re.match(r"^https?://[^\s]+$", url) or len(key) < 8:
        return None
    return {"app": str(d.get("a") or ""), "url": url, "key": key}


def _sync_sha(text, n):
    return hashlib.sha1(text.encode("utf-8")).hexdigest()[:n]


def sync_rid_profile(pid):
    return "p_" + _sync_sha(pid, 16)


def sync_rid_keyword(kw):
    return "k_" + _sync_sha(kw, 16)


def sync_rid_bookmark(pid, area, path, url):
    """The same id on every device for the same link in the same place: profile, bar/menu, folder path, address."""
    return "b_" + _sync_sha(pid + "\n" + area + "\n" + "\x1f".join(path) + "\n" + url, 20)


def _sync_hash(rec):
    d = {k: v for k, v in rec.items() if k not in ("u", "q", "d", "id")}
    return _sync_sha(json.dumps(d, sort_keys=True, ensure_ascii=False, separators=(",", ":")), 16)


_SYNC_PID_RE = re.compile(r"^[A-Za-z0-9_\-]{1,40}$")
_SYNC_URL_RE = re.compile(r"^https?://[^\s]+$", re.I)


def phone_sync_post(url, key, since, recs, timeout=25):
    """One call of the relay. Raises on every problem; the caller shows the text."""
    body = json.dumps({"since": since, "recs": recs}, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
    req = urllib.request.Request(
        url.rstrip("/") + "/sync", data=body, method="POST",
        headers={"X-Sync-Key": key, "Content-Type": "application/json", "User-Agent": "WhyBrowse-sync/1"})
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            ans = json.loads(r.read().decode("utf-8"))
    except urllib.error.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 urllib.error.URLError as e:
        raise RuntimeError("could not reach the server (%s)" % (getattr(e, "reason", e),))
    if not isinstance(ans, dict) or "seq" not in ans:
        raise RuntimeError("the server's answer was not understood")
    return ans


class PhoneSyncCore:
    """settings = the browser's settings dict (profiles, address_keywords, marks); host = PhoneSyncHost (or a fake in tests);
    state = the dict saved in phone_sync.json (url, key, since, known, src, hidden, auto, last)."""

    def __init__(self, settings, host, state, now=None, role="pc"):
        self.role = role                 # "pc" = the real program; "phone" is only used by the tests to play the other side
        self.settings = settings
        self.host = host
        self.st = state
        for k, v in (("known", {}), ("src", {}), ("hidden", []), ("since", 0)):
            self.st.setdefault(k, v)
        self.now = now or (lambda: int(time.time() * 1000))

    # ---- what is shared right now (record id -> record, without u)
    def gather(self):
        out = {}
        hidden = set(self.st["hidden"])
        for p in self.settings.get("profiles", []):
            pid = str(p.get("id") or "")
            if not _SYNC_PID_RE.match(pid) or p.get("is_favourites") or pid == FAV_PROFILE_ID or not p.get("phone"):
                continue
            out[sync_rid_profile(pid)] = {"k": "p", "pid": pid, "n": str(p.get("name") or pid), "c": str(p.get("color") or "#7c5cff"),
                                          "b": str(p.get("badge") or "?")[:1], "o": "phone" if p.get("phone_origin") else "pc"}
            tree = self.host.tree(pid)
            if not isinstance(tree, dict):
                continue
            for area in ("bar", "menu"):
                self._walk(tree.get(area) or [], pid, area, [], bool(p.get("phone_all")), out, hidden)
        if self.settings.get("phone_kw_sync", True):
            off = set(self.settings.get("phone_kw_off") or [])
            for kw, url in (self.settings.get("address_keywords") or {}).items():
                if kw in off or not isinstance(url, str) or not _SYNC_URL_RE.match(url) or " " in kw:
                    continue
                out[sync_rid_keyword(kw)] = {"k": "k", "w": kw, "url": url}
        for rid, rec in out.items():
            rec["s"] = "p" if self.st["src"].get(rid) == "p" else "c"
        return out

    def _walk(self, nodes, pid, area, path, inherit, out, hidden):
        for n in nodes:
            if not isinstance(n, dict):
                continue
            if "folder" in n:
                self._walk(n.get("folder") or [], pid, area, path + [str(n.get("title") or "")], inherit or bool(n.get("phone")), out, hidden)
            elif (inherit or n.get("phone")) and isinstance(n.get("url"), str) and _SYNC_URL_RE.match(n["url"]):
                url = n["url"]
                rid = sync_rid_bookmark(pid, area, path, url)
                if rid in hidden:
                    continue
                # "x" = the place in the PC's list, so the phone shows folders and links in exactly this order
                out[rid] = {"k": "b", "p": pid, "a": area, "f": list(path), "t": str(n.get("title") or url), "url": url, "x": len(out)}

    # ---- what the other side sent
    def apply_remote(self, recs):
        stats = {"added": 0, "removed": 0, "shortcuts": 0, "profiles": 0}
        known = self.st["known"]
        order = {"p": 0, "k": 1, "b": 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, r, 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 _sync_hash(r), "u": u, "d": 1 if r.get("d") else 0}
        return stats

    def _find_profile(self, pid):
        for p in self.settings.get("profiles", []):
            if p.get("id") == pid:
                return p
        return None

    def _list(self, tree, area, path, create):
        lst = tree.setdefault(area, [])
        for name in path:
            nxt = None
            for n in lst:
                if isinstance(n, dict) and "folder" in n and (n.get("title") or "") == name:
                    nxt = n
                    break
            if nxt is None:
                if not create:
                    return None
                nxt = {"title": name, "folder": []}
                lst.append(nxt)
            lst = nxt.setdefault("folder", [])
        return lst

    def _apply_record(self, rid, kind, r, stats):
        if kind == "p":
            pid = str(r.get("pid") or "")
            if not _SYNC_PID_RE.match(pid):
                return True
            ex = self._find_profile(pid)
            if ex is None:
                self.host.add_profile({"id": pid, "name": str(r.get("n") or "Phone")[:60], "color": str(r.get("c") or "#7c5cff")[:9],
                                       "badge": str(r.get("b") or "P")[:1], "enabled": True, "shared_bookmarks": False, "last_tabs": [],
                                       "phone": True, "phone_all": True, "phone_origin": r.get("o") == "phone"})
                stats["profiles"] += 1
            elif ex.get("phone_origin") and r.get("o") == "phone":
                for key, val in (("name", str(r.get("n") or ex.get("name"))[:60]), ("color", str(r.get("c") or ex.get("color"))[:9]),
                                 ("badge", str(r.get("b") or ex.get("badge"))[:1])):
                    if ex.get(key) != val:
                        ex[key] = val
                        self.host.profiles_changed()
            return True
        if kind == "k":
            kw = str(r.get("w") or "").strip().lower()
            url = str(r.get("url") or "")
            if not kw or " " in kw or not _SYNC_URL_RE.match(url):
                return True
            kws = self.settings.setdefault("address_keywords", {})
            cur = kws.get(kw)
            if cur is not None and cur != url and rid not in self.st["known"]:
                return False                      # the PC already has this keyword for another site: the PC wins (it is pushed with a newer time)
            kws[kw] = url
            off = self.settings.get("phone_kw_off") or []
            if kw in off:
                self.settings["phone_kw_off"] = [x for x in off if x != kw]
            self.host.keywords_changed()
            stats["shortcuts"] += 1
            return True
        if kind == "b":
            pid, area, path = str(r.get("p") or ""), r.get("a"), r.get("f")
            url, title = str(r.get("url") or ""), str(r.get("t") or "")
            if (not _SYNC_PID_RE.match(pid) or area not in ("bar", "menu") or not isinstance(path, list)
                    or not all(isinstance(x, str) for x in path) or not _SYNC_URL_RE.match(url)):
                return True
            if self._find_profile(pid) is None:
                return True
            tree = self.host.tree(pid)
            if not isinstance(tree, dict):
                return True
            lst = self._list(tree, area, path, True)
            for n in lst:
                if isinstance(n, dict) and "folder" not in n and n.get("url") == url:
                    if title and n.get("title") != title:
                        n["title"] = title
                    n["phone"] = True
                    break
            else:
                lst.append({"title": title or url, "url": url, "phone": True})
                stats["added"] += 1
            if rid in self.st["hidden"]:
                self.st["hidden"] = [x for x in self.st["hidden"] if x != rid]
            self.host.tree_changed(pid)
            return True
        return True

    def _apply_delete(self, rid, kind, r, stats):
        mine = self.role == "phone" or self.st["src"].get(rid) == "p"    # made on the phone: the phone may delete it here too
        if self.role == "phone" and kind == "p":
            pid = str(r.get("pid") or "")
            for p in list(self.settings.get("profiles", [])):
                if sync_rid_profile(str(p.get("id"))) == rid:
                    self.settings["profiles"].remove(p)
            return
        if kind == "b":
            if not mine:
                if rid not in self.st["hidden"]:
                    self.st["hidden"].append(rid)
                return
            pid, area, path, url = str(r.get("p") or ""), r.get("a"), r.get("f"), str(r.get("url") or "")
            if not url:                                  # tombstones carry no details: find the node by its id
                self._remove_by_rid(rid, stats)
                return
            tree = self.host.tree(pid) if _SYNC_PID_RE.match(pid) else None
            if isinstance(tree, dict) and area in ("bar", "menu") and isinstance(path, list):
                lst = self._list(tree, area, path, False)
                if lst is not None:
                    keep = [n for n in lst if not (isinstance(n, dict) and "folder" not in n and n.get("url") == url)]
                    if len(keep) != len(lst):
                        lst[:] = keep
                        stats["removed"] += 1
                        self.host.tree_changed(pid)
        elif kind == "k":
            if not mine:
                return
            self._remove_kw_by_rid(rid, stats)

    def _remove_by_rid(self, rid, stats):
        """A tombstone has no address, so search the shared profiles for the link with this id."""
        for p in self.settings.get("profiles", []):
            pid = str(p.get("id") or "")
            if not p.get("phone") or not _SYNC_PID_RE.match(pid):
                continue
            tree = self.host.tree(pid)
            if not isinstance(tree, dict):
                continue
            for area in ("bar", "menu"):
                if self._strip(tree.get(area) or [], pid, area, [], rid):
                    stats["removed"] += 1
                    self.host.tree_changed(pid)
                    return

    def _strip(self, nodes, pid, area, path, rid):
        for n in list(nodes):
            if not isinstance(n, dict):
                continue
            if "folder" in n:
                if self._strip(n.get("folder") or [], pid, area, path + [str(n.get("title") or "")], rid):
                    return True
            elif isinstance(n.get("url"), str) and sync_rid_bookmark(pid, area, path, n["url"]) == rid:
                nodes.remove(n)
                return True
        return False

    def _remove_kw_by_rid(self, rid, stats):
        kws = self.settings.get("address_keywords") or {}
        for kw in list(kws):
            if sync_rid_keyword(kw) == rid:
                del kws[kw]
                self.host.keywords_changed()
                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 = _sync_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 (unmarked, deleted, hidden): 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 browser 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)
            more = self.pull(ans)
            for k, v in more.items():
                stats[k] += v
        stats["sent"] = len(push)
        return stats


# *************** DEL 57 - PHONE SYNC - THE BROWSER SIDE (adapter, background runner, the "Phone sync" window) *****************
class PhoneSyncHost:
    """What PhoneSyncCore needs from the running browser. Trees of other profiles are read from their files and written back in flush()."""

    def __init__(self, win):
        self.win = win
        self.settings = win.settings
        self._trees = {}              # bookmarks file -> tree (profiles that are not the active one)
        self._dirty = set()           # bookmarks files that changed
        self._active_dirty = False
        self._kw_dirty = False
        self._settings_dirty = False

    def _prof(self, pid):
        for p in self.settings.get("profiles", []):
            if p.get("id") == pid:
                return p
        return None

    def _file(self, prof):
        try:
            return os.path.normcase(os.path.abspath(self.win._bookmarks_file(prof)))
        except Exception:
            return ""

    def _is_active(self, prof):
        return self._file(prof) == self._file(self.win._active_profile())

    def tree(self, pid):
        prof = self._prof(pid)
        if prof is None or self.win._is_fav_profile(prof):
            return None
        if self._is_active(prof):
            if not isinstance(self.win.bookmarks, dict):
                self.win.bookmarks = normalize_bookmarks(self.win.bookmarks)
            self.win.bookmarks.setdefault("bar", [])
            self.win.bookmarks.setdefault("menu", [])
            return self.win.bookmarks
        f = self._file(prof)
        if f not in self._trees:
            self._trees[f] = normalize_bookmarks(load_json(self.win._bookmarks_file(prof), []))
        return self._trees[f]

    def tree_changed(self, pid):
        prof = self._prof(pid)
        if prof is None:
            return
        if self._is_active(prof):
            self._active_dirty = True
        else:
            self._dirty.add(self._file(prof))

    def keywords_changed(self):
        self._kw_dirty = True
        self._settings_dirty = True

    def profiles_changed(self):
        self._settings_dirty = True

    def add_profile(self, p):
        self.settings.setdefault("profiles", []).append(p)
        self._settings_dirty = True

    def flush(self):
        for prof in self.settings.get("profiles", []):
            f = self._file(prof) if self._prof(prof.get("id")) else ""
            if f in self._dirty and f in self._trees:
                save_json(self.win._bookmarks_file(prof), self._trees[f])
                self._dirty.discard(f)
        if self._active_dirty:
            self.win._save_bm()
            try:
                self.win.build_bookmarks_bar()
            except Exception as e:
                log_line("phone sync: bookmarks bar not redrawn: %s" % e)
            self._active_dirty = False
        if self._settings_dirty:
            save_json(SETTINGS_FILE, self.settings)
            self._settings_dirty = False
        if self._kw_dirty:
            try:
                self.win._build_completer()
            except Exception:
                pass
            self._kw_dirty = False


def _phone_safe(fn):
    """An exception inside a Qt slot aborts the whole program: this logs it and carries on."""
    nargs = fn.__code__.co_argcount

    def wrapper(*a, **k):
        try:
            # A button's clicked(bool) hands over the "checked" flag; the slot may not want it (that made every button here do nothing).
            return fn(*a[:nargs], **k)
        except Exception as e:
            log_line("phone sync window: %s\n%s" % (e, traceback.format_exc()))
    wrapper.__name__ = fn.__name__
    return wrapper


def phone_sync_load_state():
    st = load_json(PHONE_SYNC_FILE, {})
    return st if isinstance(st, dict) else {}


def phone_sync_save_state(st):
    save_json(PHONE_SYNC_FILE, st)


def phone_sync_configured(st):
    return bool(st.get("url")) and len(str(st.get("key") or "")) >= 8


def phone_sync_server_label(st):
    m = re.match(r"^https?://([^/]+)", st.get("url") or "")
    return m.group(1) if m else ""


class PhoneSyncRunner(QObject):
    """Runs one sync round in two network steps; the network part is on a worker thread, everything that touches the browser's data is
    done back on the GUI thread (the signal below)."""
    _got = pyqtSignal(int, object, str)           # phase, answer, error text
    finished = pyqtSignal(bool, str)              # ok, one line for the status

    def __init__(self, win):
        super().__init__(win)
        self.win = win
        self.busy = False
        self._ctx = None
        self._got.connect(self._on_got)

    def start(self):
        st = self.win._phone_state
        if self.busy or not phone_sync_configured(st):
            return False
        self.busy = True
        host = PhoneSyncHost(self.win)
        core = PhoneSyncCore(self.win.settings, host, st)
        self._ctx = {"host": host, "core": core, "stats": {"added": 0, "removed": 0, "shortcuts": 0, "profiles": 0}, "sent": 0}
        self._net(1, st.get("since", 0), {})
        return True

    def _net(self, phase, since, recs):
        url, key = self.win._phone_state["url"], self.win._phone_state["key"]

        def work():
            try:
                self._got.emit(phase, phone_sync_post(url, key, since, recs), "")
            except Exception as e:
                self._got.emit(phase, {}, str(e)[:200])
        threading.Thread(target=work, daemon=True).start()

    def _add(self, stats):
        for k, v in stats.items():
            self._ctx["stats"][k] = self._ctx["stats"].get(k, 0) + v

    def _on_got(self, phase, ans, err):
        ctx = self._ctx
        if ctx is None:
            return
        if err:
            return self._end(False, "Not synced: " + err)
        try:
            core = ctx["core"]
            if phase == 1:
                self._add(core.pull(ans))
                push, newknown = core.make_push()
                ctx["pending"] = (push, newknown)
                if push:
                    return self._net(2, core.st["since"], push)
            else:
                push, newknown = ctx["pending"]
                core.commit(newknown)
                ctx["sent"] = len(push)
                self._add(core.pull(ans))
            self._end(True, "")
        except Exception as e:
            log_line("phone sync failed: %s\n%s" % (e, traceback.format_exc()))
            self._end(False, "Not synced: %s" % e)

    def _end(self, ok, msg):
        ctx, self._ctx, self.busy = self._ctx, None, False
        st = self.win._phone_state
        try:
            ctx["host"].flush()
        except Exception as e:
            log_line("phone sync flush failed: %s" % e)
        if ok:
            s = ctx["stats"]
            msg = "Synced: sent %d, got %d bookmarks, %d shortcuts, %d profiles, %d removed" % (
                ctx["sent"], s["added"], s["shortcuts"], s["profiles"], s["removed"])
        st["last"] = {"t": int(time.time()), "ok": bool(ok), "msg": msg}
        phone_sync_save_state(st)
        log_line("phone sync: " + msg)
        self.finished.emit(bool(ok), msg)


def _wb_phone_sync_boot(self):
    """Called once at the end of Browser.__init__: loads the state, starts the quiet automatic sync (15 s after start, then every 10 min)."""
    self._phone_state = phone_sync_load_state()
    self._phone_runner = PhoneSyncRunner(self)
    self._phone_timer = QTimer(self)
    self._phone_timer.timeout.connect(self._phone_sync_tick)
    self._phone_timer.start(10 * 60 * 1000)
    QTimer.singleShot(15000, self._phone_sync_tick)


def _wb_phone_sync_tick(self):
    st = self._phone_state
    if phone_sync_configured(st) and st.get("auto", True) and not self._is_fav_profile():
        self._phone_runner.start()


def _wb_open_phone_sync(self):
    dlg = PhoneSyncDialog(self)
    dlg.exec()


Browser._phone_sync_boot = _wb_phone_sync_boot
Browser._phone_sync_tick = _wb_phone_sync_tick
Browser.open_phone_sync = _wb_open_phone_sync


class _PhoneServerDialog(QDialog):
    """Where the relay is: paste a code from another device, or type the address and key, or take relay.json."""

    def __init__(self, parent, st):
        super().__init__(parent)
        self.st = st
        self.setWindowTitle(APP_NAME + " - Phone sync server")
        self.setModal(True)
        self.resize(520, 300)
        self.setStyleSheet(dialog_qss())
        apply_window_icon(self)
        lay = QVBoxLayout(self)
        lay.addWidget(QLabel("The server is a small relay of your own (see relay\\README_relay.md). It only passes the lists you share.\n"
                             "Paste a code (it fills in the two boxes), or type them."))
        self.ed_url = QLineEdit(st.get("url", ""))
        self.ed_url.setPlaceholderText("https://your.server.example/whybrowse/")
        self.ed_key = QLineEdit(st.get("key", ""))
        self.ed_key.setEchoMode(QLineEdit.EchoMode.Password)
        self.ed_key.setPlaceholderText("key")
        lay.addWidget(QLabel("Address:"))
        lay.addWidget(self.ed_url)
        lay.addWidget(QLabel("Key:"))
        lay.addWidget(self.ed_key)
        row = QHBoxLayout()
        b1 = QPushButton("Paste a code")
        b1.clicked.connect(self._paste)
        row.addWidget(b1)
        self.b2 = QPushButton("Use relay.json")
        self.b2.setEnabled(os.path.isfile(PHONE_RELAY_JSON))
        self.b2.setToolTip("relay.json in this program's data folder, made by relay\\make_installer.py")
        self.b2.clicked.connect(self._use_json)
        row.addWidget(self.b2)
        row.addStretch(1)
        lay.addLayout(row)
        self.msg = QLabel("")
        lay.addWidget(self.msg)
        lay.addStretch(1)
        row2 = QHBoxLayout()
        row2.addStretch(1)
        b3 = QPushButton("Save")
        b3.clicked.connect(self._save)
        b4 = QPushButton("Cancel")
        b4.clicked.connect(self.reject)
        row2.addWidget(b3)
        row2.addWidget(b4)
        lay.addLayout(row2)

    def _paste(self):
        d = sync_code_parse(QApplication.clipboard().text())
        if not d:
            self.msg.setText("The clipboard does not hold a sync code.")
            return
        self.ed_url.setText(d["url"])
        self.ed_key.setText(d["key"])
        self.msg.setText("Code read. Press Save.")

    def _use_json(self):
        d = load_json(PHONE_RELAY_JSON, {})
        if isinstance(d, dict) and d.get("url") and d.get("key"):
            self.ed_url.setText(str(d["url"]))
            self.ed_key.setText(str(d["key"]))
            self.msg.setText("relay.json read. Press Save.")
        else:
            self.msg.setText("relay.json has no url / key.")

    def _save(self):
        url, key = self.ed_url.text().strip(), self.ed_key.text().strip()
        if not re.match(r"^https?://[^\s]+$", url) or len(key) < 8:
            self.msg.setText("Give an address that starts with https:// and a key.")
            return
        if url != self.st.get("url") or key != self.st.get("key"):
            self.st.update({"url": url if url.endswith("/") else url + "/", "key": key, "since": 0, "known": {}})   # another server: start over
        self.accept()


class PhoneSyncDialog(QDialog):
    """☰ -> Phone sync: the connection, which profiles / bookmarks / shortcuts the phone gets, what came from the phone. Changes are kept at once."""
    ROLE_KIND = Qt.ItemDataRole.UserRole
    ROLE_REF = Qt.ItemDataRole.UserRole + 1

    def __init__(self, win):
        super().__init__(win)
        self.win = win
        self.st = win._phone_state
        self.host = PhoneSyncHost(win)
        self._refs = []               # tree items hold an index into this list (Qt would only keep a COPY of a dict)
        self.setWindowTitle(APP_NAME + " - Phone sync (Issu's WhyBrowse app)")
        self.setModal(True)
        self.resize(760, 640)
        self.setStyleSheet(dialog_qss())
        apply_window_icon(self)
        lay = QVBoxLayout(self)
        self.tabs = QTabWidget()
        lay.addWidget(self.tabs, 1)
        self._build_connection()
        self._build_tree()
        self._build_shortcuts()
        row = QHBoxLayout()
        self.lbl_bottom = QLabel("Changes are kept at once. Sync runs by itself every 10 minutes (and when you press Sync now).")
        row.addWidget(self.lbl_bottom, 1)
        bc = QPushButton("Close")
        bc.clicked.connect(self.accept)
        row.addWidget(bc)
        lay.addLayout(row)
        win._phone_runner.finished.connect(self._on_finished)
        self._refresh_status()

    # ---- tab 1: connection
    def _build_connection(self):
        w = QWidget()
        lay = QVBoxLayout(w)
        lay.addWidget(QLabel(
            "The phone app <b>Issu's WhyBrowse</b> shows the profiles, bookmarks and address shortcuts you choose here, and what you add on the phone "
            "comes back (a profile made on the phone becomes a profile of its own here). Nothing else is shared: no history, no tabs, no logins."))
        lay.itemAt(0).widget().setWordWrap(True)
        lay.itemAt(0).widget().setTextFormat(Qt.TextFormat.RichText)
        self.lbl_status = QLabel("")
        self.lbl_status.setWordWrap(True)
        lay.addWidget(self.lbl_status)
        steps = QLabel("<b>How it works</b><br>1. <b>Server...</b> once (paste the code or use relay.json).<br>"
                       "2. On the tab <b>Profiles &amp; bookmarks</b> tick the profile(s) for the phone. A ticked profile sends ALL its bookmarks; "
                       "untick <i>Share ALL</i> inside it to pick folders or links instead.<br>"
                       "3. That is all - it is sent a few seconds after every change (or press <b>Sync now</b>).<br>"
                       "4. <b>Copy code for the phone</b> once, and paste it in the app under Settings.")
        steps.setWordWrap(True)
        steps.setTextFormat(Qt.TextFormat.RichText)
        lay.addWidget(steps)
        self.lbl_will = QLabel("")
        self.lbl_will.setWordWrap(True)
        self.lbl_will.setTextFormat(Qt.TextFormat.RichText)
        lay.addWidget(self.lbl_will)
        r1 = QHBoxLayout()
        self.b_server = QPushButton("Server...")
        self.b_server.clicked.connect(self._server)
        self.b_sync = QPushButton("Sync now")
        self.b_sync.clicked.connect(self._sync_now)
        self.b_code = QPushButton("Copy code for the phone")
        self.b_code.clicked.connect(self._copy_code)
        for b in (self.b_server, self.b_sync, self.b_code):
            r1.addWidget(b)
        r1.addStretch(1)
        lay.addLayout(r1)
        self.chk_auto = QCheckBox("Sync automatically (a few seconds after start, then every 10 minutes)")
        self.chk_auto.setChecked(bool(self.st.get("auto", True)))
        self.chk_auto.toggled.connect(self._auto)
        lay.addWidget(self.chk_auto)
        self.lbl_code = QLabel("")
        self.lbl_code.setWordWrap(True)
        lay.addWidget(self.lbl_code)
        self.lbl_hidden = QLabel("")
        self.b_unhide = QPushButton("Show them on the phone again")
        self.b_unhide.clicked.connect(self._unhide)
        lay.addWidget(self.lbl_hidden)
        lay.addWidget(self.b_unhide)
        lay.addStretch(1)
        self.tabs.addTab(w, "Connection")

    def _refresh_status(self):
        st = self.st
        if phone_sync_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"
            self.lbl_status.setText("Server: <b>%s</b><br>Last sync: %s  -  %s" % (phone_sync_server_label(st), when, last.get("msg") or "-"))
        else:
            self.lbl_status.setText("No server yet. Press <b>Server...</b>: paste a code, or use the relay.json made by relay\\make_installer.py.")
        self.lbl_status.setTextFormat(Qt.TextFormat.RichText)
        ok = phone_sync_configured(st)
        self.b_sync.setEnabled(ok and not self.win._phone_runner.busy)
        self.b_code.setEnabled(ok)
        n = len(st.get("hidden") or []) + len(self.win.settings.get("phone_kw_off") or [])
        self.lbl_hidden.setText("Removed from the phone's list on the phone (kept here, not sent again): %d bookmarks, %d shortcuts."
                                % (len(st.get("hidden") or []), len(self.win.settings.get("phone_kw_off") or [])))
        self.b_unhide.setEnabled(bool(n))
        self._refresh_will()

    def _refresh_will(self):
        """One line that says plainly what the phone will get now (a ticked profile with nothing ticked inside it gives an empty phone)."""
        try:
            recs = PhoneSyncCore(self.win.settings, self.host, self.st).gather()
        except Exception as e:
            self.lbl_will.setText("")
            log_line("phone sync window: summary: %s" % e)
            return
        np_ = sum(1 for r in recs.values() if r.get("k") == "p")
        nb = sum(1 for r in recs.values() if r.get("k") == "b")
        nk = sum(1 for r in recs.values() if r.get("k") == "k")
        if np_ == 0:
            txt = "<b style='color:#f0a030'>The phone gets nothing yet: no profile is ticked.</b> Open the tab Profiles &amp; bookmarks and tick one."
        elif nb == 0:
            txt = ("<b style='color:#f0a030'>The phone gets %d profile(s) but NO bookmarks.</b> Open the profile on the tab Profiles &amp; bookmarks and tick "
                   "<i>Share ALL bookmarks</i>, or single folders / links." % np_)
        else:
            txt = "<b>The phone gets:</b> %d profile(s), %d bookmarks, %d address shortcuts." % (np_, nb, nk)
        self.lbl_will.setText(txt)

    def _kick_sync(self):
        """A few seconds after the last tick: send it (so there is no second thing to remember)."""
        t = getattr(self, "_kick_timer", None)
        if t is None:
            t = QTimer(self)
            t.setSingleShot(True)
            t.timeout.connect(self._kick_fire)
            self._kick_timer = t
        t.start(3000)

    @_phone_safe
    def _kick_fire(self):
        if phone_sync_configured(self.st) and not self.win._phone_runner.busy:
            if self.win._phone_runner.start():
                self.lbl_status.setText("Syncing...")

    @_phone_safe
    def _server(self):
        d = _PhoneServerDialog(self, self.st)
        if d.exec():
            phone_sync_save_state(self.st)
            self._refresh_status()

    @_phone_safe
    def _sync_now(self):
        if self.win._phone_runner.start():
            self.lbl_status.setText("Syncing...")
            self.b_sync.setEnabled(False)

    @_phone_safe
    def _on_finished(self, ok, msg):
        try:
            self._refresh_status()
            self._rebuild_tree()
            self._fill_shortcuts()
        except RuntimeError:
            pass

    @_phone_safe
    def _copy_code(self):
        code = sync_code_make(self.st["url"], self.st["key"])
        QApplication.clipboard().setText(code)
        self.lbl_code.setText("Copied. In the phone app: Settings > Sync > <b>Paste code</b>. The code holds your server key: send it only to your own "
                              "phone (it is on the clipboard now; copy something else when you are done).")
        self.lbl_code.setTextFormat(Qt.TextFormat.RichText)

    def _auto(self, on):
        self.st["auto"] = bool(on)
        phone_sync_save_state(self.st)

    @_phone_safe
    def _unhide(self):
        self.st["hidden"] = []
        self.win.settings["phone_kw_off"] = []
        save_json(SETTINGS_FILE, self.win.settings)
        phone_sync_save_state(self.st)
        self._refresh_status()
        self._fill_shortcuts()

    # ---- tab 2: profiles and bookmarks
    def _build_tree(self):
        w = QWidget()
        lay = QVBoxLayout(w)
        info = QLabel("Tick a <b>profile</b> to show it on the phone: it then sends <b>all its bookmarks</b>, folders as they are here. To send only some, "
                      "open the profile, untick <b>Share ALL bookmarks</b> and tick single folders / links (a ticked folder shares everything inside it). "
                      "Only the profile's name, colour and badge are shared - never logins or cookies.")
        info.setWordWrap(True)
        info.setTextFormat(Qt.TextFormat.RichText)
        lay.addWidget(info)
        self.tree = QTreeWidget()
        self.tree.setHeaderHidden(True)
        self.tree.itemChanged.connect(self._tree_changed)
        self.tree.itemExpanded.connect(self._tree_expanded)
        lay.addWidget(self.tree, 1)
        self.tabs.addTab(w, "Profiles && bookmarks")
        self._rebuild_tree()

    def _profiles(self):
        return [p for p in self.win.settings.get("profiles", []) if not self.win._is_fav_profile(p)]

    def _rebuild_tree(self):
        self.tree.blockSignals(True)
        self.tree.clear()
        self._refs = []
        for p in self._profiles():
            it = QTreeWidgetItem(self.tree)
            it.setFlags(it.flags() | Qt.ItemFlag.ItemIsUserCheckable)
            it.setCheckState(0, Qt.CheckState.Checked if p.get("phone") else Qt.CheckState.Unchecked)
            it.setText(0, "%s  %s%s" % (p.get("badge", "?"), p.get("name", p.get("id")), "   (made on the phone)" if p.get("phone_origin") else ""))
            it.setData(0, self.ROLE_KIND, "profile")
            it.setData(0, self.ROLE_REF, p.get("id"))
            QTreeWidgetItem(it).setText(0, "...")                     # lazy: filled when opened
        self.tree.blockSignals(False)

    def _node_count(self, nodes):
        n = 0
        for x in nodes or []:
            n += self._node_count(x.get("folder")) if "folder" in x else (1 if x.get("url") else 0)
        return n

    def _ref(self, node):
        self._refs.append(node)
        return len(self._refs) - 1

    @_phone_safe
    def _tree_expanded(self, it):
        if it.data(0, self.ROLE_KIND) == "profile" and it.childCount() == 1 and it.child(0).text(0) == "...":
            self._fill_profile(it)

    def _fill_profile(self, it):
        pid = it.data(0, self.ROLE_REF)
        prof = next((p for p in self.win.settings.get("profiles", []) if p.get("id") == pid), None)
        tree = self.host.tree(pid)
        self.tree.blockSignals(True)
        it.takeChildren()
        if prof is None or tree is None:
            self.tree.blockSignals(False)
            return
        allc = QTreeWidgetItem(it)
        allc.setFlags(allc.flags() | Qt.ItemFlag.ItemIsUserCheckable)
        allc.setCheckState(0, Qt.CheckState.Checked if prof.get("phone_all") else Qt.CheckState.Unchecked)
        allc.setText(0, "Share ALL bookmarks of this profile  (%d links)" % (self._node_count(tree.get("bar")) + self._node_count(tree.get("menu"))))
        allc.setData(0, self.ROLE_KIND, "all")
        allc.setData(0, self.ROLE_REF, pid)
        for area, title in (("bar", "Bookmarks bar"), ("menu", "Bookmarks menu")):
            top = QTreeWidgetItem(it)
            top.setText(0, "%s  (%d links)" % (title, self._node_count(tree.get(area))))
            self._fill_nodes(top, tree.get(area) or [], bool(prof.get("phone_all")))
        self.tree.blockSignals(False)

    def _fill_nodes(self, parent, nodes, inherited):
        for n in nodes:
            if not isinstance(n, dict) or not (n.get("url") or "folder" in n):
                continue
            it = QTreeWidgetItem(parent)
            isf = "folder" in n
            it.setText(0, ("📁 " if isf else "") + str(n.get("title") or n.get("url") or "")[:90])
            it.setToolTip(0, "" if isf else str(n.get("url") or ""))
            it.setFlags(it.flags() | Qt.ItemFlag.ItemIsUserCheckable)
            marked = inherited or bool(n.get("phone"))
            it.setCheckState(0, Qt.CheckState.Checked if marked else Qt.CheckState.Unchecked)
            if inherited:
                it.setFlags(it.flags() & ~Qt.ItemFlag.ItemIsEnabled)
            it.setData(0, self.ROLE_KIND, "folder" if isf else "link")
            it.setData(0, self.ROLE_REF, self._ref(n))
            if isf:
                self._fill_nodes(it, n.get("folder") or [], marked)

    @_phone_safe
    def _tree_changed(self, it, col):
        kind = it.data(0, self.ROLE_KIND)
        on = it.checkState(0) == Qt.CheckState.Checked
        if kind == "profile":
            pid = it.data(0, self.ROLE_REF)
            for p in self.win.settings.get("profiles", []):
                if p.get("id") == pid:
                    p["phone"] = on
                    if on and not p.get("phone_all") and not self._has_marks(pid):
                        p["phone_all"] = True        # nothing picked yet: a ticked profile sends all its bookmarks (the usual wish)
                        if it.childCount() and it.child(0).text(0) != "...":
                            self.tree.blockSignals(True)
                            it.takeChildren()
                            QTreeWidgetItem(it).setText(0, "...")
                            self.tree.blockSignals(False)
                            it.setExpanded(False)
            self._save_settings()
        elif kind == "all":
            pid = it.data(0, self.ROLE_REF)
            for p in self.win.settings.get("profiles", []):
                if p.get("id") == pid:
                    p["phone_all"] = on
            self._save_settings()
            self._fill_profile(it.parent())
            it.parent().setExpanded(True)
        elif kind in ("folder", "link"):
            n = self._refs[it.data(0, self.ROLE_REF)]
            if on:
                n["phone"] = True
            else:
                n.pop("phone", None)
            if kind == "folder":                       # a ticked folder says it all: single marks inside it are cleared
                self._clear_marks(n.get("folder") or [])
                self.tree.blockSignals(True)
                it.takeChildren()
                self._fill_nodes(it, n.get("folder") or [], on)
                self.tree.blockSignals(False)
            top = it
            while top.parent() is not None and top.data(0, self.ROLE_KIND) != "profile":
                top = top.parent()
            self._save_tree(top.data(0, self.ROLE_REF))

    def _clear_marks(self, nodes):
        for x in nodes:
            if isinstance(x, dict):
                x.pop("phone", None)
                if "folder" in x:
                    self._clear_marks(x["folder"])

    def _has_marks(self, pid):
        tree = self.host.tree(pid) or {}

        def any_mark(nodes):
            for x in nodes or []:
                if isinstance(x, dict) and (x.get("phone") or ("folder" in x and any_mark(x["folder"]))):
                    return True
            return False
        return any_mark(tree.get("bar")) or any_mark(tree.get("menu"))

    def _save_settings(self):
        save_json(SETTINGS_FILE, self.win.settings)
        self._refresh_will()
        self._kick_sync()

    def _save_tree(self, pid):
        self.host.tree_changed(pid)
        self.host.flush()
        self._refresh_will()
        self._kick_sync()

    # ---- tab 3: shortcuts
    def _build_shortcuts(self):
        w = QWidget()
        lay = QVBoxLayout(w)
        info = QLabel("Address shortcuts: type <b>y</b> in the address box and get youtube.com. Ticked ones are sent to the phone; shortcuts you add on the "
                      "phone arrive here too.")
        info.setWordWrap(True)
        info.setTextFormat(Qt.TextFormat.RichText)
        lay.addWidget(info)
        self.chk_kw = QCheckBox("Send my address shortcuts to the phone")
        self.chk_kw.setChecked(bool(self.win.settings.get("phone_kw_sync", True)))
        self.chk_kw.toggled.connect(self._kw_master)
        lay.addWidget(self.chk_kw)
        self.kw_tree = QTreeWidget()
        self.kw_tree.setColumnCount(2)
        self.kw_tree.setHeaderLabels(["Shortcut  (tick = on the phone)", "Goes to"])
        self.kw_tree.setRootIsDecorated(False)
        self.kw_tree.itemChanged.connect(self._kw_changed)
        lay.addWidget(self.kw_tree, 1)
        row = QHBoxLayout()
        ba = QPushButton("Add...")
        ba.clicked.connect(self._kw_add)
        br = QPushButton("Remove")
        br.clicked.connect(self._kw_remove)
        row.addWidget(ba)
        row.addWidget(br)
        row.addStretch(1)
        lay.addLayout(row)
        self.tabs.addTab(w, "Address shortcuts")
        self._fill_shortcuts()

    def _fill_shortcuts(self):
        self.kw_tree.blockSignals(True)
        self.kw_tree.clear()
        off = set(self.win.settings.get("phone_kw_off") or [])
        for kw, url in sorted((self.win.settings.get("address_keywords") or {}).items()):
            it = QTreeWidgetItem(self.kw_tree)
            it.setFlags(it.flags() | Qt.ItemFlag.ItemIsUserCheckable)
            it.setCheckState(0, Qt.CheckState.Unchecked if kw in off else Qt.CheckState.Checked)
            it.setText(0, kw)
            it.setText(1, url)
        self.kw_tree.resizeColumnToContents(0)
        self.kw_tree.blockSignals(False)

    def _kw_master(self, on):
        self.win.settings["phone_kw_sync"] = bool(on)
        self._save_settings()

    @_phone_safe
    def _kw_changed(self, it, col):
        kw = it.text(0)
        off = [x for x in (self.win.settings.get("phone_kw_off") or []) if x != kw]
        if it.checkState(0) != Qt.CheckState.Checked:
            off.append(kw)
        self.win.settings["phone_kw_off"] = off
        self._save_settings()

    @_phone_safe
    def _kw_add(self):
        kw, ok = QInputDialog.getText(self, "Add shortcut", "Keyword (no spaces), for example  y :")
        kw = (kw or "").strip().lower()
        if not ok or not kw or " " in kw:
            return
        url, ok = QInputDialog.getText(self, "Add shortcut", "Goes to (address):", text="https://")
        url = (url or "").strip()
        if not ok or not re.match(r"^https?://[^\s]+$", url):
            return
        self.win.settings.setdefault("address_keywords", {})[kw] = url
        self._save_settings()
        try:
            self.win._build_completer()
        except Exception:
            pass
        self._fill_shortcuts()

    @_phone_safe
    def _kw_remove(self):
        it = self.kw_tree.currentItem()
        if it is None:
            return
        self.win.settings.get("address_keywords", {}).pop(it.text(0), None)
        self._save_settings()
        try:
            self.win._build_completer()
        except Exception:
            pass
        self._fill_shortcuts()

    def done(self, r):
        try:
            self.win._phone_runner.finished.disconnect(self._on_finished)
        except Exception:
            pass
        try:
            self.host.flush()
        except Exception:
            pass
        super().done(r)


# ============================================================================
#  DEL 15 - MAIN
# ============================================================================
def main():
    # AppUserModelID must be set BEFORE QApplication (correct taskbar grouping)
    set_app_user_model_id()

    # High-DPI friendliness
    try:
        os.environ.setdefault("QT_ENABLE_HIGHDPI_SCALING", "1")
    except Exception:
        pass

    # Force classic, always-visible scrollbars (Chromium's overlay scrollbars
    # fade out, which looks like the scrollbar "disappearing" e.g. on Tradera).
    try:
        # Read settings early (no Qt needed) to honour the "keep background tabs
        # active" choice before Chromium starts.
        _early = load_json(SETTINGS_FILE, {})
        keep_bg = bool(_early.get("keep_bg_active", True)) if isinstance(_early, dict) else True
        flags = os.environ.get("QTWEBENGINE_CHROMIUM_FLAGS", "")
        add = ""
        # Chromium only honours the LAST --disable-features=, so all disabled
        # features must go in ONE comma-separated flag.
        if "disable-features" not in flags:
            feats = "OverlayScrollbar"
            if keep_bg:
                feats += ",IntensiveWakeUpThrottling,CalculateNativeWinOcclusion"
            add += " --disable-features=" + feats
        # Keep BACKGROUND tabs fully alive & responsive (uses more memory/CPU).
        # Without these, Chromium throttles an idle tab (e.g. a big Google Sheet)
        # so hard it behaves as if it slept. Turn OFF "keep background tabs active"
        # in Settings → Performance to let them throttle and save memory.
        if keep_bg:
            if "renderer-backgrounding" not in flags:
                add += " --disable-renderer-backgrounding"
            if "background-timer-throttling" not in flags:
                add += " --disable-background-timer-throttling"
            if "backgrounding-occluded-windows" not in flags:
                add += " --disable-backgrounding-occluded-windows"
        # Quiet Chromium's own console spam (harmless WebRTC/P2P STUN messages).
        if "log-level" not in flags:
            add += " --log-level=3"
        # (DEL 56 note: --log-file is ignored by QtWebEngine - tested 2026-11-15 - so the
        # Chromium assertion line can only be seen on stderr: see WhyBrowse_Chromium_log.bat.)
        if add:
            os.environ["QTWEBENGINE_CHROMIUM_FLAGS"] = (flags + add).strip()
    except Exception:
        pass

    app = QApplication(sys.argv)
    app.setApplicationName(APP_NAME)
    app.setApplicationDisplayName(APP_NAME)

    # Keep this handle alive for the whole app lifetime - see check_single_instance().
    # If another instance already holds this Helpfiles folder, this run becomes
    # a "secondary" instance: separate Chromium storage (never fights over the
    # same locked cookie file) + a live cookie hand-off so it still starts
    # logged in (see IS_SECONDARY_INSTANCE / profile_paths() / Browser class).
    global IS_SECONDARY_INSTANCE
    app._wb_instance_mutex, IS_SECONDARY_INSTANCE = check_single_instance()

    # ---- Single-instance URL forwarding ----
    # If WhyBrowse is ALREADY running and Windows launched us just to open a
    # link (default-browser click in Thunderbird etc.), hand that URL to the
    # running instance over the local pipe and quit — do NOT open a second
    # WhyBrowse. The running instance opens it in profile 1 and comes forward.
    launch_url = get_launch_url()
    launch_profile = get_launch_profile()
    if IS_SECONDARY_INSTANCE and launch_url:
        if forward_url_to_running_instance(launch_url, profile=launch_profile):
            log_line("Forwarded URL to running instance, exiting: %s (profile=%s)"
                     % (launch_url, launch_profile or "-"))
            return
        # Nobody answered the pipe (running instance too old / starting up):
        # fall through and open normally rather than losing the link.
        log_line("Forward failed; opening URL in this instance instead.")

    # ---- No blinking cursor anywhere (Qt equivalent of insertofftime=0) ----
    app.setCursorFlashTime(0)

    p = ico_path()
    if p:
        app.setWindowIcon(QIcon(p))

    install_crash_handler(app)
    # Safety net: no window may open bigger than the monitor it lands on.
    install_screen_clamp(app)
    log_line("WhyBrowse started. Version: {} · Base dir: {}".format(
        APP_VERSION, BASE_DIR))

    # A travel copy is unlocked BEFORE the window exists, because the
    # window is built from bookmarks and settings that are still inside
    # the encrypted file at this point. No password, no bookmarks.
    if _TRAVEL_MODE:
        if not travel_startup_unlock():
            _travel_shutdown()
            return

    win = Browser(launch_url=launch_url)
    # Cold start with --profile=: switch before the launch URL is opened, so
    # the link lands on the right login rather than in profile 1 (F(re)email
    # uses this to match a mail's Gmail account to its browser profile).
    if launch_profile:
        try:
            _target = win._resolve_profile_id(launch_profile)
            if _target and _target != win.active_id:
                win.switch_profile(_target)
                log_line("Cold start switched to profile %s" % _target)
            elif not _target:
                log_line("Requested profile %r not found" % launch_profile)
        except Exception as _e:
            log_line("Could not apply --profile: %s" % _e)
    win.show()
    win.raise_()
    win.activateWindow()
    # Re-assert the icon on the first event-loop tick (matches the icon recipe).
    QTimer.singleShot(0, lambda: apply_window_icon(win))
    # Delayed so it never competes with startup for CPU/network; checks PyPI
    # for a newer Chromium engine (PyQt6-WebEngine) and toasts if one exists.
    QTimer.singleShot(4000, win._check_engine_update_on_startup)
    # Fetch latest stable Chrome version from Google's VERSIONHISTORY API so
    # the UA string always reports a believable, current Chrome.  Runs at most
    # once every 30 days; completely silent on failure.
    QTimer.singleShot(6000, win._check_chrome_version_on_startup)

    if IS_SECONDARY_INSTANCE:
        QTimer.singleShot(600, lambda: show_toast(
            win, "Linked session: inherited logins from the other open window"))

    # TEMPORARY: a version/cookie popup that sits BEHIND the main window and must
    # be closed by hand, so we always know which build is running. Shown after the
    # main window + lowered so it doesn't steal focus.
    # (The version is also shown in About and logged at startup.)
    def _show_version_popup():
        try:
            win._version_popup = VersionPopup(win)
            win._version_popup.show()
            win._version_popup.lower()
            win.raise_()
            win.activateWindow()
        except Exception as e:
            log_line("version popup error: {}".format(e))
    # DISABLED (popup off). Re-enable by un-commenting the next line:
    # QTimer.singleShot(300, _show_version_popup)

    code = app.exec()
    # A travel session seals its file and deletes its working folder.
    # atexit does this too, but only if the interpreter gets that far.
    try:
        _travel_shutdown()
    except Exception as e:
        log_line("Travel shutdown failed: {}".format(e))
    sys.exit(code)


if __name__ == "__main__":
    main()
