#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ============================================================
#  MKV Player  –  Lightweight video player (libmpv backend)
#  Author : Lars "Issu" Olsson
# ============================================================
#
# ToDo:
#   DEL 01  Imports, path bootstrap, dependency check
#   DEL 02  Crash handler
#   DEL 03  Settings (load / save / defaults)
#   DEL 04  Resume positions (per-file, 28-day TTL)
#   DEL 05  Colors & helpers
#   DEL 06  MKVPlayer class + __init__
#   DEL 07    _build_menu
#   DEL 08    _build_ui  (overlay layout: video fills window, controls float)
#   DEL 08b   Right-click context menu (every button; usable in tiny windows)
#   DEL 09    _init_mpv
#   DEL 10    mpv observers (thread-safe)
#   DEL 11    _poll – 200 ms GUI refresh
#   DEL 12    Playback (open, play, stop, seek, volume, resume)
#   DEL 13    Auto-hide controls (mouse tracking)
#   DEL 14    Window modes (windowed / maximize / stretch / fullscreen)
#   DEL 15    _on_close – save & cleanup
#   DEL 16    About dialog
#   DEL 17    Help dialog
#   DEL 18    Entry point
#   DEL 04f   Subtitle sync engine – multi-point time remap (pure functions)
#   DEL 20b   Subtitle sync dialog – mark points, review, "Correct" to save
#   DEL 21    Bluetooth headphones – Win32 reconnect (module level)
#   DEL 12c   Bluetooth 🎧 button, chooser, right-click entries (in the class)
#   DEL 12d   S key: bake the temporary , / . sub-delay into the subtitle file
#             (confirm dialog, Enter = yes, old file kept as BACKUP-<name>)
#   DEL 12e   Sub menu: "Open subtitle in editor" under the languages ->
#             Meditor (via _launch_my_app), Notepad if Meditor is not found
#             (2026-11-25)


# *************** DEL 01 - IMPORTS & BOOTSTRAP ***************

import sys
import os
import json
import hashlib
import traceback
import datetime
import ctypes
import sqlite3
import tkinter as tk
from tkinter import filedialog, messagebox
import os
import sys
import shutil
import subprocess
import socket
import threading


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


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


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


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

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

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


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

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


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


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


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

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


_HUB_PY_ROOTS = None


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

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

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


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

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


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

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


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

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

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

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

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


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


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


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


# Resolve base directory - works as .py and as PyInstaller .exe
if getattr(sys, "frozen", False):
    BASE_DIR = _program_home()
    # --onefile builds extract everything to _MEIPASS; add it to PATH
    # so bundled DLLs (via --add-binary) are findable.
    _MEIPASS = getattr(sys, "_MEIPASS", "")
    if _MEIPASS:
        os.environ["PATH"] = _MEIPASS + os.pathsep + os.environ.get("PATH", "")
else:
    _MEIPASS = ""
    BASE_DIR = _program_home()

# Canonical root for app-relative resources (icons, etc.)
APP_DIR = BASE_DIR

# Settings/logs stored under Helpfiles/BGGCollection/
# Shared resources (libmpv DLL etc.) stay in Helpfiles/1---Movie/
HELPFILES    = os.path.join(BASE_DIR, "Helpfiles")
DIR_LOGS     = os.path.join(HELPFILES, "0---Empty")
DIR_SETTINGS = os.path.join(HELPFILES, "MKV")
DIR_MOVIE    = os.path.join(HELPFILES, "1---Movie")

# Default path to movie DB  (sibling folder Movies/Helpfiles/movies/movies.db)
MOVIES_DB_DEFAULT = os.path.join(BASE_DIR, "..", "Movies", "Helpfiles", "movies", "movies.db")

SUB_REPLACE_DIR  = os.path.join(DIR_SETTINGS, "sub_replace")
SUB_REPLACE_TEMP = os.path.join(DIR_SETTINGS, "sub_temp")
SUB_SYNC_TEMP    = os.path.join(DIR_SETTINGS, "sub_sync_temp")

for _d in (DIR_LOGS, DIR_SETTINGS, DIR_MOVIE, SUB_REPLACE_DIR, SUB_REPLACE_TEMP, SUB_SYNC_TEMP):
    os.makedirs(_d, exist_ok=True)

SETTINGS_FILE    = os.path.join(DIR_SETTINGS, "MKVPlayer_settings.json")
RESUME_FILE      = os.path.join(DIR_SETTINGS, "MKVPlayer_resume.json")
SUB_FILE         = os.path.join(DIR_SETTINGS, "MKVPlayer_sub_settings.json")
SUB_SYNC_FILE    = os.path.join(DIR_SETTINGS, "MKVPlayer_sub_sync.json")
STATS_FILE       = os.path.join(DIR_SETTINGS, "MKVPlayer_stats.json")
NOTES_FILE       = os.path.join(DIR_SETTINGS, "MKVPlayer_movie_notes.json")
LOG_FILE         = os.path.join(DIR_LOGS,     "MKVPlayer_crash.log")

# Inject DLL directories into PATH *before* importing mpv.
# Search order: _MEIPASS first (bundled via --add-binary), then DIR_MOVIE (external).
_dll_search_dirs = []
if _MEIPASS:
    _dll_search_dirs.append(_MEIPASS)
_dll_search_dirs.append(DIR_MOVIE)

# os.add_dll_directory (Python 3.8+, Windows) is the most reliable way to
# register extra DLL search paths — ctypes.CDLL and LoadLibrary both honour it.
for _sd in _dll_search_dirs:
    if os.path.isdir(_sd):
        os.environ["PATH"] = _sd + os.pathsep + os.environ.get("PATH", "")
        if hasattr(os, "add_dll_directory"):
            try:
                os.add_dll_directory(_sd)
            except Exception:
                pass

_dll_loaded = False
for _sd in _dll_search_dirs:
    for _dll_name in ("libmpv-2.dll", "mpv-2.dll", "libmpv.dll", "mpv-1.dll"):
        _dll_path = os.path.join(_sd, _dll_name)
        if os.path.isfile(_dll_path):
            try:
                ctypes.CDLL(_dll_path)
                _dll_loaded = True
            except OSError:
                pass
            break
    if _dll_loaded:
        break

try:
    import mpv as _mpv_module
    MPV_AVAILABLE = True
except (ImportError, OSError, Exception):
    MPV_AVAILABLE = False


# *************** DEL 02 - CRASH HANDLER ***************

def _write_crash_log(msg: str) -> None:
    ts = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    try:
        with open(LOG_FILE, "a", encoding="utf-8") as fh:
            fh.write(f"\n{'=' * 60}\n{ts}\n{msg}\n")
    except Exception:
        pass


def _log_info(msg: str) -> None:
    """Write a lightweight [INFO] entry to the same log file."""
    ts = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    try:
        with open(LOG_FILE, "a", encoding="utf-8") as fh:
            fh.write(f"{ts}  [INFO]  {msg}\n")
    except Exception:
        pass


def crash_handler(exc_type, exc_value, exc_tb):
    msg = "".join(traceback.format_exception(exc_type, exc_value, exc_tb))
    _write_crash_log(msg)
    try:
        messagebox.showerror("Unexpected Error",
                             f"MKV Player crashed:\n\n{exc_value}\n\n"
                             f"Log saved to:\n{LOG_FILE}")
    except Exception:
        pass


sys.excepthook = crash_handler


# *************** DEL 03 - SETTINGS ***************

DEFAULT_SETTINGS = {
    "window_geometry" : "980x640",
    "volume"          : 80,
    "last_dir"        : "",
    "last_file"       : "",
    "subtitle_dirs"   : [],
    "panscan"         : 0.0,   # 0.0 = keep aspect (show whole frame), 1.0 = fill/crop the sides
    "panscan_migrated": False, # one-time fix: reset the old crop-by-default value
    "sub_scale"       : 0.65,  # subtitle size multiplier  ← hard-coded default
    "sub_pos"         : 102,   # vertical position 0 (top) – 150 (below bottom)  ← hard-coded default
    "sub_plain_text"  : True,  # strip bold/italic/color from subtitles
    "auto_play_next"  : True,  # auto-play next file (alphabetical) on EOF
    "skip_seconds"    : 10,    # seconds for PgUp/PgDn skip buttons
    "arrow_skip"      : 5,     # seconds for Left/Right arrow keys
    "sync_step_ms"    : 100,   # ms per keypress for sub/audio sync
    "start_fullscreen"   : True,  # start player in F11 fullscreen mode
    "fullscreen_on_play" : True,  # go fullscreen when playback starts
    "windowed_on_pause"  : True,  # shrink to window when paused
    # Default fill mode used when a film starts playing (see DEL 14):
    #   "stretch"   = fill screen, video stretched (distorted)
    #   "fill"      = fill screen, cropped, aspect ratio kept (no stretch)
    #   "letterbox" = full frame visible, black bars top/bottom as needed
    # Square videos always use "fill", regardless of this setting.
    "default_max_mode"   : "stretch",
    "movies_db"          : "",    # path to movies.db (empty = use default)
    "subtitle_dir_langs" : {},    # {dir_path: "Swedish"} language labels per sub dir
    # Optional subtitle-matching "ignore" rules.  If a film's filename starts/
    # ends with one of these, subtitles are ALSO searched for under the name
    # with that part stripped.  Exact filename match is always tried first.
    # [{"text": "Downloaded_", "type": "prefix"}, {"text": "-source", "type": "suffix"}]
    "subtitle_ignore_affixes" : [],
    # Button bar
    "btn_order"          : [],    # filled by load_settings()
    "btn_visible"        : {},    # key -> bool; missing key = visible
    # New features
    "auto_reload_subs"   : True,  # auto-reload subtitle if file changes on disk
    "hide_cursor_on_play": True,  # hide mouse cursor during fullscreen playback
    "recent_files"       : [],    # up to 5 recently opened paths
    "plan_list"          : [],    # up to 10 planned films [{"title":…,"path":…}]
    "movies_dirs"        : [],    # user-defined movie directories for Open list
    # Where the films of each database category live, e.g.
    # {"Good": ["D:/Good", "E:/Good"], "Okay": [...]} - several folders (disks)
    # per category are fine.  Used first by DB search (DEL 04g).
    "category_dirs"      : {},
    "scan_depth"         : 5,     # folder levels searched below each folder
    # Private folders.  A film inside one of these (or any subfolder below it)
    # is never written to ANY history: not the Latest list, not "Last file",
    # not the play statistics.  Its playback POSITION is still remembered, but
    # in a separate file keyed by a hash of the path, so nothing readable about
    # the film is stored anywhere.
    "private_dirs"       : [],    # folders kept out of every history
    # Hardware acceleration for video decoding
    # "auto-safe" = låt mpv välja säkert, "auto" = aggressivare, "no" = CPU only
    # "d3d11va" / "nvdec" / "vaapi" = specifik metod
    "hwdec"              : "auto-safe",
    # GPU rendering backend.  "auto" = mpv väljer, "d3d11" = säkrast på Windows,
    # "opengl" / "vulkan" = alternativ om d3d11 ger artefakter
    "gpu_api"            : "auto",
    # Frame timing.  "audio" = safe default.  "display-resample" = jämnare men
    # kan ge ghost/bubbel med fel drivrutin.  "display-vdrop" = droppar frames.
    "video_sync"         : "audio",
    # Rörelsekompenserad interpolering – stäng AV om du ser ghost/bubbel/glid
    "interpolation"      : False,
    # Framedrop-strategi när systemet inte hänger med
    # "no" = aldrig droppa  "vo" = droppa i renderer  "decoder+vo" = aggressiv
    "framedrop"          : "vo",
    # Audio track priority: list of keywords matched against lang code or title
    # (case-insensitive, substring).  First match wins; unmatched tracks last.
    "audio_lang_priority": ["swe", "svenska", "Swedish", "sv",
                            "eng", "English", "en"],
    # Live subtitle word replacement (on by default)
    "sub_live_replace"   : True,
    # Clock overlay – flash current time briefly at chosen intervals
    "clock_overlay"      : False,  # master on/off
    "clock_start_hour"   : 0,      # hour of first trigger (0–23)
    "clock_start_minute" : 0,      # minute of first trigger: 0, 15, 30 or 45
    "clock_interval_min" : 15,     # repeat interval in minutes: 15, 30 or 60
    "clock_duration_ms"  : 1000,   # how long to show the clock (500–2500 ms)
    "clock_show_time_left": False, # also show remaining playback time, e.g. "-37 min"
    # Elapsed-time overlay – flash "X min" at regular intervals
    "elapsed_overlay"      : False,       # master on/off
    "elapsed_interval_min" : 5,           # trigger every N minutes (3–60)
    "elapsed_mode"         : "wallclock", # "wallclock" = minutes since session start, "watchtime" = actual play time
    # Mark-for-deletion: renames the loaded file by adding a marker so you can
    # delete it manually later.  No file is ever deleted by the program itself.
    "delete_marker"        : "0---DELETE-",  # text added to the filename
    "delete_marker_mode"   : "prefix",       # "prefix" or "suffix"
    # ---- HDR / brightness stability ----
    # HDR video tone-mapped to an SDR screen can suddenly get much brighter or
    # darker between scenes ("flicker").  That is mpv's DYNAMIC peak detection,
    # not the file.  Keep this OFF for a stable picture; turn it on only if you
    # actually want per-scene auto-exposure.
    "hdr_peak_detect"      : False,
    # Tone-mapping curve used when converting HDR -> SDR.  "bt.2390" is a good,
    # stable default.  Other options: "hable", "mobius", "reinhard", "clip".
    "tone_mapping"         : "bt.2390",
}

# Hard-coded subtitle defaults used by the Reset button
SUB_SCALE_DEFAULT = 0.65
SUB_POS_DEFAULT   = 102


def load_settings() -> dict:
    result = dict(DEFAULT_SETTINGS)
    result["btn_order"] = list(_BTN_ORDER_DEFAULT)   # fill the placeholder
    try:
        with open(SETTINGS_FILE, "r", encoding="utf-8") as fh:
            result.update(json.load(fh))
    except Exception:
        pass
    # Ensure all defined buttons appear in btn_order (add new ones at end)
    existing = set(result.get("btn_order", []))
    for k in _BTN_ORDER_DEFAULT:
        if k not in existing:
            result["btn_order"].append(k)
    # One-time migration: older versions shipped panscan=1.0 (crop the sides) as
    # the default, which cut off the edges of the picture ("uce Willis").  Reset
    # it to 0.0 (show the whole frame) once.  A deliberate later choice is kept.
    if not result.get("panscan_migrated"):
        if abs(float(result.get("panscan", 0.0)) - 1.0) < 1e-6:
            result["panscan"] = 0.0
        result["panscan_migrated"] = True
    return result


def save_settings(s: dict) -> None:
    try:
        with open(SETTINGS_FILE, "w", encoding="utf-8") as fh:
            json.dump(s, fh, indent=2)
    except Exception:
        pass


# *************** DEL 04 - RESUME POSITIONS ***************

RESUME_TTL_DAYS = 28     # keep per-film position data this many days
RESUME_MIN_POS  = 30.0   # seconds: do not resume if less than this
RESUME_MAX_PCT  = 0.95   # do not resume if past 95% of duration


def load_resume() -> dict:
    try:
        with open(RESUME_FILE, "r", encoding="utf-8") as fh:
            return json.load(fh)
    except Exception:
        return {}


def save_resume(data: dict) -> None:
    try:
        with open(RESUME_FILE, "w", encoding="utf-8") as fh:
            json.dump(data, fh, indent=2)
    except Exception:
        pass


def clean_resume(data: dict) -> dict:
    """Remove entries older than RESUME_TTL_DAYS."""
    cutoff = datetime.datetime.now() - datetime.timedelta(days=RESUME_TTL_DAYS)
    result = {}
    for k, v in data.items():
        try:
            saved = datetime.datetime.fromisoformat(v.get("saved", "2000-01-01"))
            if saved > cutoff:
                result[k] = v
        except Exception:
            pass
    return result


def get_resume_pos(data: dict, path: str):
    """Return saved position (float seconds) if valid, else None."""
    entry = data.get(path)
    if not entry:
        return None
    pos = float(entry.get("pos", 0))
    dur = float(entry.get("dur", 0))
    if pos < RESUME_MIN_POS:
        return None
    if dur > 0 and pos >= dur * RESUME_MAX_PCT:
        return None
    return pos


def set_resume_pos(data: dict, path: str, pos: float, dur: float) -> None:
    data[path] = {
        "pos"  : round(pos, 1),
        "dur"  : round(dur, 1),
        "saved": datetime.datetime.now().isoformat(timespec="seconds"),
    }


# *************** DEL 04a - PRIVATE FOLDERS ***************
# A folder listed under settings["private_dirs"] is invisible to every history
# in the program: the Latest menu, the "Last" button, the play statistics and
# the "Latest 25%" column in the movie DB all skip its films.
#
# The playback POSITION is still kept, because resuming is the one thing that
# has to survive - but it lives in its own file and is keyed by a SHA-256 hash
# of the path, never by the path itself.  Opening that file shows a list of
# hex strings and second counts, no titles and no folders.

PRIVATE_RESUME_FILE = os.path.join(DIR_SETTINGS, "MKVPlayer_resume_private.json")


def _norm_path(p: str) -> str:
    """Absolute + case-folded, so C:\\Film and c:/film/ compare equal."""
    try:
        return os.path.normcase(os.path.abspath(p)).rstrip("\\/")
    except Exception:
        return (p or "").lower()


def is_private_path(path: str, private_dirs) -> bool:
    """True if path sits in one of the private folders, or below one."""
    if not path or not private_dirs:
        return False
    p = _norm_path(path)
    for d in private_dirs:
        d = _norm_path(d)
        # An empty entry would make os.sep match everything - skip it.
        if not d:
            continue
        if p == d or p.startswith(d + os.sep):
            return True
    return False


def private_key(path: str) -> str:
    """Hash used as the resume key for a private film (stores no title)."""
    return hashlib.sha256(_norm_path(path).encode("utf-8", "replace")).hexdigest()


def load_private_resume() -> dict:
    try:
        with open(PRIVATE_RESUME_FILE, "r", encoding="utf-8") as fh:
            return json.load(fh)
    except Exception:
        return {}


def save_private_resume(data: dict) -> None:
    try:
        with open(PRIVATE_RESUME_FILE, "w", encoding="utf-8") as fh:
            json.dump(data, fh, indent=2)
    except Exception:
        pass


# *************** DEL 04b - PER-FILM SUBTITLE SETTINGS ***************

def load_sub_settings() -> dict:
    """Load per-film subtitle overrides {path: {sub_scale, sub_pos}}."""
    try:
        with open(SUB_FILE, "r", encoding="utf-8") as fh:
            return json.load(fh)
    except Exception:
        return {}


def save_sub_settings(data: dict) -> None:
    try:
        with open(SUB_FILE, "w", encoding="utf-8") as fh:
            json.dump(data, fh, indent=2)
    except Exception:
        pass


def load_sub_sync() -> dict:
    """Load per-film subtitle sync anchor points.

    Structure:  {video_path: {"sub_path": <path>, "points": [
                     {"sub_s": float, "video_s": float, "text": str}, ...]}}
    "sub_path" is the ORIGINAL (un-resynced) subtitle file the points were
    measured against; if the film's active subtitle no longer matches,
    the sync is simply not applied (see _apply_sub_resync)."""
    try:
        with open(SUB_SYNC_FILE, "r", encoding="utf-8") as fh:
            return json.load(fh)
    except Exception:
        return {}


def save_sub_sync(data: dict) -> None:
    try:
        with open(SUB_SYNC_FILE, "w", encoding="utf-8") as fh:
            json.dump(data, fh, indent=2, ensure_ascii=False)
    except Exception:
        pass


# *************** DEL 04c - PLAY STATISTICS ***************

def load_stats() -> dict:
    """Load the persistent play-statistics database (never reset)."""
    try:
        with open(STATS_FILE, "r", encoding="utf-8") as fh:
            return json.load(fh)
    except Exception:
        return {"version": 1, "films": {}}


def save_stats_data(data: dict) -> None:
    try:
        with open(STATS_FILE, "w", encoding="utf-8") as fh:
            json.dump(data, fh, indent=2, ensure_ascii=False)
    except Exception:
        pass


def load_notes() -> dict:
    """Load per-film notes keyed by imdb_id: {imdb_id: {comment, last_seen_25pct}}."""
    try:
        with open(NOTES_FILE, "r", encoding="utf-8") as fh:
            return json.load(fh)
    except Exception:
        return {}


def save_notes(data: dict) -> None:
    try:
        with open(NOTES_FILE, "w", encoding="utf-8") as fh:
            json.dump(data, fh, indent=2, ensure_ascii=False)
    except Exception:
        pass


def _normalize_title(raw: str) -> str:
    """Normalize a filename or DB title to a comparable lowercase string.
    Strips extension, year patterns like (2010) or .2010., dots/underscores → space."""
    import re as _re2
    s = os.path.splitext(raw)[0]          # remove extension
    s = _re2.sub(r'[\._]', ' ', s)        # dots/underscores → space
    s = _re2.sub(r'\b(19|20)\d{2}\b', '', s)  # strip 4-digit years
    s = _re2.sub(r'[^\w\s]', '', s)       # strip remaining punctuation
    return ' '.join(s.lower().split())    # collapse whitespace


def build_seen25_lookup(stats_data: dict, resume_data: dict) -> dict:
    """Return {normalized_title: 'YYYY-MM-DD'} for films where a session
    reached ≥25% of the film's total duration."""
    result = {}
    for path, entry in stats_data.get("films", {}).items():
        sessions = entry.get("sessions", [])
        if not sessions:
            continue
        # Get film duration: prefer resume_data (most accurate)
        dur = float(resume_data.get(path, {}).get("dur", 0))
        if dur < 60:
            # Fallback: use the largest end_pos_s we have seen
            dur = max((s.get("end_pos_s", 0) for s in sessions), default=0)
        if dur < 60:
            continue
        threshold = dur * 0.25
        # Find the latest date where end_pos_s >= threshold
        best_date = None
        for s in sessions:
            if s.get("end_pos_s", 0) >= threshold:
                d = s.get("date", "")
                if d and (best_date is None or d > best_date):
                    best_date = d
        if best_date:
            key = _normalize_title(os.path.basename(path))
            # Keep the latest date if same title appears under multiple paths
            if key not in result or best_date > result[key]:
                result[key] = best_date
    return result


# *************** DEL 04d - SUBTITLE LIVE WORD REPLACEMENT ***************
# Replacement lists are stored as JSON files per language in SUB_REPLACE_DIR.
# E.g.  sub_replace/replace_svenska.json  →  {"nån": "någon", "nåt": "något"}
# Keys are case-insensitive; replacement preserves the original token's case.

import re as _re   # available globally; avoids repeated imports in hot path
import webbrowser  # the open-with block needs this at module level

def _lang_file_key(lang: str) -> str:
    """Normalize a language name to a safe filename key, max 40 chars."""
    return _re.sub(r'[^\w]', '_', lang.lower().strip())[:40] or "default"


def load_replace_list(lang: str) -> dict:
    """Return {original_lower: replacement_lower} dict for *lang* (empty if none).

    Keys and values are both normalised to lower-case so that _repl() can
    apply case-preservation correctly.  Comment keys (starting with '__') and
    keys that are empty after stripping are silently ignored.
    """
    path = os.path.join(SUB_REPLACE_DIR, f"replace_{_lang_file_key(lang)}.json")
    try:
        with open(path, "r", encoding="utf-8") as fh:
            raw = json.load(fh)
        result = {}
        for k, v in raw.items():
            k2 = k.strip().lower()
            if not k2 or k2.startswith("__"):
                continue
            result[k2] = str(v).strip().lower()
        return result
    except Exception:
        return {}


def save_replace_list(lang: str, data: dict) -> None:
    """Save {original: replacement} dict for *lang* (keys kept as-is)."""
    path = os.path.join(SUB_REPLACE_DIR, f"replace_{_lang_file_key(lang)}.json")
    try:
        with open(path, "w", encoding="utf-8") as fh:
            json.dump(data, fh, indent=2, ensure_ascii=False, sort_keys=True)
    except Exception:
        pass


# *************** DEL 04e - SUBTITLE MATCHING: NUMERALS + ARTICLE ***************
# Two permanent, always-on equivalence rules used by _find_all_subtitles()
# (in addition to the exact match and the "ignored affixes" match above):
#
#   1. Roman <-> Arabic numerals in a trailing sequence-number token are
#      interchangeable, e.g. "..._ii" also looks for "..._2", and
#      "..._4" also looks for "..._IV".
#
#   2. A leading article ("The_Title...") is also looked for moved to the
#      end with a comma ("Title...,_The") - the common subtitle-site
#      convention.  If the title ends in a number, that number may sit
#      either before or after the moved article - both are tried, since
#      only the actual file on disk can say which is right:
#        "The_devil_wears_prada_2"  ->  "devil_wears_prada,_The_2"
#                                        (2 = which sequel -> after "The")
#        "The_war_2031"             ->  "war_2031,_The"
#                                        (2031 = part of the title -> before "The")
#
# Only "the" is handled as an article for now - add more words to
# _ARTICLE_WORDS below if needed (e.g. "a", "an").

_ARTICLE_WORDS   = ("the",)
_ARTICLE_PATTERN = "|".join(_re.escape(w) for w in _ARTICLE_WORDS)

_ROMAN_NUMERAL_RE = _re.compile(
    r"^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$", _re.IGNORECASE)
_ROMAN_VALUES   = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
_ARABIC_TO_ROMAN = [
    (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"),
    (100,  "C"), (90,  "XC"), (50,  "L"), (40,  "XL"),
    (10,   "X"), (9,   "IX"), (5,   "V"), (4,   "IV"), (1, "I"),
]


def _roman_to_int(token: str):
    """Value of `token` if it's a well-formed Roman numeral in consistent
    case ('ii' or 'II', but not 'Ii'); otherwise None.  Mixed case is
    rejected on purpose - it's what lets a coincidental word like 'Mix'
    pass through untouched instead of being read as a numeral."""
    if not token or not (token.isupper() or token.islower()):
        return None
    up = token.upper()
    if not _ROMAN_NUMERAL_RE.match(up):
        return None
    total, prev = 0, 0
    for ch in reversed(up):
        v = _ROMAN_VALUES[ch]
        total += v if v >= prev else -v
        prev = max(prev, v)
    return total


def _int_to_roman(n: int) -> str:
    """Upper-case Roman numeral for 1-3999, else ''."""
    if not (0 < n <= 3999):
        return ""
    out = []
    for value, sym in _ARABIC_TO_ROMAN:
        cnt, n = divmod(n, value)
        out.append(sym * cnt)
    return "".join(out)


def _is_number_like(token: str) -> bool:
    return bool(token) and (token.isdigit() or _roman_to_int(token) is not None)


def _swap_trailing_numeral(name: str) -> list:
    """If the last '_'-separated token of `name` is a plain number or a
    Roman numeral, return alternate version(s) with that token swapped to
    the other form.  Both letter-cases are offered for a freshly-made
    Roman numeral, since scene names use either.  [] if nothing to swap.
    """
    head, sep, last = name.rpartition("_")
    prefix = head + sep
    if last.isdigit():
        roman = _int_to_roman(int(last))
        return [prefix + roman, prefix + roman.lower()] if roman else []
    n = _roman_to_int(last)
    return [prefix + str(n)] if n is not None else []


def _article_variants(name: str) -> list:
    """Move a leading article ('The_Title') to the trailing comma form
    ('Title,_The'), or back again - see the DEL 04e notes above for why a
    trailing number is tried on both sides of the moved article."""
    variants = []

    m = _re.match(rf"^({_ARTICLE_PATTERN})_(.+)$", name, _re.IGNORECASE)
    if m:
        article, rest = m.group(1), m.group(2)
        title, _sep, last = rest.rpartition("_")
        if title and _is_number_like(last):
            variants.append(f"{title},_{article}_{last}")   # number after "The"
        variants.append(f"{rest},_{article}")                # number (if any) stays put

    m = _re.match(rf"^(.+),_({_ARTICLE_PATTERN})_(.+)$", name, _re.IGNORECASE)
    if m:
        title, article, num = m.groups()
        variants.append(f"{article}_{title}_{num}")
    else:
        m = _re.match(rf"^(.+),_({_ARTICLE_PATTERN})$", name, _re.IGNORECASE)
        if m:
            title, article = m.groups()
            variants.append(f"{article}_{title}")

    return variants


def smart_subtitle_name_variants(name: str) -> list:
    """All alternate names reachable from `name` by repeatedly applying the
    Roman/Arabic-numeral swap and the article move, in any combination
    (e.g. swap-then-move or move-then-swap end up at the same places).
    `name` itself is never included in the result.
    """
    pool = {name}
    for _ in range(8):          # small fixed point - the state space is tiny
        added = False
        for cur in list(pool):
            for cand in _swap_trailing_numeral(cur) + _article_variants(cur):
                if cand not in pool:
                    pool.add(cand)
                    added = True
        if not added:
            break
    pool.discard(name)
    return list(pool)


# *************** DEL 04g - SMART FILM FINDER (Open list + DB search) ***************
# Everything the "Open (movies list)" search box and the "DB search" window need
# to find a film file on disk.  Pure functions + one small cache class - no Tk.
#
#  * File names are compared as WORDS, not as raw text:  case, accents,
#    '_' '.' '-' ',' ( ) ' & are ignored;  "The" is ignored ("The_Ring" =
#    "Ring,_The" = "Ring");  small Roman numerals = digits ("Rocky_II" = "Rocky_2").
#  * A year in the file name ("(2022)", "..._2022", "Name.2022.1080p...") is NOT
#    part of the title and is never required to match.
#  * "Title---Extra title" (three hyphens) = title + extra title: the file matches
#    "Title", "Extra title" or "Title Extra title".
#  * Match strength: 4 = exactly the title, 3 = exactly the title as the folder
#    name, 2 = title + release words ("..._extended", "..._(bad_quality)"),
#    1 = title + a number ("Taken_2" for "Taken") or title inside a longer name.
#    Only strength 3-4 is ever started without asking.
#  * Folders are scanned lazily, only a few levels deep, once per session
#    (cached); the category folders of the film are looked at first and the
#    other folders only if the film was not found there.
#  * The same film on two mirrored disks (same file name + same size) is ONE film.
# ToDo: persist the index between runs if a scan ever feels slow on the HDDs.

import unicodedata as _ud

FILM_VIDEO_EXT = frozenset({".mkv", ".mp4", ".avi", ".mov", ".wmv", ".flv",
                            ".webm", ".ts", ".m2ts", ".m4v", ".3gp", ".ogv"})
FILM_SKIP_DIRS = frozenset({"$recycle.bin", "system volume information",
                            "subs", "x---subs", "subtitles"})
FILM_CATEGORIES = ("Shit", "Bad", "Okay", "Good", "Best", "Rest")
FILM_SCAN_DEPTH_DEFAULT = 5     # folder levels below a registered folder
_FT_SMALL_ROMAN = {"ii": "2", "iii": "3", "iv": "4", "vi": "6",
                   "vii": "7", "viii": "8", "ix": "9"}
_FT_YEAR_RE = _re.compile(r"^(?:19|20)\d\d$")


def ft_words(text: str) -> list:
    """Comparable words of a title / file name (see DEL 04g header)."""
    s = _ud.normalize("NFKD", text or "")
    s = "".join(ch for ch in s if not _ud.combining(ch))
    s = s.casefold().replace("&", " and ")
    s = _re.sub(r"['\u2019`\u00b4]", "", s)
    words = [_FT_SMALL_ROMAN.get(w, w) for w in _re.findall(r"[^\W_]+", s)]
    kept = [w for w in words if w != "the"]
    return kept or words


def ft_parse(stem: str) -> dict:
    """Split a file/folder name (no extension) into its title parts.
    Returns {first, core, extra, year, keys}:
      first = words before '---' (year and all)          core = first without year + release junk
      extra = word lists after each '---'                keys = [core, first] without duplicates"""
    year = None
    def _grp(m):
        nonlocal year
        inner = m.group(1).strip()
        if _FT_YEAR_RE.match(inner):
            year = int(inner)
        return " "
    s = _re.sub(r"[\(\[]([^\)\]]*)[\)\]]", _grp, stem or "")
    pieces = _re.split(r"-{2,}", s)
    first = ft_words(pieces[0]) if pieces else []
    extra = [w for w in (ft_words(p) for p in pieces[1:]) if w]
    core = list(first)
    for i, w in enumerate(first):
        if i >= 1 and _FT_YEAR_RE.match(w):          # "Name 2022 1080p ..."
            if year is None:
                year = int(w)
            core = first[:i]
            break
    keys = [core] if core == first else [core, first]
    return {"first": first, "core": core, "extra": extra,
            "year": year, "keys": keys}


def ft_title_variants(title: str, extratitle: str = "") -> list:
    """Word lists a database film may be called on disk."""
    out = []
    for t in (ft_words(title),
              ft_words(extratitle) if extratitle else [],
              ft_words(f"{title} {extratitle}") if extratitle else []):
        if t and t not in out:
            out.append(t)
    return out


def _ft_has_run(words: list, run: list) -> bool:
    n = len(run)
    return n > 0 and any(words[i:i + n] == run for i in range(len(words) - n + 1))


class FilmEntry:
    """One video file found on disk, with its name already taken apart."""
    __slots__ = ("path", "name", "size", "parsed", "parent_keys",
                 "words", "flat", "year")

    def __init__(self, path, size, parent_name="", parent_is_root=True,
                 folders=()):
        """`folders` = names of the folders between the registered folder
        and the file (outermost first)."""
        self.path = path
        self.name = os.path.basename(path)
        self.size = size
        self.parsed = ft_parse(os.path.splitext(self.name)[0])
        self.parent_keys = ([] if parent_is_root or not parent_name
                            else ft_parse(parent_name)["keys"])
        words = list(ft_words(os.path.splitext(self.name)[0]))
        for fname in folders:                    # a series folder name finds its episodes
            words += ft_words(fname)
        self.words = words
        self.flat = " ".join(words)
        self.year = self.parsed["year"]


def ft_score(entry: "FilmEntry", titles: list) -> int:
    """0 = not it ... 4 = exactly this title (see DEL 04g header)."""
    best = 0
    p = entry.parsed
    for t in titles:
        if not t:
            continue
        for k in p["keys"]:
            if k == t:
                return 4
            if k[:len(t)] == t:
                rest = k[len(t):]
                best = max(best, 1 if any(w.isdigit() for w in rest) else 2)
            elif _ft_has_run(k, t):
                best = max(best, 1)
        for e in p["extra"]:
            if e == t:
                return 4
        if p["extra"] and p["first"] + p["extra"][0] == t:   # "Title---Extra"
            return 4
        for pk in entry.parent_keys:
            if pk == t:
                best = max(best, 3)
    return best


def ft_query(text: str):
    """Words of a search box text, and the year typed in it (or None).
    A year never has to match - it only floats matching films to the top."""
    words = ft_words(text)
    years = [w for w in words if _FT_YEAR_RE.match(w)]
    rest = [w for w in words if not _FT_YEAR_RE.match(w)]
    if not rest:
        return words, None
    return rest, (int(years[0]) if years else None)


def ft_filter(entries: list, query: str) -> list:
    """Entries whose name (or series folder) contains every typed word.
    Words match the START of a word first ("spe no ev"); if that finds
    nothing, they may match anywhere inside a word."""
    toks, qyear = ft_query(query)
    if not toks:
        return list(entries)
    def _all(e, anywhere):
        for t in toks:
            if anywhere:
                if t not in e.flat:
                    return False
            elif not any(w.startswith(t) for w in e.words):
                return False
        return True
    res = [e for e in entries if _all(e, False)] or \
          [e for e in entries if _all(e, True)]
    if qyear:
        res.sort(key=lambda e: 0 if e.year == qyear else 1)   # stable: A-Z kept
    return res


def ft_split_dirs(text: str) -> list:
    """'D:\\Good, E:\\Good' or 'D:\\Good; E:\\Good' -> list of folders."""
    text = (text or "").strip()
    if not text:
        return []
    if os.path.isdir(text.strip('"')):
        return [text.strip('"')]
    sep = ";" if ";" in text else ","
    out = []
    for part in text.split(sep):
        part = part.strip().strip('"').strip()
        if part and part not in out:
            out.append(part)
    return out


def ft_prune_roots(roots: list, depth: int) -> list:
    """Existing folders only, no duplicates, and no folder that a listed
    folder already covers (within `depth` levels)."""
    clean = []
    for r in roots:
        if r and os.path.isdir(r):
            n = os.path.normcase(os.path.normpath(r))
            if all(n != os.path.normcase(os.path.normpath(c)) for c in clean):
                clean.append(r)
    out = []
    for r in clean:
        n = os.path.normcase(os.path.normpath(r))
        covered = False
        for o in clean:
            on = os.path.normcase(os.path.normpath(o))
            if on != n and n.startswith(on.rstrip("\\/") + os.sep):
                levels = n[len(on):].strip("\\/").count(os.sep) + 1
                if levels <= depth:
                    covered = True
                    break
        if not covered:
            out.append(r)
    return out


class FilmIndex:
    """Session cache: folder -> its video files.  Each folder is walked once."""

    def __init__(self):
        self._lock = threading.Lock()
        self._roots = {}          # normcase root -> [FilmEntry]
        self.scans = 0            # how many folders were really walked

    def clear(self):
        with self._lock:
            self._roots.clear()

    def entries(self, root: str, depth: int) -> list:
        key = os.path.normcase(os.path.normpath(root))
        with self._lock:
            if key in self._roots:
                return self._roots[key]
            found = self._walk(root, depth)
            self._roots[key] = found
            self.scans += 1
            return found

    @staticmethod
    def _walk(root: str, depth: int) -> list:
        out = []
        stack = [(root, 0, ())]
        while stack:
            d, level, names = stack.pop()
            try:
                it = os.scandir(d)
            except OSError:
                continue
            with it:
                for e in it:
                    try:
                        if e.is_dir(follow_symlinks=False):
                            nm = e.name.lower()
                            if (level < depth and nm not in FILM_SKIP_DIRS
                                    and not nm.startswith("$")):
                                stack.append((e.path, level + 1,
                                              names + (e.name,)))
                        elif (os.path.splitext(e.name)[1].lower() in FILM_VIDEO_EXT
                              and e.is_file()):
                            out.append(FilmEntry(
                                e.path, e.stat().st_size,
                                os.path.basename(d), level == 0, names))
                    except OSError:
                        continue
        out.sort(key=lambda fe: fe.path.lower())
        return out


def ft_unique(entries: list) -> list:
    """Drop repeats: the same path, or the same file name + size (mirror disks)."""
    seen, out = set(), []
    for e in entries:
        k1 = os.path.normcase(os.path.normpath(e.path))
        k2 = (e.name.lower(), e.size)
        if k1 in seen or k2 in seen:
            continue
        seen.add(k1)
        seen.add(k2)
        out.append(e)
    return out


def ft_find(index: "FilmIndex", groups: list, titles: list, depth: int) -> list:
    """[(score, entry)] best first.  `groups` = folder lists in priority order;
    the walk stops after the first group that holds an exact (4) hit."""
    found, seen = [], set()
    for roots in groups:
        exact = False
        for r in roots:
            for e in index.entries(r, depth):
                k1 = os.path.normcase(os.path.normpath(e.path))
                k2 = (e.name.lower(), e.size)
                if k1 in seen or k2 in seen:
                    continue
                sc = ft_score(e, titles)
                if sc:
                    seen.add(k1)
                    seen.add(k2)
                    found.append((sc, e))
                    exact = exact or sc >= 4
        if exact:
            break
    found.sort(key=lambda t: (-t[0], t[1].path.lower()))
    return found


# *************** DEL 04f - SUBTITLE SYNC ENGINE (multi-point time remap) ***
# Lets the user mark 2+ places where video-time and subtitle-time should
# line up ("anchor points").  Between two anchors, every line in between is
# stretched/compressed linearly so it lands proportionally where it should;
# outside the first/last anchor, a constant shift (that anchor's own delta)
# is used.  Anchors are stored in original-subtitle-time space (SUB_SYNC_FILE)
# so they stay valid however many times the file gets re-synced.
#
# Pure functions only below - no Tk / mpv references, so they're easy to
# reason about and to unit-test in isolation.

def _s_to_srt_time(sec: float) -> str:
    """seconds -> 'HH:MM:SS,mmm' (SubRip)."""
    sec = max(0.0, sec)
    total_ms = int(round(sec * 1000))
    h, rem = divmod(total_ms, 3600000)
    m, rem = divmod(rem, 60000)
    s, ms  = divmod(rem, 1000)
    return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}"


def _ass_time_to_s(ts: str) -> float:
    """'H:MM:SS.cc' (ASS/SSA, centiseconds) -> seconds."""
    m = _re.match(r'\s*(\d+):(\d{2}):(\d{2})\.(\d{2})\s*$', ts or "")
    if not m:
        return 0.0
    h, mi, s, cs = (int(x) for x in m.groups())
    return h * 3600 + mi * 60 + s + cs / 100.0


def _s_to_ass_time(sec: float) -> str:
    """seconds -> 'H:MM:SS.cc' (ASS/SSA, centiseconds)."""
    sec = max(0.0, sec)
    total_cs = int(round(sec * 100))
    h, rem = divmod(total_cs, 360000)
    mi, rem = divmod(rem, 6000)
    s, cs = divmod(rem, 100)
    return f"{h}:{mi:02d}:{s:02d}.{cs:02d}"


_SRT_TIME_RE = _re.compile(
    r'(\d{2}):(\d{2}):(\d{2})[.,](\d{3})(\s*-->\s*)'
    r'(\d{2}):(\d{2}):(\d{2})[.,](\d{3})')

_TAG_RE = _re.compile(r'<[^>]+>|\{[^}]*\}')   # SRT <i> tags + ASS {\...} overrides


def _strip_sub_tags(text: str) -> str:
    """Remove SRT/ASS formatting tags and collapse whitespace, for display only."""
    text = text.replace("\\N", " ").replace("\\n", " ")
    text = _TAG_RE.sub("", text)
    return " ".join(text.split())


def parse_subtitle_cues(path: str) -> list:
    """Parse an .srt or .ass/.ssa file into cues for the sync dialog.

    Returns [{"start": float, "end": float, "text": str}, ...] in file
    order, in the ORIGINAL (un-resynced) file's own time space.  Returns []
    on any read error or unsupported format.
    """
    try:
        with open(path, "r", encoding="utf-8", errors="ignore") as fh:
            content = fh.read()
    except Exception:
        return []

    ext = os.path.splitext(path)[1].lower()
    cues = []

    if ext == ".srt":
        blocks = _re.split(r'\r?\n\r?\n+', content.strip())
        for block in blocks:
            lines = block.splitlines()
            for li, line in enumerate(lines):
                m = _SRT_TIME_RE.search(line)
                if not m:
                    continue
                h1, m1, s1, ms1 = (int(x) for x in m.groups()[0:4])
                h2, m2, s2, ms2 = (int(x) for x in m.groups()[5:9])
                start = h1 * 3600 + m1 * 60 + s1 + ms1 / 1000.0
                end   = h2 * 3600 + m2 * 60 + s2 + ms2 / 1000.0
                text  = _strip_sub_tags(" ".join(lines[li + 1:]))
                cues.append({"start": start, "end": end, "text": text})
                break

    elif ext in (".ass", ".ssa"):
        for line in content.splitlines():
            if not line.startswith("Dialogue:"):
                continue
            parts = line[len("Dialogue:"):].split(",", 9)
            if len(parts) != 10:
                continue
            try:
                start = _ass_time_to_s(parts[1])
                end   = _ass_time_to_s(parts[2])
            except Exception:
                continue
            cues.append({"start": start, "end": end,
                        "text": _strip_sub_tags(parts[9])})

    return cues


def build_sync_remap(points: list):
    """Build f(original_sub_time) -> corrected_time from 1+ anchor points.

    points: [{"sub_s": float, "video_s": float}, ...] (any order, any count >= 1)
    1 point  -> constant shift (that point's own delta) everywhere.
    2+ points -> piecewise-linear between consecutive anchors (sorted by
                 sub_s); constant shift (nearest anchor's delta) before the
                 first and after the last anchor.
    """
    pts = sorted(points, key=lambda p: p["sub_s"])
    # Collapse near-duplicate sub_s values (keep the later one wins)
    dedup = []
    for p in pts:
        if dedup and abs(p["sub_s"] - dedup[-1]["sub_s"]) < 1e-6:
            dedup[-1] = p
        else:
            dedup.append(p)
    pts = dedup

    if len(pts) == 1:
        shift = pts[0]["video_s"] - pts[0]["sub_s"]
        return lambda t: max(0.0, t + shift)

    def f(t: float) -> float:
        if t <= pts[0]["sub_s"]:
            return max(0.0, t + (pts[0]["video_s"] - pts[0]["sub_s"]))
        if t >= pts[-1]["sub_s"]:
            return max(0.0, t + (pts[-1]["video_s"] - pts[-1]["sub_s"]))
        for i in range(len(pts) - 1):
            s0, v0 = pts[i]["sub_s"],     pts[i]["video_s"]
            s1, v1 = pts[i + 1]["sub_s"], pts[i + 1]["video_s"]
            if s0 <= t <= s1:
                if abs(s1 - s0) < 1e-6:
                    return max(0.0, v0)
                frac = (t - s0) / (s1 - s0)
                return max(0.0, v0 + frac * (v1 - v0))
        return t   # unreachable in practice

    return f


def invert_sync_remap(points: list, video_s: float) -> float:
    """Inverse of build_sync_remap(): best-guess ORIGINAL sub time for a
    given video time, using the same anchors.  Used only to pre-select a
    sensible line in the sync dialog when marking a new point - not used
    for the actual subtitle rewrite (which always goes sub_s -> video_s)."""
    if not points:
        return video_s
    pts = sorted(points, key=lambda p: p["video_s"])
    if len(pts) == 1:
        return max(0.0, video_s - (pts[0]["video_s"] - pts[0]["sub_s"]))
    if video_s <= pts[0]["video_s"]:
        return max(0.0, video_s - (pts[0]["video_s"] - pts[0]["sub_s"]))
    if video_s >= pts[-1]["video_s"]:
        return max(0.0, video_s - (pts[-1]["video_s"] - pts[-1]["sub_s"]))
    for i in range(len(pts) - 1):
        v0, s0 = pts[i]["video_s"],     pts[i]["sub_s"]
        v1, s1 = pts[i + 1]["video_s"], pts[i + 1]["sub_s"]
        if v0 <= video_s <= v1:
            if abs(v1 - v0) < 1e-6:
                return max(0.0, s0)
            frac = (video_s - v0) / (v1 - v0)
            return max(0.0, s0 + frac * (s1 - s0))
    return video_s


def rewrite_subtitle_times(path: str, remap) -> "str | None":
    """Return new file content for *path* with every start/end time passed
    through remap(t).  None if the file can't be read or the format is
    unsupported.  Text, indices, styling - everything else - is untouched."""
    try:
        with open(path, "r", encoding="utf-8", errors="ignore") as fh:
            content = fh.read()
    except Exception:
        return None

    return _rewrite_sub_text(content, os.path.splitext(path)[1].lower(), remap)


def _rewrite_sub_text(content: str, ext: str, remap) -> "str | None":
    """The text-only core of rewrite_subtitle_times(): every start/end time in
    *content* (an .srt or .ass/.ssa body) goes through remap(t).  None for an
    unsupported *ext*.  Line endings are left exactly as they are."""
    if ext == ".srt":
        def _sub(m):
            h1, m1, s1, ms1 = (int(x) for x in m.groups()[0:4])
            arrow = m.group(5)
            h2, m2, s2, ms2 = (int(x) for x in m.groups()[5:9])
            start = h1 * 3600 + m1 * 60 + s1 + ms1 / 1000.0
            end   = h2 * 3600 + m2 * 60 + s2 + ms2 / 1000.0
            return _s_to_srt_time(remap(start)) + arrow + _s_to_srt_time(remap(end))
        return _SRT_TIME_RE.sub(_sub, content)

    if ext in (".ass", ".ssa"):
        out = []
        for line in content.splitlines(keepends=True):
            if line.startswith("Dialogue:"):
                parts = line.split(",", 9)
                if len(parts) == 10:
                    try:
                        start = _ass_time_to_s(parts[1])
                        end   = _ass_time_to_s(parts[2])
                        parts[1] = _s_to_ass_time(remap(start))
                        parts[2] = _s_to_ass_time(remap(end))
                        out.append(",".join(parts))
                        continue
                    except Exception:
                        pass
            out.append(line)
        return "".join(out)

    return None   # unsupported format


# ---- Writing a corrected subtitle back to disk (used by the S key and by the
# sync dialog's "update file" button) ------------------------------------------

def read_sub_text(path: str):
    """Read a subtitle file WITHOUT losing anything.  Returns (text, encoding)
    or None when the file can't be read.  The encoding is detected (BOM ->
    UTF-8-SIG / UTF-16, else UTF-8, else Windows-1252, else Latin-1) so the
    file can be written back in the very same encoding: a cp1252 file with
    å/ä/ö stays cp1252.  (The display reader above uses errors="ignore",
    which would silently drop those letters.)  Line endings are kept."""
    try:
        with open(path, "rb") as fh:
            raw = fh.read()
    except Exception:
        return None
    if raw.startswith((b"\xff\xfe", b"\xfe\xff")):
        enc = "utf-16"
    elif raw.startswith(b"\xef\xbb\xbf"):
        enc = "utf-8-sig"
    else:
        enc = "utf-8"
    try:
        return raw.decode(enc), enc
    except UnicodeDecodeError:
        pass
    try:
        return raw.decode("cp1252"), "cp1252"
    except UnicodeDecodeError:
        return raw.decode("latin-1"), "latin-1"


def backup_subtitle_file(path: str) -> str:
    """Copy *path* to BACKUP-<name> in the same folder (BACKUP-2-<name>,
    BACKUP-3-<name> ... if earlier backups exist, so the very first one - the
    true original - is never overwritten).  Returns the backup's path."""
    folder, name = os.path.split(path)
    n = 1
    while True:
        prefix = "BACKUP-" if n == 1 else f"BACKUP-{n}-"
        target = os.path.join(folder, prefix + name)
        if not os.path.exists(target):
            break
        n += 1
    shutil.copy2(path, target)
    return target


def bake_subtitle_file(path: str, remap):
    """Rewrite every time in the subtitle file *path* through remap(t), after
    saving the old file as BACKUP-<name>.  Returns (backup_path, None) on
    success or (None, error_text) - on any error the original file is left
    exactly as it was (the new content is written to a temp file and swapped
    in with os.replace, so a cut-off write can't corrupt the subtitle)."""
    ext = os.path.splitext(path)[1].lower()
    if ext not in (".srt", ".ass", ".ssa"):
        return None, "Only .srt / .ass / .ssa subtitle files can be rewritten."
    got = read_sub_text(path)
    if got is None:
        return None, "Could not read the subtitle file."
    text, enc = got
    new_text = _rewrite_sub_text(text, ext, remap)
    if new_text is None:
        return None, "Could not understand the subtitle format."
    try:
        backup = backup_subtitle_file(path)
    except Exception as exc:
        return None, f"Could not make the backup - nothing was changed:\n{exc}"
    tmp = path + ".tmp-sync"
    try:
        with open(tmp, "wb") as fh:
            fh.write(new_text.encode(enc))
        os.replace(tmp, path)
    except Exception as exc:
        for leftover in (tmp, backup):
            try:
                os.remove(leftover)
            except Exception:
                pass
        return None, f"Could not write the subtitle file:\n{exc}"
    return backup, None


# *************** DEL 05 - COLORS & HELPERS ***************

C_BG       = "#111118"    # main window background
C_BG2      = "#1a1a2a"    # control bar background
C_BG3      = "#0f3460"    # dialog header
C_VIDEO_BG = "#000000"    # behind the video
C_ACCENT   = "#e94560"    # highlights / links
C_FG       = "#eaeaea"    # primary text
C_FG_DIM   = "#666677"    # muted text
C_SEP      = "#2a2a42"    # separator lines
C_TROUGH   = "#2a2a42"    # slider troughs
C_BTN      = "grey25"     # button normal colour  <- change here
C_BTN_HOV  = "grey35"     # button hover colour   <- change here

# Pixels from bottom where the control bar becomes visible
CTRL_SHOW_ZONE = 110
# Milliseconds before controls auto-hide after cursor leaves zone
CTRL_HIDE_MS   = 2200


def no_blink(w) -> None:
    """Disable cursor blink on Entry / Text widgets."""
    try:
        w.configure(insertofftime=0, insertontime=9999999)
    except Exception:
        pass


def fmt_time(s) -> str:
    """Seconds -> 'H:MM:SS' or 'M:SS'."""
    if s is None or s < 0:
        return "0:00"
    s = int(s)
    h, r = divmod(s, 3600)
    m, sec = divmod(r, 60)
    return f"{h}:{m:02d}:{sec:02d}" if h else f"{m}:{sec:02d}"


def _place_top_center(top: tk.Toplevel, width: int, height: int) -> None:
    """Position a Toplevel centered horizontally on screen, near the top."""
    top.update_idletasks()
    sw = top.winfo_screenwidth()
    x = max(0, (sw - width) // 2)
    top.geometry(f"{width}x{height}+{x}+30")


def auto_close_popup(root: tk.Tk, message: str, delay_ms: int = 1000,
                     bg: str = None) -> None:
    """Borderless notification that vanishes automatically."""
    bg = bg or C_BG3
    top = tk.Toplevel(root)
    top.overrideredirect(True)
    top.configure(bg=bg)
    root.update_idletasks()
    pw, ph = 360, 52
    rx, ry = root.winfo_rootx(), root.winfo_rooty()
    rw, rh = root.winfo_width(),  root.winfo_height()
    top.geometry(f"{pw}x{ph}+{rx+(rw-pw)//2}+{ry+(rh-ph)//2}")
    tk.Label(top, text=message, bg=bg, fg="white",
             font=("Segoe UI", 10)).pack(expand=True)
    top.after(delay_ms, top.destroy)


# Shared keyword args for toolbar buttons
_BTN = dict(
    bg=C_BTN, fg="white",                   # bg = grey25  <- change
    activebackground=C_BTN_HOV,
    activeforeground="white",
    relief="flat", padx=10, pady=5,
    font=("Segoe UI", 10), cursor="hand2",
)


def _bind_hover(b: tk.Button,
                n: str = C_BTN,
                h: str = C_BTN_HOV) -> None:
    b.bind("<Enter>", lambda _: b.configure(bg=h))
    b.bind("<Leave>", lambda _: b.configure(bg=n))


# ── Canonical button definitions (key → display label) ──────────────────────
_BTN_DEFS = {
    "open_list":  "Open",
    "open":       "Browse",
    "last":       "Last",
    "latest":     "Latest ▾",
    "db":         "🎬 DB",
    "stats":      "📊 Stats",
    "settings":   "⚙",
    "keyboard":   "⌨",
    "stop":       "Stop",
    "rw":         "<< -10s",    # label updated dynamically
    "play":       "Play",
    "fw":         "+10s >>",    # label updated dynamically
    "next":       "Next ▶▶",
    "sub":        "Sub ▾",      # label updated dynamically
    "audio":      "Audio ▾",   # label updated dynamically
    "plan":       "Plan 📋",
    "mark_del":   "🗑 Mark",
    "fullscreen": "Fullscreen",
    "close":      "Close",
    "bluetooth":  "🎧 Connect",  # Bluetooth headphones (DEL 21); label updated dynamically
}
# Default order (separators auto-inserted between groups)
_BTN_ORDER_DEFAULT = [
    "open_list", "open", "last", "latest", "db", "stats", "settings",
    "keyboard",
    "stop", "rw", "play", "fw", "next",
    "sub", "audio", "plan", "mark_del",
    "fullscreen", "close",
    "bluetooth",                 # far right (2026-11-09)
]
# Group membership – sep drawn when crossing group boundary
_BTN_GROUPS = {
    "open_list": 0, "open": 0, "last": 0, "latest": 0, "db": 0,
    "stats": 0, "settings": 0, "keyboard": 0,
    "stop": 1, "rw": 1, "play": 1, "fw": 1, "next": 1,
    "sub": 2, "audio": 2, "plan": 2, "mark_del": 2,
    "fullscreen": 3, "close": 3,
    "bluetooth": 4,
}
# Labels managed elsewhere – don't overwrite on rebuild
_BTN_DYNAMIC_LABEL = {"rw", "fw", "play", "sub", "audio", "bluetooth"}


# *************** DEL 20 - VIRTUAL KEYBOARD ***************

class VirtualKeyboard(tk.Toplevel):
    """
    Musklickbart skärmtangentbord.
    Infogar text i det Entry / Text-fält som senast hade fokus.
    Stödjer svenska (default), engelska och ryska layouter.
    """

    _LAYOUTS = {
        "SV": ("Svenska", [
            ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-"],
            ["q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "å"],
            ["a", "s", "d", "f", "g", "h", "j", "k", "l", "ö", "ä"],
            ["z", "x", "c", "v", "b", "n", "m", ",", ".", "_"],
        ]),
        "EN": ("English", [
            ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-"],
            ["q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "[", "]"],
            ["a", "s", "d", "f", "g", "h", "j", "k", "l", ";", "'"],
            ["z", "x", "c", "v", "b", "n", "m", ",", ".", "/"],
        ]),
        "RU": ("Ryska", [
            ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"],
            ["й", "ц", "у", "к", "е", "н", "г", "ш", "щ", "з", "х", "ъ"],
            ["ф", "ы", "в", "а", "п", "р", "о", "л", "д", "ж", "э", "ё"],
            ["я", "ч", "с", "м", "и", "т", "ь", "б", "ю"],
        ]),
    }

    # Shift-map: lowercase → shifted character
    _SHIFT_MAP = {
        # Siffror / tecken – Svensk layout
        "1": "!", "2": '"', "3": "#", "4": "¤", "5": "%",
        "6": "&", "7": "/", "8": "(", "9": ")", "0": "=",
        "-": "?", ",": ";", ".": ":", "_": "-",
        # Engelska extra
        "[": "{", "]": "}", ";": ":", "'": '"', "/": "?",
        # Ryska versaler
        "й":"Й","ц":"Ц","у":"У","к":"К","е":"Е","н":"Н","г":"Г",
        "ш":"Ш","щ":"Щ","з":"З","х":"Х","ъ":"Ъ","ф":"Ф","ы":"Ы",
        "в":"В","а":"А","п":"П","р":"Р","о":"О","л":"Л","д":"Д",
        "ж":"Ж","э":"Э","ё":"Ё","я":"Я","ч":"Ч","с":"С","м":"М",
        "и":"И","т":"Т","ь":"Ь","б":"Б","ю":"Ю",
    }
    # Alla latinska bokstäver → versaler automatiskt
    for _ch in "abcdefghijklmnopqrstuvwxyzåäö":
        _SHIFT_MAP[_ch] = _ch.upper()

    def __init__(self, root: tk.Tk, default_lang: str = "SV"):
        super().__init__(root)
        self.title("Tangentbord")
        self.configure(bg=C_BG2)
        self.resizable(False, False)
        self.attributes("-topmost", True)
        self.protocol("WM_DELETE_WINDOW", self.hide)

        self._target     = None   # senast fokuserade Entry / Text
        self._shift      = False
        self._lang       = default_lang
        self._key_btns   = {}     # char → Button (byggs om vid layoutbyte)
        self._shift_btn  = None
        self._lang_btns  = {}

        self._build()
        self.withdraw()   # dold tills _toggle_vkb visar den

    # ── Publik API ─────────────────────────────────────────────────────────

    def set_target(self, widget) -> None:
        """Kallas av MKVPlayer när ett Entry/Text-fält får fokus."""
        self._target = widget

    def show(self) -> None:
        self.deiconify()
        self.lift()

    def hide(self) -> None:
        self.withdraw()

    def toggle(self) -> None:
        if self.state() == "withdrawn":
            self.show()
        else:
            self.hide()

    # ── Bygg / återbygg UI ────────────────────────────────────────────────

    def _build(self) -> None:
        for w in self.winfo_children():
            w.destroy()
        self._key_btns.clear()
        self._shift = False

        # Gemensamma stilar
        K = dict(
            bg="grey28", fg="white",
            activebackground="grey45", activeforeground="white",
            relief="flat", font=("Segoe UI", 11),
            cursor="hand2", width=3, padx=1, pady=3,
        )
        K_WIDE  = dict(K, width=10)   # Mellanslag
        K_MED   = dict(K, width=5)    # Backspace, Rensa, Enter
        K_SHIFT = dict(K, width=5)    # Shift-knapp
        K_LANG  = dict(
            bg=C_BG3, fg="white",
            activebackground="#1a4a80", activeforeground="white",
            relief="flat", font=("Segoe UI", 9),
            cursor="hand2", padx=8, pady=3,
        )

        # ── Layoutrad ────────────────────────────────────────────────────
        lang_bar = tk.Frame(self, bg=C_BG)
        lang_bar.pack(fill="x", padx=4, pady=(4, 2))
        tk.Label(lang_bar, text="Layout:", bg=C_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(side="left", padx=(2, 4))

        self._lang_btns = {}
        for code, (name, _) in self._LAYOUTS.items():
            b = tk.Button(lang_bar, text=name,
                          command=lambda c=code: self._set_lang(c), **K_LANG)
            b.pack(side="left", padx=2)
            self._lang_btns[code] = b
        self._update_lang_btns()

        # ── Tangentraderna ────────────────────────────────────────────────
        _, rows = self._LAYOUTS[self._lang]
        key_frame = tk.Frame(self, bg=C_BG2)
        key_frame.pack(padx=4, pady=2)

        for row in rows:
            rf = tk.Frame(key_frame, bg=C_BG2)
            rf.pack(fill="x", pady=1)
            for ch in row:
                b = tk.Button(rf, text=ch,
                              command=lambda c=ch: self._press(c),
                              **K)
                b.pack(side="left", padx=1)
                self._key_btns[ch] = b

        # ── Aktionsrad: Shift  Mellanslag  Backspace  Rensa  Enter ────────
        act = tk.Frame(key_frame, bg=C_BG2)
        act.pack(fill="x", pady=(3, 1))

        self._shift_btn = tk.Button(act, text="Shift ↑",
                                    command=self._toggle_shift, **K_SHIFT)
        self._shift_btn.pack(side="left", padx=1)

        tk.Button(act, text="Mellanslag",
                  command=lambda: self._press(" "), **K_WIDE).pack(side="left", padx=1)

        tk.Button(act, text="⌫ Bakåt",
                  command=self._backspace, **K_MED).pack(side="left", padx=1)

        tk.Button(act, text="Rensa",
                  command=self._clear_target, **K_MED).pack(side="left", padx=1)

        tk.Button(act, text="↵ Enter",
                  command=self._send_return, **K_MED).pack(side="left", padx=1)

    def _set_lang(self, code: str) -> None:
        self._lang = code
        self._build()

    def _update_lang_btns(self) -> None:
        for code, b in self._lang_btns.items():
            if code == self._lang:
                b.configure(bg=C_ACCENT, activebackground=C_ACCENT)
            else:
                b.configure(bg=C_BG3, activebackground="#1a4a80")

    # ── Tangentaktioner ───────────────────────────────────────────────────

    def _press(self, char: str) -> None:
        if self._shift:
            char = self._SHIFT_MAP.get(char,
                   char.upper() if char.isalpha() else char)
            # Stäng av shift efter en tryckning (som ett riktigt tangentbord)
            self._shift = False
            if self._shift_btn:
                self._shift_btn.configure(bg="grey28")
            self._refresh_labels()
        self._insert(char)

    def _toggle_shift(self) -> None:
        self._shift = not self._shift
        if self._shift_btn:
            self._shift_btn.configure(
                bg=C_ACCENT if self._shift else "grey28")
        self._refresh_labels()

    def _refresh_labels(self) -> None:
        """Uppdatera alla tangentetiketter beroende på shift-läge."""
        _, rows = self._LAYOUTS[self._lang]
        for row in rows:
            for ch in row:
                b = self._key_btns.get(ch)
                if b:
                    lbl = (self._SHIFT_MAP.get(ch,
                           ch.upper() if ch.isalpha() else ch)
                           if self._shift else ch)
                    b.configure(text=lbl)

    def _insert(self, char: str) -> None:
        w = self._target
        if not w:
            return
        try:
            if isinstance(w, tk.Text):
                w.insert("insert", char)
            else:   # tk.Entry
                idx = w.index("insert")
                w.insert(idx, char)
        except Exception:
            pass

    def _backspace(self) -> None:
        w = self._target
        if not w:
            return
        try:
            if isinstance(w, tk.Text):
                w.delete("insert-1c", "insert")
            else:
                idx = w.index("insert")
                if idx > 0:
                    w.delete(idx - 1, idx)
        except Exception:
            pass

    def _clear_target(self) -> None:
        w = self._target
        if not w:
            return
        try:
            if isinstance(w, tk.Text):
                w.delete("1.0", "end")
            else:
                w.delete(0, "end")
        except Exception:
            pass

    def _send_return(self) -> None:
        """Skicka Return-händelse till målfältet (triggar t.ex. sökfunktioner)."""
        w = self._target
        if not w:
            return
        try:
            w.event_generate("<Return>")
        except Exception:
            pass


# *************** DEL 20b - SUBTITLE SYNC DIALOG ***************
# Non-modal Toplevel (no grab_set) so the main window - including its own
# seek bar / space-bar play-pause - stays fully usable while this is open;
# the user is meant to bounce between "look at another spot in the film"
# and "mark it here" without closing the dialog.  See DEL 04f for the pure
# time-remap math and DEL 04b's SUB_SYNC_FILE for persistence.

class SubSyncDialog(tk.Toplevel):
    """
    Workflow:
      1. Opens already paused, with the nearest subtitle line pre-selected.
      2. User scrolls/clicks the list (mouse + scrollbar) to the line that's
         actually being spoken, nudges playback with the +/- buttons if
         needed, then clicks "Correct" to save that as an anchor point.
      3. "Mark point here" can be pressed again after seeking elsewhere in
         the film (via this dialog's own transport, or the main window's)
         to add further anchor points - 2 or more give a stretched/
         compressed mapping between them instead of one flat shift.
    """

    def __init__(self, app, sub_path: str, cues: list):
        super().__init__(app.root)
        self.app      = app
        self.sub_path = sub_path
        self.cues     = cues
        self._closing = False
        self._tick_id = None

        existing = app.sub_sync.get(app._current_file, {})
        self.points = (list(existing.get("points", []))
                      if existing.get("sub_path") == sub_path else [])

        self.title("Subtitle Sync")
        self.configure(bg=C_BG)
        _place_top_center(self, 640, 640)
        self.minsize(520, 480)
        self.transient(app.root)     # stays above the main window, not modal
        self.protocol("WM_DELETE_WINDOW", self._on_close)
        self.bind("<Escape>", lambda _: self._on_close())

        self._build()
        self._mark_here()            # first candidate = wherever playback is now
        self._tick()

    # ── UI ──────────────────────────────────────────────────────────────

    def _build(self) -> None:
        _B2 = dict(bg=C_BTN, fg="white", activebackground=C_BTN_HOV,
                   activeforeground="white", relief="flat",
                   padx=8, pady=4, font=("Segoe UI", 9), cursor="hand2")

        def _btn(parent, label, cmd, **kw):
            b = tk.Button(parent, text=label, command=cmd, **{**_B2, **kw})
            _bind_hover(b, kw.get("bg", C_BTN), C_BTN_HOV)
            b.pack(side="left", padx=2)
            return b

        hdr = tk.Frame(self, bg=C_BG3)
        hdr.pack(fill="x")
        tk.Label(hdr, text=f"  🔧 Sync subtitle  —  {os.path.basename(self.sub_path)}",
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 10, "bold")).pack(
                     side="left", pady=8)

        tk.Label(self, bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 justify="left", wraplength=610,
                 text="Pause where you hear speech, pick the matching line below, "
                      "adjust if needed, then click \u2713 Correct. Mark 2 or more "
                      "points and the lines between them are stretched/compressed "
                      "to match. You can still use the main window's seek bar / "
                      "space bar while this is open."
                 ).pack(fill="x", padx=10, pady=(6, 4))

        # ---- Transport row ----
        trans = tk.Frame(self, bg=C_BG)
        trans.pack(fill="x", padx=10, pady=(0, 4))
        self.time_lbl = tk.Label(trans, text="Video position: 0:00",
                                 bg=C_BG, fg=C_ACCENT, font=("Segoe UI", 10, "bold"))
        self.time_lbl.pack(side="left", padx=(0, 10))
        _btn(trans, "⏵/⏸", lambda: self.app._toggle_play())
        _btn(trans, "-1s",   lambda: self._nudge(-1.0))
        _btn(trans, "-0.1s", lambda: self._nudge(-0.1))
        _btn(trans, "+0.1s", lambda: self._nudge(+0.1))
        _btn(trans, "+1s",   lambda: self._nudge(+1.0))
        _btn(trans, "▶ Preview 3s", self._preview)

        mark_row = tk.Frame(self, bg=C_BG)
        mark_row.pack(fill="x", padx=10, pady=(0, 6))
        _btn(mark_row, "⚑ Mark point here  (pause + jump to nearest line)",
            self._mark_here, bg=C_ACCENT)

        # ---- Subtitle line list ----
        tk.Label(self, text="  Subtitle lines  (click the one being spoken)",
                 bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 8, "italic")).pack(
                     anchor="w", padx=10)
        list_frame = tk.Frame(self, bg=C_BG)
        list_frame.pack(fill="both", expand=True, padx=10, pady=(2, 4))
        sb = tk.Scrollbar(list_frame, orient="vertical")
        sb.pack(side="right", fill="y")
        self.lb = tk.Listbox(list_frame, bg=C_BG2, fg=C_FG,
                             selectbackground=C_BG3, selectforeground=C_ACCENT,
                             activestyle="none", font=("Consolas", 9),
                             relief="flat", bd=0, height=12,
                             yscrollcommand=sb.set)
        self.lb.pack(side="left", fill="both", expand=True)
        sb.config(command=self.lb.yview)
        for c in self.cues:
            self.lb.insert("end", f"  {fmt_time(c['start']):>8}   {c['text'][:80]}")
        self.lb.bind("<<ListboxSelect>>", lambda _e: self._update_delta_label())

        self.delta_lbl = tk.Label(self, text="", bg=C_BG, fg=C_FG,
                                  font=("Segoe UI", 9), wraplength=610,
                                  justify="left")
        self.delta_lbl.pack(fill="x", padx=10, pady=(0, 4))

        _btn(self, "✓  Correct — save this point", self._commit_from_selection,
            bg=C_ACCENT).pack(anchor="w", padx=10, pady=(0, 8))

        # ---- Confirmed anchor points ----
        tk.Label(self, text="  Saved sync points for this film",
                 bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 8, "italic")).pack(
                     anchor="w", padx=10)
        pts_frame = tk.Frame(self, bg=C_BG)
        pts_frame.pack(fill="x", padx=10, pady=(2, 4))
        self.pts_lb = tk.Listbox(pts_frame, bg=C_BG2, fg=C_FG,
                                 selectbackground=C_BG3, selectforeground=C_ACCENT,
                                 activestyle="none", font=("Consolas", 9),
                                 relief="flat", bd=0, height=4)
        self.pts_lb.pack(side="left", fill="both", expand=True)
        self._refresh_points_list()

        btn_row = tk.Frame(self, bg=C_BG)
        btn_row.pack(fill="x", padx=10, pady=(0, 8))
        _btn(btn_row, "✕ Remove selected point", self._remove_selected_point)
        _btn(btn_row, "🗑 Reset all points", self._reset_all)
        _btn(btn_row, "💾 Uppdatera undertextfil", self._write_to_file, bg=C_ACCENT)
        _btn(btn_row, "Close", self._on_close)

    # ── Live updates ────────────────────────────────────────────────────

    def _tick(self) -> None:
        if self._closing:
            return
        p = self.app._player
        if p is not None:
            try:
                t = float(p.time_pos or 0.0)
                self.time_lbl.configure(
                    text=f"Video position: {fmt_time(t)}   ({t:.3f}s)")
            except Exception:
                pass
        self._update_delta_label()
        self._tick_id = self.after(150, self._tick)

    def _current_video_s(self) -> float:
        p = self.app._player
        if p is None:
            return 0.0
        try:
            return float(p.time_pos or 0.0)
        except Exception:
            return 0.0

    def _update_delta_label(self) -> None:
        sel = self.lb.curselection()
        if not sel:
            self.delta_lbl.configure(
                text="No line selected - click one in the list above.")
            return
        cue = self.cues[sel[0]]
        video_s = self._current_video_s()
        delta = video_s - cue["start"]
        self.delta_lbl.configure(
            text=f"Selected line starts at {fmt_time(cue['start'])}  |  "
                f"video is at {fmt_time(video_s)}  |  \u0394 = {delta:+.3f}s")

    # ── Transport helpers ───────────────────────────────────────────────

    def _nudge(self, step: float) -> None:
        new_pos = max(0.0, self._current_video_s() + step)
        self.app._seek_abs(new_pos)

    def _preview(self) -> None:
        p = self.app._player
        if p is None:
            return
        start = max(0.0, self._current_video_s() - 1.0)
        self.app._seek_abs(start)
        try:
            p.pause = False
        except Exception:
            pass
        self.after(3000, self._preview_stop)

    def _preview_stop(self) -> None:
        p = self.app._player
        if p is not None:
            try:
                p.pause = True
            except Exception:
                pass

    def _nearest_cue_index(self, t: float) -> int:
        best_i, best_d = 0, None
        for i, c in enumerate(self.cues):
            d = abs(c["start"] - t)
            if best_d is None or d < best_d:
                best_i, best_d = i, d
        return best_i

    def _mark_here(self) -> None:
        """Pause and pre-select the subtitle line nearest the current
        position (using the existing anchors' inverse mapping as a
        best guess, so it starts close and only needs small adjusting)."""
        p = self.app._player
        if p is not None:
            try:
                p.pause = True
            except Exception:
                pass
        video_s = self._current_video_s()
        guess_sub_s = invert_sync_remap(self.points, video_s) if self.points else video_s
        idx = self._nearest_cue_index(guess_sub_s)
        self.lb.selection_clear(0, "end")
        self.lb.selection_set(idx)
        self.lb.see(idx)
        self.lb.activate(idx)
        self._update_delta_label()

    # ── Anchor point management ─────────────────────────────────────────

    def _commit_from_selection(self) -> None:
        sel = self.lb.curselection()
        if not sel:
            auto_close_popup(self.app.root, "Select a subtitle line first.")
            return
        cue = self.cues[sel[0]]
        self._commit_point(cue["start"], self._current_video_s(), cue["text"])

    def _commit_point(self, sub_s: float, video_s: float, text: str) -> None:
        REPLACE_THRESHOLD = 2.0   # seconds - re-marking near an old anchor updates it
        for p in self.points:
            if abs(p["sub_s"] - sub_s) < REPLACE_THRESHOLD:
                p.update(sub_s=sub_s, video_s=video_s, text=text[:60])
                break
        else:
            self.points.append({"sub_s": sub_s, "video_s": video_s, "text": text[:60]})
        self.points.sort(key=lambda p: p["sub_s"])
        self._save_points()
        self._refresh_points_list()
        auto_close_popup(self.app.root,
                         f"\u2713 Sync point saved  ({len(self.points)} total)",
                         delay_ms=1000)

    def _save_points(self) -> None:
        if self.points:
            self.app.sub_sync[self.app._current_file] = {
                "sub_path": self.sub_path,
                "points": self.points,
            }
        else:
            self.app.sub_sync.pop(self.app._current_file, None)
        save_sub_sync(self.app.sub_sync)
        self.app._reload_subs()      # apply immediately

    def _refresh_points_list(self) -> None:
        self.pts_lb.delete(0, "end")
        for p in self.points:
            delta = p["video_s"] - p["sub_s"]
            self.pts_lb.insert(
                "end",
                f"  sub {fmt_time(p['sub_s'])} \u2192 video {fmt_time(p['video_s'])}"
                f"   (\u0394 {delta:+.2f}s)   {p.get('text', '')[:40]}")

    def _remove_selected_point(self) -> None:
        sel = self.pts_lb.curselection()
        if not sel:
            return
        del self.points[sel[0]]
        self._save_points()
        self._refresh_points_list()

    def _reset_all(self) -> None:
        if not self.points:
            return
        if not messagebox.askyesno("Reset sync",
                                   "Remove all sync points for this film?",
                                   parent=self):
            return
        self.points = []
        self._save_points()
        self._refresh_points_list()

    # ── Write correction into the real subtitle file ────────────────────

    def _write_to_file(self) -> None:
        """Bake the current sync correction directly into the subtitle
        file on disk, then clear this film's saved sync state (anchor
        points + the player's temp copy) so the now-already-correct file
        isn't resynced a second time on top of itself the next time this
        film is opened."""
        if not self.points:
            auto_close_popup(self.app.root, "Inga synkpunkter att skriva.")
            return
        if not messagebox.askyesno(
                "Update subtitle file",
                f"Rewrite the times directly in:\n{os.path.basename(self.sub_path)}\n\n"
                f"The old file is kept as BACKUP-{os.path.basename(self.sub_path)}.",
                parent=self):
            return

        remap = build_sync_remap(self.points)
        # Backup first, same encoding back (DEL 04f: bake_subtitle_file).
        _backup, err = bake_subtitle_file(self.sub_path, remap)
        if err:
            messagebox.showerror("Error", err, parent=self)
            return

        # Filen har nu de korrigerade tiderna på riktigt - rensa sparade
        # synkpunkter och spelarens tempkopia för den här filmen, annars
        # skulle korrigeringen appliceras en gång till ovanpå sig själv
        # nästa gång filmen öppnas.
        self.points = []
        self.app.sub_sync.pop(self.app._current_file, None)
        save_sub_sync(self.app.sub_sync)
        self._remove_sync_temp_copy()
        self._refresh_points_list()

        # Läs om raderna så listan i dialogen visar de nya (redan
        # korrekta) tiderna, inte de gamla original-tiderna.
        self.cues = parse_subtitle_cues(self.sub_path)
        self.lb.delete(0, "end")
        for c in self.cues:
            self.lb.insert("end", f"  {fmt_time(c['start']):>8}   {c['text'][:80]}")

        self.app._reload_subs()      # ladda om undertexten i spelaren
        auto_close_popup(self.app.root, "✓ Undertextfilen uppdaterad",
                         delay_ms=1200)

    def _remove_sync_temp_copy(self) -> None:
        """Delete the leftover sync-temp copy for this film's subtitle,
        if one exists (see DEL 4f's SUB_SYNC_TEMP naming)."""
        base = os.path.basename(self.sub_path)
        temp_path = os.path.join(SUB_SYNC_TEMP, f"_sync_{base}")
        try:
            if os.path.isfile(temp_path):
                os.remove(temp_path)
        except Exception:
            pass

    # ── Close ────────────────────────────────────────────────────────────

    def _on_close(self) -> None:
        self._closing = True
        if self._tick_id is not None:
            try:
                self.after_cancel(self._tick_id)
            except Exception:
                pass
        self.app._sync_dialog = None
        self.destroy()


# *************** DEL 21 - BLUETOOTH HEADPHONES (pure Win32, no admin) ***************
# ToDo (2026-11-09): added so a Bluetooth headset that is paired but "half
# connected" can be reconnected with ONE click inside the player, instead of
# minimising the window and pressing Connect in Windows' Bluetooth list.
#
# How it works: Windows' own bthprops.cpl API.  A paired headset is "connected"
# by switching its A2DP (stereo music) service OFF and ON again for that one
# device - exactly what the Connect button in Windows does.  Nothing is
# installed, no admin rights, nothing outside the player is touched.
#
# Public functions (all safe to call from a worker thread):
#   bt_list_devices()          -> [{"addr","name","connected","audio"}, ...]
#   bt_connect(addr, progress) -> (ok: bool, message: str)

import time   # needed by bt_connect (short pauses)

_BT_A2DP_SINK = "{0000110B-0000-1000-8000-00805F9B34FB}"   # stereo music profile
_BT_SERVICE_DISABLE = 0
_BT_SERVICE_ENABLE  = 1


class _BT_SYSTEMTIME(ctypes.Structure):
    _fields_ = [(n, ctypes.c_ushort) for n in
                ("wYear", "wMonth", "wDayOfWeek", "wDay",
                 "wHour", "wMinute", "wSecond", "wMilliseconds")]


class _BT_DEVICE_INFO(ctypes.Structure):
    _fields_ = [("dwSize",          ctypes.c_uint32),
                ("Address",         ctypes.c_ulonglong),
                ("ulClassofDevice", ctypes.c_uint32),
                ("fConnected",      ctypes.c_int32),
                ("fRemembered",     ctypes.c_int32),
                ("fAuthenticated",  ctypes.c_int32),
                ("stLastSeen",      _BT_SYSTEMTIME),
                ("stLastUsed",      _BT_SYSTEMTIME),
                ("szName",          ctypes.c_wchar * 248)]


class _BT_SEARCH_PARAMS(ctypes.Structure):
    _fields_ = [("dwSize",              ctypes.c_uint32),
                ("fReturnAuthenticated", ctypes.c_int32),
                ("fReturnRemembered",    ctypes.c_int32),
                ("fReturnUnknown",       ctypes.c_int32),
                ("fReturnConnected",     ctypes.c_int32),
                ("fIssueInquiry",        ctypes.c_int32),
                ("cTimeoutMultiplier",   ctypes.c_ubyte),
                ("hRadio",               ctypes.c_void_p)]


class _BT_FIND_RADIO_PARAMS(ctypes.Structure):
    _fields_ = [("dwSize", ctypes.c_uint32)]


class _BT_GUID(ctypes.Structure):
    _fields_ = [("Data1", ctypes.c_uint32), ("Data2", ctypes.c_uint16),
                ("Data3", ctypes.c_uint16), ("Data4", ctypes.c_ubyte * 8)]


def _bt_guid(text: str) -> "_BT_GUID":
    import uuid
    u = uuid.UUID(text)
    g = _BT_GUID()
    g.Data1, g.Data2, g.Data3 = u.time_low, u.time_mid, u.time_hi_version
    for i, b in enumerate(u.bytes[8:]):
        g.Data4[i] = b
    return g


_bt_dll_cache = {}


def _bt_dll():
    """Load bthprops.cpl + kernel32 once, with correct 64-bit signatures."""
    if "bt" in _bt_dll_cache:
        return _bt_dll_cache["bt"], _bt_dll_cache["k32"]
    V = ctypes.c_void_p
    bt  = ctypes.WinDLL("bthprops.cpl")
    k32 = ctypes.WinDLL("kernel32")
    bt.BluetoothFindFirstRadio.argtypes = [ctypes.POINTER(_BT_FIND_RADIO_PARAMS),
                                           ctypes.POINTER(V)]
    bt.BluetoothFindFirstRadio.restype  = V
    bt.BluetoothFindNextRadio.argtypes  = [V, ctypes.POINTER(V)]
    bt.BluetoothFindNextRadio.restype   = ctypes.c_int
    bt.BluetoothFindRadioClose.argtypes = [V]
    bt.BluetoothFindRadioClose.restype  = ctypes.c_int
    bt.BluetoothFindFirstDevice.argtypes = [ctypes.POINTER(_BT_SEARCH_PARAMS),
                                            ctypes.POINTER(_BT_DEVICE_INFO)]
    bt.BluetoothFindFirstDevice.restype  = V
    bt.BluetoothFindNextDevice.argtypes  = [V, ctypes.POINTER(_BT_DEVICE_INFO)]
    bt.BluetoothFindNextDevice.restype   = ctypes.c_int
    bt.BluetoothFindDeviceClose.argtypes = [V]
    bt.BluetoothFindDeviceClose.restype  = ctypes.c_int
    bt.BluetoothGetDeviceInfo.argtypes   = [V, ctypes.POINTER(_BT_DEVICE_INFO)]
    bt.BluetoothGetDeviceInfo.restype    = ctypes.c_uint32
    bt.BluetoothSetServiceState.argtypes = [V, ctypes.POINTER(_BT_DEVICE_INFO),
                                            ctypes.POINTER(_BT_GUID),
                                            ctypes.c_uint32]
    bt.BluetoothSetServiceState.restype  = ctypes.c_uint32
    k32.CloseHandle.argtypes = [V]
    k32.CloseHandle.restype  = ctypes.c_int
    _bt_dll_cache["bt"], _bt_dll_cache["k32"] = bt, k32
    return bt, k32


def _bt_open_radios() -> list:
    """Handles of every Bluetooth adapter Windows currently has working."""
    bt, _k32 = _bt_dll()
    radios = []
    fp = _BT_FIND_RADIO_PARAMS(ctypes.sizeof(_BT_FIND_RADIO_PARAMS))
    h = ctypes.c_void_p()
    hfind = bt.BluetoothFindFirstRadio(ctypes.byref(fp), ctypes.byref(h))
    if not hfind:
        return radios
    try:
        radios.append(h.value)
        while True:
            h2 = ctypes.c_void_p()
            if not bt.BluetoothFindNextRadio(hfind, ctypes.byref(h2)):
                break
            radios.append(h2.value)
    finally:
        bt.BluetoothFindRadioClose(hfind)
    return radios


def _bt_close_radios(radios: list) -> None:
    _bt, k32 = _bt_dll()
    for r in radios:
        try:
            k32.CloseHandle(ctypes.c_void_p(r))
        except Exception:
            pass


def _bt_addr_text(a: int) -> str:
    return ":".join(f"{(a >> (8 * i)) & 0xFF:02X}" for i in range(5, -1, -1))


def _bt_addr_int(text: str) -> int:
    return int(text.replace(":", "").replace("-", ""), 16)


def _bt_devices_on_radio(radio) -> list:
    """Every paired/remembered device known to one adapter (no inquiry, so it
    is instant).  Returns raw _BT_DEVICE_INFO structs."""
    bt, _k32 = _bt_dll()
    sp = _BT_SEARCH_PARAMS()
    sp.dwSize = ctypes.sizeof(_BT_SEARCH_PARAMS)
    sp.fReturnAuthenticated = 1
    sp.fReturnRemembered    = 1
    sp.fReturnConnected     = 1
    sp.fReturnUnknown       = 0
    sp.fIssueInquiry        = 0
    sp.cTimeoutMultiplier   = 1
    sp.hRadio = ctypes.c_void_p(radio)
    out = []
    info = _BT_DEVICE_INFO()
    info.dwSize = ctypes.sizeof(_BT_DEVICE_INFO)
    hfind = bt.BluetoothFindFirstDevice(ctypes.byref(sp), ctypes.byref(info))
    if not hfind:
        return out
    try:
        while True:
            copy = _BT_DEVICE_INFO()
            ctypes.memmove(ctypes.byref(copy), ctypes.byref(info),
                           ctypes.sizeof(_BT_DEVICE_INFO))
            out.append(copy)
            info.dwSize = ctypes.sizeof(_BT_DEVICE_INFO)
            if not bt.BluetoothFindNextDevice(hfind, ctypes.byref(info)):
                break
    finally:
        bt.BluetoothFindDeviceClose(hfind)
    return out


def bt_list_devices() -> list:
    """Paired Bluetooth devices: [{"addr","name","connected","audio"}].
    Empty list when Windows has no working Bluetooth adapter."""
    result, seen = [], set()
    radios = _bt_open_radios()
    try:
        for r in radios:
            for d in _bt_devices_on_radio(r):
                if d.Address in seen:
                    continue
                seen.add(d.Address)
                major = (d.ulClassofDevice >> 8) & 0x1F      # 4 = audio/video
                result.append({
                    "addr":      _bt_addr_text(d.Address),
                    "name":      d.szName or _bt_addr_text(d.Address),
                    "connected": bool(d.fConnected),
                    "audio":     major == 4,
                })
    finally:
        _bt_close_radios(radios)
    result.sort(key=lambda x: (not x["audio"], x["name"].lower()))
    return result


def bt_connect(addr_text: str, progress=None) -> tuple:
    """(Re)connect the paired headset with this address.  Blocks up to ~12 s;
    call it from a worker thread.  Returns (ok, message)."""
    def say(t):
        if progress:
            try:
                progress(t)
            except Exception:
                pass
    try:
        bt, _k32 = _bt_dll()
    except Exception as exc:
        return False, f"Windows' Bluetooth library could not be loaded:\n{exc}"
    radios = _bt_open_radios()
    if not radios:
        return False, ("Windows has no WORKING Bluetooth adapter right now.\n\n"
                       "Open Device Manager > Bluetooth: an adapter with a "
                       "yellow warning sign is not working.  Unplug and re-plug "
                       "the USB Bluetooth stick (or remove it if the computer "
                       "has Bluetooth built in).")
    try:
        want = _bt_addr_int(addr_text)
        found = None
        for r in radios:
            for d in _bt_devices_on_radio(r):
                if d.Address == want:
                    found = (r, d)
                    break
            if found:
                break
        if not found:
            return False, ("This headset is not paired with the Bluetooth "
                           "adapter Windows is using now.\n\nPair it once in "
                           "Windows > Settings > Bluetooth & devices, then "
                           "choose it again with the right-click menu.")
        radio, dev = found
        name = dev.szName or addr_text
        guid = _bt_guid(_BT_A2DP_SINK)
        say("switching audio service off")
        bt.BluetoothSetServiceState(ctypes.c_void_p(radio), ctypes.byref(dev),
                                    ctypes.byref(guid), _BT_SERVICE_DISABLE)
        time.sleep(0.4)
        say("switching audio service on")
        rc = bt.BluetoothSetServiceState(ctypes.c_void_p(radio),
                                         ctypes.byref(dev), ctypes.byref(guid),
                                         _BT_SERVICE_ENABLE)
        if rc != 0:
            # Never leave the service switched off.
            try:
                bt.BluetoothSetServiceState(ctypes.c_void_p(radio),
                                            ctypes.byref(dev),
                                            ctypes.byref(guid),
                                            _BT_SERVICE_ENABLE)
            except Exception:
                pass
            why = {1060: "the headset does not offer stereo audio",
                   5:    "access denied",
                   87:   "invalid parameter"}.get(rc, f"error {rc}")
            return False, (f"Windows would not connect '{name}' ({why}).\n\n"
                           "Make sure the headset is switched on and close "
                           "to the computer.")
        # Wait until Windows reports the headset as connected.
        say("waiting for the headset")
        for _ in range(24):                                    # 24 x 0.5 s
            chk = _BT_DEVICE_INFO()
            chk.dwSize = ctypes.sizeof(_BT_DEVICE_INFO)
            chk.Address = want
            if bt.BluetoothGetDeviceInfo(ctypes.c_void_p(radio),
                                         ctypes.byref(chk)) == 0 \
                    and chk.fConnected:
                return True, f"Connected: {name}"
            time.sleep(0.5)
        return False, (f"'{name}' did not answer.\n\nSwitch the headset on "
                       "(or off and on), keep it close, and click the button "
                       "again.")
    except Exception as exc:
        return False, f"Bluetooth error: {exc}"
    finally:
        _bt_close_radios(radios)


# *************** DEL 06 - MKVPLAYER CLASS ***************

class MKVPlayer:
    APP_NAME = "MKV Player"
    APP_VER  = "1.4"
    DOC_URL  = ("https://docs.google.com/document/d/"
                "1B6y3CP-DafUKoXF9Apg4BpEl2m1j0kghRgD7lweF41s/edit?usp=sharing")

    def __init__(self, initial_file: str = None) -> None:
        self.settings      = load_settings()
        self.resume_data   = clean_resume(load_resume())
        # Positions for films in private folders - same TTL, hashed keys.
        self.resume_private = clean_resume(load_private_resume())
        self.sub_settings  = load_sub_settings()   # per-film subtitle overrides
        self.sub_sync      = load_sub_sync()       # per-film subtitle sync anchor points
        self._sync_dialog  = None        # SubSyncDialog instance while open, else None
        self._sub_save_dlg  = None       # "Update subtitle file?" dialog (S key) while open
        self._sub_save_busy = False      # True from the S press until that dialog is answered
        self._player       = None        # mpv.MPV instance or None
        self._seeking      = False       # True while user drags seek bar
        self._duration     = 0.0
        self._poll_id      = None        # after() handle - GUI poll loop
        self._save_id      = None        # after() handle - periodic resume save
        self._hide_id      = None        # after() handle - auto-hide timer
        self._ctrl_visible = True
        self._is_fullscreen= False
        self._fullscreen_stretch = False   # True when in fullscreen-stretch mode
        self._pre_fs_state = "normal"
        self._current_file = None        # path of file currently loaded
        self._sub_tracks   = []          # [(label, path), ...] for current film
        self._active_sub1  = None        # primary sub path (or None)
        self._active_sub2  = None        # secondary sub path (or None)
        self._audio_tracks    = []       # list of mpv track dicts (type==audio)
        self._active_audio_id = None     # mpv track id of selected audio track
        # New feature state
        self._sub_mtimes     = {}          # path -> float mtime for auto-reload
        self._replace_mtimes = {}          # path -> float mtime for replace-JSON hot-reload
        self._sub_poll_ctr = 0           # counts _poll ticks for sub mtime check
        self._cursor_hidden= False       # True when cursor is hidden
        self._cursor_hide_id = None      # after() handle for cursor auto-hide
        self._all_btns     = {}          # key -> tk.Button (all buttons, all the time)
        self._bt_busy      = False       # True while a Bluetooth connect runs (DEL 12c)
        self._bt_result    = None        # (ok, message) set by the worker thread
        self._bt_label_id  = None        # after() handle that resets the button text
        self._vkb          = None       # VirtualKeyboard instance (lazy-created)
        self._vkb_last_target = None     # senast fokuserade Entry/Text-widget
        # ---- Statistics ----
        self._stats_data       = load_stats()
        self._stats_session    = None    # dict for the current play session
        self._stats_seek_from  = None    # player pos (s) at seek-drag start
        # ---- Clock overlay ----
        self._clock_last_shown = None    # (hour, minute) when clock was last flashed
        self._clock_hide_id    = None    # after() handle for hiding the clock label
        # ---- Elapsed overlay ----
        self._elapsed_session_start = None  # datetime: när första uppspelningen startade
        self._elapsed_watch_seconds = 0.0   # ackumulerad faktisk speltid (sekunder)
        self._elapsed_last_trigger  = 0     # senaste utlösta N-minutersgräns (undviker repeat)

        # AppUserModelID måste sättas INNAN tk.Tk() skapas
        try:
            ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
                "IssuOrg.MKVPlayer.1")
            _log_info("AppUserModelID set OK")
        except Exception as exc:
            _log_info(f"AppUserModelID failed: {exc}")

        # ---- Root window ----
        self.root = tk.Tk()
        self.root.title(self.APP_NAME)
        self.root.configure(bg=C_BG)
        self.root.minsize(480, 300)
        self.root.geometry(self.settings.get("window_geometry", "980x640"))
        self.root.protocol("WM_DELETE_WINDOW", self._on_close)

        self._build_menu()
        self._build_ui()

        # Force HWND creation before handing wid to mpv
        self.root.update()
        self._init_mpv()

        # after(0) = första event-loop-ticken, EFTER att tkinter satt sin
        # default-ikon – annars skriver tkinter över vår ikon efteråt
        self.root.after(0, self._setup_window_icon)

        # Restore volume
        vol = int(self.settings.get("volume", 80))
        self._vol_var.set(vol)
        self._apply_volume(vol)

        self._poll()
        self._schedule_resume_save()

        if not MPV_AVAILABLE:
            self.root.after(200, self._warn_no_mpv)

        if self.settings.get("start_fullscreen", True):
            self.root.after(150, self._enter_fullscreen)

        # Fil skickad från OS (dubbelklick / "Öppna med" när programmet är
        # satt som standard för .mkv) - kommer in som kommandoradsargument
        # och laddades tidigare aldrig, oavsett hur mpv/fönstret mådde.
        if initial_file and os.path.isfile(initial_file):
            self.root.after(250, lambda p=initial_file: self._open_path(p))

        # A second film is handed over instead of opening a
        # second window.  This has to sit BEFORE mainloop:
        # __init__ never returns until the window closes.
        si_listen(self.root, self._open_path)
        self.root.mainloop()


# *************** DEL 06b - WINDOW ICON ***************

    def _setup_window_icon(self) -> None:
        """Kallas via root.after(0) så att event-loopen har startat och
        tkinter inte kan skriva över ikonen efteråt.

        Kanal 1 - iconbitmap(): tkinters eget API.  Fungerar korrekt när
                   den anropas inifrån event-loopen (inte vid direkt anrop).

        Kanal 2 - WM_SETICON via ctypes med FindWindowW – tillförlitligare
                   än winfo_id() som ger tkinter-intern content-frame, inte
                   det yttre Win32-fönster som ska ha ikonen.
        """
        import platform
        if platform.system() != "Windows":
            return

        ico_path = os.path.join(APP_DIR, "Icons", "MKV-player.ico")
        if not os.path.isfile(ico_path):
            _log_info(f"Icon not found: {ico_path}")
            return

        # Kanal 1: iconbitmap
        try:
            self.root.iconbitmap(ico_path)
            _log_info("iconbitmap OK")
        except Exception as exc:
            _log_info(f"iconbitmap failed: {exc}")

        # Kanal 2: WM_SETICON
        try:
            user32          = ctypes.windll.user32
            WM_SETICON      = 0x0080
            ICON_SMALL      = 0
            ICON_BIG        = 1
            IMAGE_ICON      = 1
            LR_LOADFROMFILE = 0x0010
            LR_DEFAULTSIZE  = 0x0040

            ico  = ico_path
            hwnd = user32.FindWindowW(None, self.root.title())
            if not hwnd:
                _log_info("FindWindowW hittade inget fönster, hoppar WM_SETICON")
                return

            hbig = user32.LoadImageW(None, ico, IMAGE_ICON, 0,  0,  LR_LOADFROMFILE | LR_DEFAULTSIZE)
            hsml = user32.LoadImageW(None, ico, IMAGE_ICON, 16, 16, LR_LOADFROMFILE)

            if hbig:
                user32.SendMessageW(hwnd, WM_SETICON, ICON_BIG,  hbig)
                _log_info(f"WM_SETICON ICON_BIG OK (hwnd={hwnd})")
            else:
                _log_info("LoadImageW ICON_BIG returnerade NULL")

            if hsml:
                user32.SendMessageW(hwnd, WM_SETICON, ICON_SMALL, hsml)
                _log_info("WM_SETICON ICON_SMALL OK")
            else:
                _log_info("LoadImageW ICON_SMALL returnerade NULL")

        except Exception as exc:
            _log_info(f"WM_SETICON failed: {exc}")


# *************** DEL 07 - MENU BAR ***************

    def _build_menu(self) -> None:
        MN = dict(bg=C_BG2, fg=C_FG, activebackground=C_BG3,
                  activeforeground=C_FG, tearoff=False)
        mb = tk.Menu(self.root, **MN)
        self._menubar = mb
        self.root.config(menu=mb)

        fm = tk.Menu(mb, **MN)
        fm.add_command(label="Open File...", command=self._open_file,
                       accelerator="Ctrl+O")
        fm.add_separator()
        fm.add_command(label="Exit", command=self._on_close)
        mb.add_cascade(label="File", menu=fm)

        hm = tk.Menu(mb, **MN)
        hm.add_command(label="Help",  command=self._show_help)
        hm.add_command(label="About", command=self._show_about)
        mb.add_cascade(label="Help", menu=hm)

        self.root.bind_all("<Control-o>", lambda _: self._open_file())


# *************** DEL 08 - UI / OVERLAY LAYOUT ***************
# Layout strategy:
#   - video_frame fills the ENTIRE root window (place, relwidth/relheight=1)
#   - mpv renders into video_frame's HWND
#   - ctrl_bar and close_btn are siblings of video_frame with higher z-order,
#     so they float ON TOP of the video without affecting its size

    def _build_ui(self) -> None:

        # ---- Video frame - fills whole window ----
        self.video_frame = tk.Frame(self.root, bg=C_VIDEO_BG)
        self.video_frame.place(relx=0, rely=0, relwidth=1.0, relheight=1.0)

        self._placeholder = tk.Label(
            self.video_frame,
            text="   Open a video file to begin  (Ctrl+O)",
            bg=C_VIDEO_BG, fg="#2a2a50",
            font=("Segoe UI", 15))
        self._placeholder.place(relx=0.5, rely=0.5, anchor="center")

        # ---- Clock overlay label – floats bottom-left, shown briefly ----
        self._clock_lbl = tk.Label(
            self.root,
            text="",
            bg="black", fg="white",
            font=("Segoe UI", 20, "bold"),
            padx=12, pady=5,
            relief="flat", bd=0)
        # Not placed yet; shown/hidden by _show_clock_overlay / _hide_clock_overlay

        # ---- Control overlay - floats at the bottom of the window ----
        self.ctrl_bar = tk.Frame(self.root, bg=C_BG2)
        # Placed / forgotten by _show_controls / _hide_controls

        # -- Seek row --
        seek_row = tk.Frame(self.ctrl_bar, bg=C_BG2)
        seek_row.pack(fill="x", padx=8, pady=(6, 0))

        self._time_lbl = tk.Label(
            seek_row, text="0:00 / 0:00",
            bg=C_BG2, fg=C_FG_DIM,
            font=("Segoe UI", 8))
        self._time_lbl.pack(side="right", padx=4)

        self._seek_var = tk.DoubleVar(value=0.0)
        self._seek_bar = tk.Scale(
            seek_row, variable=self._seek_var,
            from_=0, to=1000, orient="horizontal",
            bg=C_BG2, fg=C_FG, troughcolor="#e94560",
            highlightthickness=0, sliderrelief="flat",
            sliderlength=18, width=14,
            showvalue=False, command=self._on_seek_drag)
        self._seek_bar.pack(fill="x", expand=True, side="left")
        # Click anywhere on the bar to jump there; drag to scrub.  We handle
        # B1 ourselves and return "break" so tk.Scale's default page-step does
        # not fight the absolute positioning.
        self._seek_bar.bind("<Button-1>",        self._on_seek_click)
        self._seek_bar.bind("<B1-Motion>",       self._on_seek_motion)
        self._seek_bar.bind("<ButtonRelease-1>", self._on_seek_release)
        self._seek_bar.bind("<MouseWheel>",
                            lambda e: self._seek_rel(5 if e.delta > 0 else -5))

        # -- Button row --
        btn_row = tk.Frame(self.ctrl_bar, bg=C_BG2)
        btn_row.pack(pady=4)

        # Left cluster: transport controls (dynamically ordered / hidden)
        self._left_frame = tk.Frame(btn_row, bg=C_BG2)
        self._left_frame.pack(side="left", padx=8)

        # Create ALL buttons once; layout is handled by _build_btn_row()
        _skip = int(self.settings.get("skip_seconds", 10))
        btn_specs = [
            ("open_list", "Open",             self._open_movies_list),
            ("open",     "Browse",            self._open_file),
            ("last",     "Last",             self._open_last_file),
            ("latest",   "Latest ▾",         self._show_latest_menu),
            ("db",       "🎬 DB",            self._show_db_search),
            ("stats",    "📊 Stats",         self._show_stats_dialog),
            ("settings", "⚙",               self._show_settings),
            ("keyboard", "⌨",               self._toggle_vkb),
            ("stop",     "Stop",             self._stop),
            ("rw",       f"<< -{_skip}s",   lambda: self._seek_rel(-int(self.settings.get("skip_seconds",10)))),
            ("play",     "Play",             self._toggle_play),
            ("fw",       f"+{_skip}s >>",   lambda: self._seek_rel( int(self.settings.get("skip_seconds",10)))),
            ("next",     "Next ▶▶",         self._play_next_file),
            ("sub",      "Sub ▾",           self._show_sub_menu),
            ("audio",    "Audio ▾",         self._show_audio_menu),
            ("plan",     "Plan 📋",          self._show_plan),
            ("mark_del", "🗑 Mark",          self._mark_for_deletion),
            ("fullscreen", "Fullscreen",     self._toggle_fullscreen),
            ("close",    "Close",            self._on_close),
            ("bluetooth", "🎧 Connect",        self._bt_button_click),
        ]
        for key, lbl, cmd in btn_specs:
            b = tk.Button(self._left_frame, text=lbl, command=cmd, **_BTN)
            if key == "bluetooth":
                b.configure(width=13)      # fixed size: label text never resizes it
            _bind_hover(b)
            self._all_btns[key] = b
        # Named aliases expected by other methods
        self._btn_open_list = self._all_btns["open_list"]
        self._btn_open     = self._all_btns["open"]
        self._btn_last     = self._all_btns["last"]
        self._btn_dbsearch = self._all_btns["db"]
        self._btn_settings = self._all_btns["settings"]
        self._btn_stop     = self._all_btns["stop"]
        self._btn_rw       = self._all_btns["rw"]
        self._btn_pp       = self._all_btns["play"]
        self._btn_fw       = self._all_btns["fw"]
        self._btn_next     = self._all_btns["next"]
        self._btn_sub      = self._all_btns["sub"]
        self._btn_audio    = self._all_btns["audio"]

        # Initial layout pass
        self._build_btn_row()

        # Right cluster: volume + fullscreen (always visible, not configurable)
        right = tk.Frame(btn_row, bg=C_BG2)
        right.pack(side="right", padx=8)

        tk.Label(right, text="Vol:", bg=C_BG2, fg=C_FG,
                 font=("Segoe UI", 10)).pack(side="left", padx=(0, 3))

        self._vol_var = tk.IntVar(value=80)
        tk.Scale(right, variable=self._vol_var,
                 from_=0, to=200, orient="horizontal",
                 bg=C_BG2, fg=C_FG, troughcolor=C_TROUGH,
                 highlightthickness=0, sliderrelief="flat",
                 sliderlength=14, width=8, length=110,
                 showvalue=True,
                 command=self._apply_volume).pack(side="left")

        tk.Frame(right, bg=C_SEP, width=1).pack(
            side="left", fill="y", padx=6, pady=4)

        self._btn_fs    = self._all_btns["fullscreen"]
        self._btn_close = self._all_btns["close"]

        # Show controls on startup
        self._show_controls()

        # ---- Mouse tracking for auto-hide ----
        self.root.bind_all("<Motion>", self._on_mouse_move)

        # ---- FocusIn tracking for virtual keyboard ----
        self.root.bind_all("<FocusIn>", self._vkb_focus_in)

        # ---- Keyboard bindings ----
        r = self.root
        skip = lambda: int(self.settings.get("skip_seconds", 10))
        arrow = lambda: int(self.settings.get("arrow_skip", 5))
        r.bind("<space>",          lambda _: self._toggle_play())
        r.bind("<Left>",           lambda _: self._seek_rel(-arrow()))
        r.bind("<Right>",          lambda _: self._seek_rel( arrow()))
        r.bind("<Up>",             lambda _: self._vol_delta(5))
        r.bind("<Down>",           lambda _: self._vol_delta(-5))
        r.bind("<m>",              lambda _: self._toggle_mute())
        r.bind("<f>",              lambda _: self._toggle_fullscreen())
        r.bind("<F11>",            lambda _: self._toggle_fullscreen())
        r.bind("<Control-F11>",    lambda _: self._toggle_fullscreen_stretch())
        r.bind("<Escape>",         lambda _: self._on_escape())
        r.bind("<Key-1>",          lambda _: self._go_windowed())
        r.bind("<Return>",         lambda _: self._go_maximized())
        r.bind("<Control-Return>", lambda _: self._go_maximized_stretch())
        # Skip forward/back with configurable step
        r.bind("<Prior>",          lambda _: self._seek_rel(-skip()))   # PgUp
        r.bind("<Next>",           lambda _: self._seek_rel( skip()))   # PgDn
        r.bind("<n>",              lambda _: self._play_next_file())
        # Subtitle sync  , / .  (like PotPlayer)
        r.bind("<comma>",          lambda _: self._sub_delay_delta(-1))
        r.bind("<period>",         lambda _: self._sub_delay_delta(+1))
        r.bind("<minus>",          lambda _: self._sub_delay_reset())
        # S = write the , / . adjustment into the subtitle file (DEL 12d);
        # does nothing unless a sub-delay is actually set.
        r.bind("<s>",              self._sub_delay_save_prompt)
        r.bind("<S>",              self._sub_delay_save_prompt)
        # Audio sync  Shift+, / Shift+. ; reset on _ (Shift+-)
        # På ett svenskt tangentbord översätter Windows Shift+, till keysym "semicolon"
        # och Shift+. till keysym "colon" – Tkinter ser aldrig <Shift-comma/period>.
        r.bind("<semicolon>",      lambda _: self._audio_delay_delta(-1))   # Shift+, (sv)
        r.bind("<colon>",          lambda _: self._audio_delay_delta(+1))   # Shift+. (sv)
        r.bind("<Shift-comma>",    lambda _: self._audio_delay_delta(-1))   # fallback US
        r.bind("<Shift-period>",   lambda _: self._audio_delay_delta(+1))   # fallback US
        r.bind("<underscore>",     lambda _: self._audio_delay_reset())
        # Multi-point subtitle sync (see DEL 15c) - pauses & opens the sync dialog
        r.bind("<y>",              lambda _: self._open_sync_dialog())

        # ---- Right-click context menu (every button, works in tiny windows) --
        # bind_all so the click is caught wherever tk receives it - over the
        # video, the placeholder or the control bar.  _show_context_menu
        # ignores clicks that land in a dialog / the virtual keyboard.
        self.root.bind_all("<Button-3>", self._show_context_menu)


# *************** DEL 08b - RIGHT-CLICK CONTEXT MENU *********************
# Every control-bar button also lives here, so I can reach any function -
# Mark most of all - even when the window is too small to show the button row.
# The menu is rebuilt on each right-click so its labels track the current
# state (Play/Pause, already-marked, the live Sub / Audio / Latest lists), and
# it is posted at the mouse pointer so it never depends on a button's position.

    def _is_current_marked(self) -> bool:
        """True when the currently loaded file already carries the delete
        marker (same test _mark_for_deletion uses to refuse a double-mark)."""
        path = self._current_file
        if not path:
            return False
        marker = (self.settings.get("delete_marker") or "0---DELETE-").strip()
        mode   = self.settings.get("delete_marker_mode", "prefix")
        name   = os.path.basename(path)
        stem, _ext = os.path.splitext(name)
        if mode == "prefix":
            return name.startswith(marker)
        return stem.endswith(marker)

    def _build_context_menu(self) -> tk.Menu:
        """Build a fresh right-click menu mirroring EVERY control-bar button."""
        MN = dict(tearoff=False, bg=C_BG2, fg=C_FG,
                  activebackground=C_BG3, activeforeground=C_FG,
                  font=("Segoe UI", 9))
        m = tk.Menu(self.root, **MN)
        skip = int(self.settings.get("skip_seconds", 10))

        # -- Transport --
        playing = False
        if self._player:
            try:
                playing = not bool(self._player.pause)
            except Exception:
                playing = False
        m.add_command(label=("⏸  Pause" if playing else "▶  Play"),
                      command=self._toggle_play)
        m.add_command(
            label=f"<<  Back {skip}s",
            command=lambda: self._seek_rel(
                -int(self.settings.get("skip_seconds", 10))))
        m.add_command(
            label=f"Forward {skip}s  >>",
            command=lambda: self._seek_rel(
                int(self.settings.get("skip_seconds", 10))))
        m.add_command(label="Stop",       command=self._stop)
        m.add_command(label="Next  ▶▶",   command=self._play_next_file)
        m.add_command(label="Mute / Unmute", command=self._toggle_mute)
        m.add_separator()

        # -- Tracks (live sub-menus, same content as the Sub / Audio buttons) --
        sub_m = tk.Menu(m, **MN)
        self._populate_sub_menu(sub_m)
        m.add_cascade(label="Sub  ▾", menu=sub_m)
        aud_m = tk.Menu(m, **MN)
        self._populate_audio_menu(aud_m)
        m.add_cascade(label="Audio  ▾", menu=aud_m)
        m.add_separator()

        # -- Open / recent / lists --
        m.add_command(label="Open (movies list)", command=self._open_movies_list)
        m.add_command(label="Browse...",          command=self._open_file)
        m.add_command(label="Last file",          command=self._open_last_file)
        lat_m = tk.Menu(m, **MN)
        self._populate_latest_menu(lat_m)
        m.add_cascade(label="Latest", menu=lat_m)
        m.add_command(label="🎬 DB search",  command=self._show_db_search)
        m.add_command(label="📋 Plan (watchlist)", command=self._show_plan)
        m.add_separator()

        # -- Mark (the reason this menu exists - keep it easy to hit) --
        marked = self._is_current_marked()
        m.add_command(
            label=("🗑  Already marked for deletion" if marked
                   else "🗑  Mark for deletion"),
            state=("disabled" if marked else "normal"),
            command=self._mark_for_deletion)
        m.add_separator()

        # -- Window / view --
        m.add_command(label="Windowed",            command=self._go_windowed)
        m.add_command(label="Maximized",           command=self._go_maximized)
        m.add_command(label="Fullscreen",          command=self._toggle_fullscreen)
        m.add_command(label="Fullscreen (stretch)",
                      command=self._toggle_fullscreen_stretch)
        m.add_separator()

        # -- Tools --
        m.add_command(label="📊 Stats",            command=self._show_stats_dialog)
        m.add_command(label="⚙  Settings",         command=self._show_settings)
        m.add_command(label="⌨  Virtual keyboard", command=self._toggle_vkb)
        self._bt_context_entries(m)
        m.add_separator()
        m.add_command(label="Help",  command=self._show_help)
        m.add_command(label="About", command=self._show_about)
        m.add_separator()
        m.add_command(label="Close", command=self._on_close)
        return m

    def _show_context_menu(self, event) -> None:
        """Post the context menu at the mouse pointer.  Fires only for the main
        window - a right-click inside a dialog or the virtual keyboard is left
        alone."""
        try:
            if event.widget.winfo_toplevel() is not self.root:
                return
        except Exception:
            pass
        m = self._build_context_menu()
        try:
            m.tk_popup(event.x_root, event.y_root)
        finally:
            try:
                m.grab_release()
            except Exception:
                pass


# *************** DEL 09 - MPV INITIALISATION ***************

    def _init_mpv(self) -> None:
        """Create and embed the mpv player instance."""
        if not MPV_AVAILABLE:
            return
        wid = self.video_frame.winfo_id()
        _hwdec       = self.settings.get("hwdec",         "auto-safe")
        _gpu_api     = self.settings.get("gpu_api",       "auto")
        _video_sync  = self.settings.get("video_sync",    "audio")
        _interpolate = self.settings.get("interpolation", False)
        _framedrop   = self.settings.get("framedrop",     "vo")
        _last_exc = None
        for vo in ("gpu", "sw", "sdl"):
            try:
                self._player = _mpv_module.MPV(
                    wid           = str(wid),
                    vo            = vo,
                    hwdec         = _hwdec,
                    gpu_api       = _gpu_api,
                    video_sync    = _video_sync,
                    interpolation = _interpolate,
                    framedrop     = _framedrop,
                    keep_open     = True,
                    volume        = int(self.settings.get("volume", 80)),
                )
                break
            except Exception as exc:
                self._player = None
                _last_exc = exc
        if self._player is None:
            messagebox.showerror(
                "libmpv Error",
                f"Could not initialise libmpv:\n{_last_exc}\n\n"
                "Place libmpv-2.dll in  Helpfiles/1---Movie/\n"
                "Download: https://mpv.io/installation/")
            return
        self._player.observe_property("pause",       self._obs_pause)
        self._player.observe_property("duration",    self._obs_duration)
        self._player.observe_property("eof-reached", self._obs_eof)
        # Apply saved video/subtitle settings
        self._apply_video_settings()
        self._apply_sub_settings()

    def _warn_no_mpv(self) -> None:
        dll_dir = DIR_MOVIE.replace("/", "\\")
        messagebox.showerror(
            "Missing: libmpv DLL",
            "libmpv-2.dll (or mpv-2.dll) was not found.\n\n"
            "Steps:\n"
            "  1. Go to https://sourceforge.net/projects/mpv-player-windows/files/libmpv/\n"
            "  2. Download the latest .7z file.\n"
            "  3. Extract  libmpv-2.dll\n"
            f"  4. Place it in:\n     {dll_dir}\n\n"
            "Also: pip install python-mpv\n\n"
            "Then restart MKV Player.")


# *************** DEL 10 - MPV OBSERVERS (mpv thread) ***************
# These run on mpv's internal thread - never touch tk widgets directly here.

    def _obs_pause(self, _n, val) -> None:
        if val is not None:
            self.root.after(0, self._sync_pp_btn, bool(val))

    def _obs_duration(self, _n, val) -> None:
        if val and val > 0:
            self._duration = float(val)

    def _obs_eof(self, _n, val) -> None:
        if val:
            self.root.after(0, self._on_eof)

    def _on_eof(self) -> None:
        """End-of-file reached: clear resume, then play next or stop."""
        self._stats_end_session()
        finished = self._current_file
        if finished:
            self._resume_clear(finished)
        self._seek_var.set(0)
        self._time_lbl.configure(text=f"0:00 / {fmt_time(self._duration)}")
        self._sync_pp_btn(True)
        if self.settings.get("auto_play_next", True) and finished:
            nxt = self._find_next_file(finished)
            if nxt:
                self.root.after(400, lambda p=nxt: self._open_path(p, resume=False))

    def _find_next_file(self, current_path: str):
        """Return path of next video file (alphabetical) in the same dir."""
        VIDEO_EXT = {".mkv", ".mp4", ".avi", ".mov", ".wmv", ".flv",
                     ".webm", ".ts", ".m2ts", ".m4v", ".3gp", ".ogv"}
        d = os.path.dirname(current_path)
        try:
            files = sorted(
                [f for f in os.listdir(d)
                 if os.path.splitext(f)[1].lower() in VIDEO_EXT],
                key=lambda x: x.lower()
            )
        except Exception:
            return None
        cur = os.path.basename(current_path)
        try:
            idx = files.index(cur)
            if idx + 1 < len(files):
                return os.path.join(d, files[idx + 1])
        except ValueError:
            pass
        return None

    def _open_path(self, path: str, resume: bool = True) -> None:
        """Open a specific path directly (used by Latest menu, Plan, auto-next)."""
        if not os.path.isfile(path):
            return
        self._remember_opened(path)
        self._current_file         = path
        self._duration             = 0.0
        self._add_to_recent(path)
        self.root.title(f"{self.APP_NAME}  -  {os.path.basename(path)}")
        self._placeholder.place_forget()
        if not self._player:
            return
        try:
            self._clear_stale_sub_delay()   # a , / . nudge belongs to ONE subtitle
            self._player.play(path)
            self._player.pause = False
            self._sync_pp_btn(False)
        except Exception:
            return
        self._stats_start_session(path)
        self._init_sub_for_file(path)
        self.root.after(400, self._apply_sub_settings)
        self.root.after(700, self._init_audio_for_file)
        if resume:
            resume_pos = self._resume_get(path)
            if resume_pos:
                self.root.after(900, lambda p=resume_pos: self._seek_abs(p))

    def _sync_pp_btn(self, paused: bool) -> None:
        self._btn_pp.configure(text="Play" if paused else "Pause")
        if not self._current_file:
            return  # no file loaded – skip window-mode transitions
        # Cursor: show on pause, schedule hide on play
        if paused:
            self._cancel_cursor_hide()
            self._show_cursor()
        else:
            self._schedule_cursor_hide()
        if paused and self.settings.get("windowed_on_pause", True):
            # Delay so mpv finishes its current frame before resize
            self.root.after(80, self._go_windowed)
        elif not paused and self.settings.get("fullscreen_on_play", True):
            # Always call _enter_fullscreen_default so fill-mode (stretch /
            # fill-crop / letterbox) is applied even when the window is
            # already in fullscreen (e.g. at app startup with start_fullscreen
            # enabled, _enter_fullscreen runs first but sets no fill-mode).
            # Delay until after _apply_sub_settings (400 ms) and
            # _load_subtitle (600 ms) have had time to run.
            self.root.after(750, self._enter_fullscreen_default)
            # Re-apply sub settings after mpv re-inits on resize
            self.root.after(1100, self._apply_sub_settings)
            self.root.after(1100, self._ensure_subs_visible)


# *************** DEL 11 - POLL LOOP (200 ms) ***************

    def _poll(self) -> None:
        """Refresh seek bar and time label periodically."""
        if self._player:
            try:
                pos = self._player.time_pos
                dur = self._player.duration or self._duration or 0.0
                if dur > 0 and not self._seeking and pos is not None:
                    self._seek_var.set(pos / dur * 1000.0)
                self._time_lbl.configure(
                    text=f"{fmt_time(pos)} / {fmt_time(dur)}")
            except Exception:
                pass
        # Check subtitle file mtimes every ~2 s (10 × 200 ms)
        self._sub_poll_ctr += 1
        if self._sub_poll_ctr >= 10:
            self._sub_poll_ctr = 0
            self._check_sub_mtimes()
        # Clock overlay check
        if self.settings.get("clock_overlay", False):
            self._check_clock_overlay()
        # Elapsed overlay: track watch time and check trigger
        _playing_now = bool(
            self._player and
            not getattr(self._player, "pause", True) and
            self._current_file
        )
        if _playing_now:
            if self._elapsed_session_start is None:
                self._elapsed_session_start = datetime.datetime.now()
                self._elapsed_last_trigger  = 0
            self._elapsed_watch_seconds += 0.2   # poll-intervall 200 ms
        if self.settings.get("elapsed_overlay", False):
            self._check_elapsed_overlay()
        self._poll_id = self.root.after(200, self._poll)


    def _check_clock_overlay(self) -> None:
        """Flash the current time if it matches the configured schedule.

        The schedule is anchored to start_hour:start_minute and repeats
        every clock_interval_min minutes.  We trigger whenever:
            (current_total_minutes - start_total_minutes) % interval == 0
        """
        now = datetime.datetime.now()
        h, m, s = now.hour, now.minute, now.second
        interval   = int(self.settings.get("clock_interval_min", 15))
        start_h    = int(self.settings.get("clock_start_hour",   0))
        start_m    = int(self.settings.get("clock_start_minute", 0))
        start_total   = start_h * 60 + start_m
        current_total = h * 60 + m
        # Trigger in the first 2 seconds of a matching minute; only once per minute
        if s < 2 and (current_total - start_total) % interval == 0:
            if self._clock_last_shown != (h, m):
                self._clock_last_shown = (h, m)
                text = f"{h:02d}:{m:02d}"
                if self.settings.get("clock_show_time_left", False):
                    remaining = self._get_remaining_minutes()
                    if remaining is not None:
                        text += f"   -{remaining} min"
                self._show_clock_overlay(text)

    def _get_remaining_minutes(self) -> "int | None":
        """Return whole minutes left in the current file, or None if unknown."""
        if not self._player:
            return None
        try:
            pos = self._player.time_pos
            dur = self._player.duration or self._duration or 0.0
            if pos is None or dur <= 0:
                return None
            remaining = max(0.0, dur - pos)
            return int(remaining // 60)
        except Exception:
            return None

    def _show_clock_overlay(self, text: str) -> None:
        """Place the clock label bottom-left and schedule its removal."""
        if self._clock_hide_id:
            try:
                self.root.after_cancel(self._clock_hide_id)
            except Exception:
                pass
            self._clock_hide_id = None
        dur = int(self.settings.get("clock_duration_ms", 1000))
        self._clock_lbl.configure(text=text)
        # Bottom-left corner with a small margin; y=-12 lifts it 12 px above edge
        self._clock_lbl.place(x=12, rely=1.0, anchor="sw", y=-12)
        self._clock_lbl.lift()
        self._clock_hide_id = self.root.after(dur, self._hide_clock_overlay)

    def _hide_clock_overlay(self) -> None:
        """Remove the clock label from the screen."""
        self._clock_hide_id = None
        try:
            self._clock_lbl.place_forget()
        except Exception:
            pass

    def _check_elapsed_overlay(self) -> None:
        """Flash elapsed time ('X min') when a new N-minute threshold is crossed.

        Two modes:
          wallclock  – minuter sedan sessionen startade (väggklocka)
          watchtime  – minuter av faktisk filmuppspelning (pauser räknas ej)
        """
        if self._elapsed_session_start is None:
            return  # uppspelning har inte startat än
        interval = max(1, int(self.settings.get("elapsed_interval_min", 15)))
        mode     = self.settings.get("elapsed_mode", "wallclock")

        if mode == "wallclock":
            elapsed_min = (
                datetime.datetime.now() - self._elapsed_session_start
            ).total_seconds() / 60.0
        else:  # watchtime
            elapsed_min = self._elapsed_watch_seconds / 60.0

        if elapsed_min < interval:
            return  # har inte nått första gränsen än

        trigger_count = int(elapsed_min / interval)
        if trigger_count > self._elapsed_last_trigger:
            self._elapsed_last_trigger = trigger_count
            minutes_label = trigger_count * interval
            self._show_clock_overlay(f"{minutes_label} min")


# *************** DEL 12 - PLAYBACK ***************

    # ---- Open file ----

    def _open_last_file(self) -> None:
        """Open the most recently played file directly."""
        path = self.settings.get("last_file", "")
        # A folder can be marked private AFTER it was played: never let the
        # Last button point into one.
        if path and self._is_private(path):
            self.settings["last_file"] = ""
            self.settings["last_dir"]  = ""
            path = ""
        if path and os.path.isfile(path):
            self._remember_opened(path)
            self._current_file         = path
            self._duration             = 0.0
            self._add_to_recent(path)
            self.root.title(f"{self.APP_NAME}  -  {os.path.basename(path)}")
            self._placeholder.place_forget()
            if not self._player:
                return
            resume_pos = self._resume_get(path)
            try:
                self._clear_stale_sub_delay()   # a , / . nudge belongs to ONE subtitle
                self._player.play(path)
                self._player.pause = False
                self._sync_pp_btn(False)
            except Exception as exc:
                messagebox.showerror("Playback Error", f"Cannot play:\n{exc}")
                return
            self._stats_start_session(path)
            self._init_sub_for_file(path)
            self.root.after(400, self._apply_sub_settings)
            self.root.after(700, self._init_audio_for_file)
            if resume_pos:
                self.root.after(900, lambda p=resume_pos: self._seek_abs(p))
        else:
            auto_close_popup(self.root, "No previous file saved")

    # ---- Smart film finder helpers (DEL 04g) ----

    def _film_index(self) -> "FilmIndex":
        if not hasattr(self, "_film_index_obj"):
            self._film_index_obj = FilmIndex()
        return self._film_index_obj

    def _film_depth(self) -> int:
        try:
            return max(0, min(12, int(self.settings.get("scan_depth",
                                                        FILM_SCAN_DEPTH_DEFAULT))))
        except (TypeError, ValueError):
            return FILM_SCAN_DEPTH_DEFAULT

    def _film_roots_all(self) -> list:
        """Every registered folder: the category folders, then the movies dirs."""
        roots = []
        cdirs = self.settings.get("category_dirs", {}) or {}
        for cat in FILM_CATEGORIES:
            for k, v in cdirs.items():
                if k.lower() == cat.lower():
                    roots += list(v)
        roots += list(self.settings.get("movies_dirs", []))
        return ft_prune_roots(roots, self._film_depth())

    def _film_groups_for(self, category: str) -> list:
        """Folder lists in the order a film of `category` is looked for:
        its own category folders first, everything else only if needed."""
        depth = self._film_depth()
        cat = (category or "").strip()
        mdirs = list(self.settings.get("movies_dirs", []))
        first = []
        for k, v in (self.settings.get("category_dirs", {}) or {}).items():
            if cat and k.lower() == cat.lower():
                first += list(v)
        aliases = [cat] if cat else []
        if cat.lower() == "okay":
            aliases += ["OKAY", "OK", "Ok"]       # tolerate common spellings
        for base in mdirs:
            for a in aliases:
                first.append(os.path.join(base, a))
        rest = []
        for k, v in (self.settings.get("category_dirs", {}) or {}).items():
            if not (cat and k.lower() == cat.lower()):
                rest += list(v)
        rest += mdirs
        return [g for g in (ft_prune_roots(first, depth),
                            ft_prune_roots(rest, depth)) if g]

    def _film_lookup(self, titles: list, category: str) -> list:
        """[(score, FilmEntry)] best first.  Uses the session cache; if nothing
        exact was found from cache alone, the folders are re-read once (a
        film may have been copied there since)."""
        idx, depth = self._film_index(), self._film_depth()
        groups = self._film_groups_for(category)
        scans_before = idx.scans
        found = ft_find(idx, groups, titles, depth)
        if (not found or found[0][0] < 3) and idx.scans == scans_before:
            idx.clear()
            found = ft_find(idx, groups, titles, depth)
        return found

    def _pick_film_file(self, parent, hint_name: str, items: list,
                        note: str = "") -> str:
        """Small modal list: the files that might be `hint_name`.
        items = [(text shown, path)].  Returns the chosen path, "browse"
        (user wants the file dialog) or "" (cancelled)."""
        result = {"v": ""}
        pick = tk.Toplevel(parent)
        pick.title(f"Which file?  –  {hint_name}")
        pick.configure(bg=C_BG)
        pick.transient(parent)
        pw, ph = 900, 340
        sw = pick.winfo_screenwidth()
        pick.geometry(f"{pw}x{ph}+{max(0, (sw - pw) // 2)}+60")
        pick.grab_set()
        pick.focus_force()
        pick.bind("<Escape>", lambda _: pick.destroy())

        tk.Label(pick, text=f"Found {len(items)} possible "
                            f"file{'s' if len(items) != 1 else ''} for "
                            f"\"{hint_name}\" – choose one:",
                 bg=C_BG, fg=C_FG, font=("Segoe UI", 9)).pack(
                     padx=12, pady=(10, 2), anchor="w")
        tk.Label(pick, text=note or " ", bg=C_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 8, "italic"), anchor="w").pack(
                     fill="x", padx=12, pady=(0, 4))
        lf = tk.Frame(pick, bg=C_BG)
        lf.pack(fill="both", expand=True, padx=12, pady=(0, 4))
        sb2 = tk.Scrollbar(lf, bg=C_BG, troughcolor=C_BG2, relief="flat", width=8)
        sb2.pack(side="right", fill="y")
        lb2 = tk.Listbox(lf, bg=C_BG2, fg=C_FG, selectbackground=C_BG3,
                         selectforeground=C_FG, font=("Segoe UI", 9),
                         relief="flat", highlightthickness=0,
                         activestyle="none", yscrollcommand=sb2.set)
        sb2.config(command=lb2.yview)
        lb2.pack(fill="both", expand=True)
        for text, _p in items:
            lb2.insert("end", text)
        lb2.selection_set(0)
        lb2.focus_set()

        def _play(_evt=None):
            sel = lb2.curselection()
            if sel:
                result["v"] = items[sel[0]][1]
                pick.destroy()

        def _browse():
            result["v"] = "browse"
            pick.destroy()

        lb2.bind("<Double-Button-1>", _play)
        lb2.bind("<Return>", _play)
        bf2 = tk.Frame(pick, bg=C_BG2)
        bf2.pack(fill="x")
        _bp = dict(bg=C_BTN, fg="white", activebackground=C_BTN_HOV,
                   activeforeground="white", relief="flat", padx=8, pady=4,
                   font=("Segoe UI", 9), cursor="hand2")
        tk.Button(bf2, text="Play", command=_play, **_bp).pack(
            side="right", padx=10, pady=6)
        tk.Button(bf2, text="Cancel", command=pick.destroy, **_bp).pack(
            side="right", padx=4, pady=6)
        tk.Button(bf2, text="Browse…", command=_browse, **_bp).pack(
            side="left", padx=10, pady=6)
        parent.wait_window(pick)
        return result["v"]

    def _open_movies_list(self) -> None:
        """Show a sorted list of all video files in the movies dirs and the
        category folders (sub-folders too), with a word-based search box."""
        roots = self._film_roots_all()
        if not roots:
            messagebox.showinfo(
                "Open – Movies List",
                "No movie directories configured.\n\n"
                "Add directories under:\n"
                "  ⚙ Settings  →  Directories  →  Movies directories")
            return

        # The folders are read in the background (cached for the session), so
        # the window opens at once and the list fills in when the scan is done.
        all_entries: list = []
        scan_state = {"done": False}

        def _scan_thread():
            res = []
            try:
                idx, depth = self._film_index(), self._film_depth()
                for r in roots:
                    res += idx.entries(r, depth)
            except Exception:
                pass
            res = ft_unique(res)
            res.sort(key=lambda fe: fe.name.lower())
            all_entries[:] = res
            scan_state["done"] = True

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

        # ── Dialog ──────────────────────────────────────────────
        top = tk.Toplevel(self.root)
        top.title("Open  –  Movies")
        top.configure(bg=C_BG)
        _place_top_center(top, 680, 520)
        top.transient(self.root)
        # grab_set() utelämnat – virtuella tangentbordet måste kunna ta emot klick
        top.focus_force()
        top.bind("<Escape>", lambda _: top.destroy())

        _B2 = dict(bg=C_BTN, fg="white",
                   activebackground=C_BTN_HOV, activeforeground="white",
                   relief="flat", padx=10, pady=4,
                   font=("Segoe UI", 9), cursor="hand2")

        # Search / filter bar
        hdr = tk.Frame(top, bg=C_BG)
        hdr.pack(fill="x", padx=12, pady=(10, 4))
        tk.Label(hdr, text="Search:", bg=C_BG, fg=C_FG,
                 font=("Segoe UI", 9)).pack(side="left", padx=(0, 6))
        search_var = tk.StringVar()
        search_entry = tk.Entry(hdr, textvariable=search_var,
                                bg=C_BG2, fg=C_FG, insertbackground=C_FG,
                                relief="flat", font=("Segoe UI", 9))
        no_blink(search_entry)
        search_entry.pack(side="left", fill="x", expand=True)
        search_entry.focus_set()

        # Count label
        count_lbl = tk.Label(hdr, bg=C_BG, fg=C_FG_DIM,
                             font=("Segoe UI", 8, "italic"))
        count_lbl.pack(side="right", padx=(8, 0))

        # Listbox
        lf = tk.Frame(top, bg=C_BG)
        lf.pack(fill="both", expand=True, padx=12, pady=(0, 4))
        sb = tk.Scrollbar(lf, orient="vertical")
        sb.pack(side="right", fill="y")
        lb = tk.Listbox(lf, bg=C_BG2, fg=C_FG,
                        selectbackground=C_BG3, selectforeground=C_FG,
                        activestyle="none",
                        font=("Segoe UI", 10),
                        relief="flat", bd=0,
                        yscrollcommand=sb.set)
        lb.pack(side="left", fill="both", expand=True)
        sb.config(command=lb.yview)
        lb.bind("<MouseWheel>",
                lambda e: lb.yview_scroll(-1 * (e.delta // 120), "units"))

        # Build path → total watch minutes lookup from stats
        _stats_mins = {}
        for _spath, _sentry in self._stats_data.get("films", {}).items():
            _total_s = sum(s.get("duration_s", 0)
                          for s in _sentry.get("sessions", []))
            if _total_s > 0:
                _stats_mins[_spath] = int(_total_s // 60)

        # Filtered list (updated on search).  Words are matched, not raw text:
        # "speak no evil (2024)" finds Speak_no_evil_(2022).mkv, "the ring"
        # finds Ring,_The.mkv, and a series folder name finds its episodes.
        _visible: list = []     # file paths, same order as the list box
        _root_set = {os.path.normcase(os.path.normpath(r)) for r in roots}

        def _refresh_list(*_):
            nonlocal _visible
            if not scan_state["done"]:
                count_lbl.configure(text="reading folders…")
                return
            shown = ft_filter(all_entries, search_var.get())
            _visible = [fe.path for fe in shown]
            lb.delete(0, "end")
            for fe in shown:
                mins = _stats_mins.get(fe.path)
                suffix = f"   · {mins} min" if mins else ""
                folder = os.path.dirname(fe.path)
                where = ("" if os.path.normcase(os.path.normpath(folder)) in _root_set
                         else f"   [{os.path.basename(folder)}]")
                lb.insert("end", "  " + fe.name + where + suffix)
            count_lbl.configure(
                text=f"{len(shown)} / {len(all_entries)} files")
            if _visible:
                lb.select_set(0)
                lb.see(0)

        def _poll_scan():
            try:
                if not top.winfo_exists():
                    return
            except Exception:
                return
            if scan_state["done"]:
                _refresh_list()
                if not all_entries:
                    count_lbl.configure(text="no video files found")
            else:
                top.after(150, _poll_scan)

        search_var.trace_add("write", _refresh_list)
        count_lbl.configure(text="reading folders…")
        _poll_scan()

        def _play_selected(_evt=None):
            sel = lb.curselection()
            if not sel:
                return
            path = _visible[sel[0]]
            top.destroy()
            self._remember_opened(path)
            self._current_file         = path
            self._duration             = 0.0
            self._add_to_recent(path)
            self.root.title(f"{self.APP_NAME}  -  {os.path.basename(path)}")
            self._placeholder.place_forget()
            if not self._player:
                messagebox.showwarning("No player",
                                       "libmpv is not available.")
                return
            resume_pos = self._resume_get(path)
            try:
                self._clear_stale_sub_delay()   # a , / . nudge belongs to ONE subtitle
                self._player.play(path)
                self._player.pause = False
                self._sync_pp_btn(False)
            except Exception as exc:
                messagebox.showerror("Playback Error",
                                     f"Cannot play file:\n{exc}")
                return
            self._stats_start_session(path)
            self._init_sub_for_file(path)
            self.root.after(400, self._apply_sub_settings)
            self.root.after(700, self._init_audio_for_file)
            if resume_pos:
                self.root.after(900, lambda p=resume_pos: self._seek_abs(p))

        lb.bind("<Double-Button-1>", _play_selected)
        lb.bind("<Return>",          _play_selected)

        # Keyboard nav in search field
        def _search_key(evt):
            if evt.keysym == "Down":
                lb.focus_set()
                if lb.size():
                    lb.select_set(0)
                    lb.see(0)
            elif evt.keysym == "Return":
                _play_selected()
        search_entry.bind("<KeyPress>", _search_key)

        # Buttons
        bf = tk.Frame(top, bg=C_BG)
        bf.pack(pady=(0, 10))
        play_btn = tk.Button(bf, text="▶  Play",
                             command=_play_selected, **_B2)
        play_btn.pack(side="left", padx=4)
        _bind_hover(play_btn)
        close_btn = tk.Button(bf, text="Close",
                              command=top.destroy, **_B2)
        close_btn.pack(side="left", padx=4)
        _bind_hover(close_btn)

    def _open_file(self) -> None:
        init_dir = self.settings.get("last_dir", "")
        if not os.path.isdir(init_dir):
            init_dir = ""
        path = filedialog.askopenfilename(
            parent=self.root,
            initialdir=init_dir,
            title="Open Video File",
            filetypes=[
                ("Video files",
                 "*.mkv *.mp4 *.avi *.mov *.wmv *.flv *.webm "
                 "*.ts *.m2ts *.m4v *.3gp *.ogv"),
                ("MKV",       "*.mkv"),
                ("MP4",       "*.mp4"),
                ("All files", "*.*"),
            ])
        if not path:
            return

        self._remember_opened(path)
        self._current_file         = path
        self._duration             = 0.0
        self._add_to_recent(path)
        self.root.title(f"{self.APP_NAME}  -  {os.path.basename(path)}")
        self._placeholder.place_forget()

        if not self._player:
            messagebox.showwarning("No player",
                                   "libmpv is not available.\n"
                                   "See Help > About for setup instructions.")
            return

        resume_pos = self._resume_get(path)
        try:
            self._clear_stale_sub_delay()   # a , / . nudge belongs to ONE subtitle
            self._player.play(path)
            self._player.pause = False
            self._sync_pp_btn(False)
        except Exception as exc:
            messagebox.showerror("Playback Error",
                                 f"Cannot play file:\n{exc}")
            return

        self._stats_start_session(path)
        self._init_sub_for_file(path)
        self.root.after(400, self._apply_sub_settings)
        self.root.after(700, self._init_audio_for_file)

        if resume_pos:
            self.root.after(900, lambda p=resume_pos: self._seek_abs(p))

    def _init_sub_for_file(self, path: str) -> None:
        """Scan subtitles for a new file, restore persisted choices, schedule loading."""
        self._sub_tracks  = self._find_all_subtitles(path)
        film_entry        = self.sub_settings.get(path, {})

        # Restore persisted secondary sub (validate file still exists)
        sub2_path = film_entry.get("sub2_path")
        self._active_sub2 = (sub2_path
                              if sub2_path and os.path.isfile(sub2_path)
                              else None)

        # Pick primary sub
        if film_entry.get("sub_off"):
            self._active_sub1 = None
        else:
            # Use first track found; respect saved choice if it still exists
            if self._sub_tracks:
                self._active_sub1 = self._sub_tracks[0][1]
            else:
                self._active_sub1 = None

        # Load subs after mpv has had time to open the file
        self.root.after(600, self._reload_subs)
        self.root.after(900, self._show_sub_loaded_popup)
        self._update_sub_button()

    def _seek_abs(self, pos: float) -> None:
        """Seek to absolute position (seconds)."""
        if self._player:
            try:
                self._player.seek(pos, reference="absolute", precision="exact")
            except Exception:
                pass

    def _apply_video_settings(self) -> None:
        if not self._player:
            return
        try:
            self._player.panscan = float(self.settings.get("panscan", 0.0))
        except Exception:
            pass
        # HDR brightness stability — disable mpv's dynamic peak detection so the
        # picture doesn't suddenly brighten/darken between scenes.  Each property
        # is set defensively: an unknown option on an older libmpv is ignored,
        # never fatal.
        peak = "yes" if self.settings.get("hdr_peak_detect", False) else "no"
        for attr, val in (
            ("hdr_compute_peak", peak),
            ("tone_mapping",     str(self.settings.get("tone_mapping", "bt.2390"))),
        ):
            try:
                setattr(self._player, attr, val)
            except Exception:
                pass


    def _find_subtitle(self, video_path: str):
        """Legacy wrapper — returns first subtitle found (or None)."""
        tracks = self._find_all_subtitles(video_path)
        return tracks[0][1] if tracks else None

    def _strip_ignored_affixes(self, base: str) -> str:
        """Strip configured "ignore" prefixes/suffixes from a filename base.

        Only triggers actually present on this particular filename have any
        effect - matching is opt-in per file, never forced.  Runs repeatedly
        so stacked triggers (e.g. a prefix AND a suffix on the same file, or
        several chained ones) are all removed in one go.  Comparison is
        case-insensitive (scene-release tags vary in casing), but the exact
        casing of the remaining text is preserved.
        """
        affixes = self.settings.get("subtitle_ignore_affixes", [])
        if not affixes:
            return base
        changed = True
        while changed:
            changed = False
            for item in affixes:
                text = item.get("text", "")
                kind = item.get("type", "prefix")
                if not text or len(text) >= len(base):
                    continue
                low_base, low_text = base.lower(), text.lower()
                if kind == "prefix" and low_base.startswith(low_text):
                    base = base[len(text):]
                    changed = True
                elif kind == "suffix" and low_base.endswith(low_text):
                    base = base[:-len(text)]
                    changed = True
        return base

    def _find_all_subtitles(self, video_path: str) -> list:
        """Return ordered [(label, path)] for all subtitle files found for this film.

        Exact filename matches are always searched for first, and stay first
        in the returned list (so they remain the default pick - see
        _init_sub_for_file).  If the film's filename starts/ends with a
        configured "ignore" prefix/suffix (Settings -> Directories -> Ignored
        prefixes/suffixes), the stripped name is ALSO searched; any matches
        found only that way are appended afterwards, labelled accordingly.
        Finally, Roman/Arabic numerals and a leading article ("The_") are
        permanently made interchangeable with the moved-article convention
        ("...,_The") - see smart_subtitle_name_variants() in DEL 04e.
        All of these extra matches only become the default pick when no
        exact match exists at all.
        """
        base  = os.path.splitext(os.path.basename(video_path))[0]
        langs = self.settings.get("subtitle_dir_langs", {})
        seen  = set()

        dirs_labeled = []
        for d in self.settings.get("subtitle_dirs", []):
            lbl = langs.get(d) or os.path.basename(d) or d
            dirs_labeled.append((d, lbl))

        film_dir = os.path.dirname(video_path)
        if film_dir not in {d for d, _ in dirs_labeled}:
            dirs_labeled.append((film_dir, "(film)"))

        def scan(name: str, tag: str = "") -> list:
            found = []
            for d, lbl in dirs_labeled:
                for ext in (".srt", ".SRT", ".ass", ".ASS", ".ssa", ".SSA"):
                    candidate = os.path.join(d, name + ext)
                    if os.path.isfile(candidate) and candidate not in seen:
                        seen.add(candidate)
                        found.append((f"{lbl}{tag}", candidate))
                        break
            return found

        # 1) Exact filename match - always tried first, always preferred.
        result = scan(base)

        # 2) "Ignored" prefix/suffix match - only kicks in when the filename
        #    actually contains one of the configured triggers.
        stripped = self._strip_ignored_affixes(base)
        if stripped != base:
            result.extend(scan(stripped, tag="  (ignorerar prefix/suffix)"))

        # 3) "Smart" match - Roman/Arabic numerals and a leading "The_" made
        #    interchangeable with the moved-article "...,_The" convention.
        #    Tried last (lowest priority) against both `base` and `stripped`,
        #    so tiers 1-2 above are always preferred when they find anything.
        tried = {base, stripped}
        for source in (base, stripped):
            for variant in smart_subtitle_name_variants(source):
                if variant in tried:
                    continue
                tried.add(variant)
                result.extend(scan(variant, tag="  (artikel/siffra)"))

        return result

    def _load_subtitle(self, sub_path: str) -> None:
        """Legacy – kept for compatibility."""
        self._active_sub1 = sub_path
        self._reload_subs()

    # ---- Subtitle track management (new) ----

    def _derive_top_pos(self, pos: int) -> int:
        """Mirror a bottom-relative sub-pos value to top edge."""
        # pos=102 (2% below bottom) → 0 (at top), pos=95 → 5, pos=80 → 20
        return max(0, min(100, 100 - pos))

    def _update_sub_button(self) -> None:
        """Refresh the Sub button label to reflect current state."""
        film_entry = (self.sub_settings.get(self._current_file, {})
                      if self._current_file else {})
        if film_entry.get("sub_off"):
            lbl = "Sub: Off"
        elif self._active_sub1:
            track = next((l for l, p in self._sub_tracks
                          if p == self._active_sub1), "Sub")
            lbl = f"Sub: {track}"
            if self._active_sub2:
                track2 = next((l for l, p in self._sub_tracks
                               if p == self._active_sub2), "2")
                lbl += f" +{track2}"
            if film_entry.get("sub_top"):
                lbl += " ↑"
        else:
            lbl = "Sub ▾"
        try:
            self._btn_sub.configure(text=lbl)
        except Exception:
            pass

    # ---- Audio track management ----

    def _audio_track_label(self, t: dict) -> str:
        """Build a human-readable label for an mpv audio track dict."""
        parts = []
        lang = t.get("lang") or ""
        title = t.get("title") or ""
        tid = t.get("id", "?")
        if lang:
            parts.append(lang)
        if title and title.lower() != lang.lower():
            parts.append(title)
        return f"{tid}: {' – '.join(parts)}" if parts else f"Spår {tid}"

    def _init_audio_for_file(self) -> None:
        """Read audio tracks from mpv, auto-select best one by priority."""
        if not self._player:
            return
        try:
            track_list = self._player.track_list or []
        except Exception:
            track_list = []

        self._audio_tracks = [t for t in track_list if t.get("type") == "audio"]

        if not self._audio_tracks:
            self._active_audio_id = None
            self._update_audio_button()
            return

        # Auto-select: pick the highest-priority track
        priority = self.settings.get("audio_lang_priority", [])
        best_id = self._pick_best_audio(self._audio_tracks, priority)
        if best_id is not None:
            try:
                self._player.aid = best_id
                self._active_audio_id = best_id
            except Exception:
                self._active_audio_id = None
        else:
            # No match – keep whatever mpv picked, just read the current id
            try:
                self._active_audio_id = int(self._player.aid or
                                            self._audio_tracks[0]["id"])
            except Exception:
                self._active_audio_id = self._audio_tracks[0].get("id")

        self._update_audio_button()

    def _pick_best_audio(self, tracks: list, priority: list):
        """Return mpv track id of the best match, or None if no match."""
        if not priority:
            return None
        for keyword in priority:
            kw = keyword.lower()
            for t in tracks:
                lang  = (t.get("lang")  or "").lower()
                title = (t.get("title") or "").lower()
                if kw in lang or kw in title:
                    return t["id"]
        return None

    def _update_audio_button(self) -> None:
        """Refresh the Audio button: dim when 1 track, accent-coloured when >1."""
        try:
            btn = self._btn_audio
        except AttributeError:
            return

        n = len(self._audio_tracks)
        if n == 0:
            btn.configure(text="Audio ▾", fg=C_FG_DIM)
            return

        # Label: show lang/title of active track
        active = next(
            (t for t in self._audio_tracks
             if t.get("id") == self._active_audio_id),
            self._audio_tracks[0])
        lbl = f"Audio: {self._audio_track_label(active)}" if n > 1 else "Audio ▾"

        # Colour: dim when only one track, accent when choice exists
        fg = C_ACCENT if n > 1 else C_FG_DIM
        btn.configure(text=lbl, fg=fg)

    def _populate_audio_menu(self, m: tk.Menu) -> None:
        """Fill menu m with the audio-track choices.  Shared by the Audio
        button (_show_audio_menu) and the right-click context menu, so both
        always offer exactly the same tracks."""
        if not self._audio_tracks:
            m.add_command(label="  (no audio tracks found)", state="disabled")
            return

        def chk(active): return "✓  " if active else "    "

        for t in self._audio_tracks:
            tid    = t.get("id")
            active = (tid == self._active_audio_id)
            label  = self._audio_track_label(t)
            m.add_command(
                label=f"{chk(active)}{label}",
                command=lambda _id=tid: self._choose_audio(_id))

    def _show_audio_menu(self) -> None:
        """Popup menu for selecting the active audio track."""
        if not self._audio_tracks:
            auto_close_popup(self.root, "No audio tracks found")
            return

        m = tk.Menu(self.root, tearoff=False,
                    bg=C_BG2, fg=C_FG,
                    activebackground=C_BG3, activeforeground=C_FG,
                    font=("Segoe UI", 9))

        self._populate_audio_menu(m)

        try:
            b = self._btn_audio
            b.update_idletasks()
            m.tk_popup(b.winfo_rootx(),
                       b.winfo_rooty() - m.winfo_reqheight())
        except Exception:
            pass
        finally:
            try:
                m.grab_release()
            except Exception:
                pass

    def _choose_audio(self, track_id: int) -> None:
        """Switch to the given mpv audio track id."""
        if not self._player:
            return
        try:
            self._player.aid = track_id
            self._active_audio_id = track_id
            self._update_audio_button()
        except Exception:
            pass

    def _populate_sub_menu(self, m: tk.Menu) -> None:
        """Fill menu m with the subtitle choices (Sub 1 / Sub 2 / Top / Sync /
        Off).  Shared by the Sub button (_show_sub_menu) and the right-click
        context menu, so both offer exactly the same subtitle controls."""
        film_entry = (self.sub_settings.get(self._current_file, {})
                      if self._current_file else {})
        sub_off  = film_entry.get("sub_off", False)
        sub_top  = film_entry.get("sub_top", False)
        cur_sub2 = film_entry.get("sub2_path")

        def chk(active): return "✓  " if active else "    "

        if not self._sub_tracks:
            m.add_command(label="  (no subtitles found)", state="disabled")
        else:
            # ── Sub 1 ─────────────────────────────────────────────
            m.add_command(label="── Sub 1 ──", state="disabled")
            for lbl, path in self._sub_tracks:
                active = (not sub_off) and (self._active_sub1 == path)
                m.add_command(
                    label=f"{chk(active)}{lbl}",
                    command=lambda p=path, l=lbl: self._choose_sub1(p, l))
            # Open the chosen Sub 1 file in Meditor (Notepad if no Meditor)
            m.add_command(
                label="📝  Open subtitle in editor (Meditor)...",
                state=("normal" if self._active_sub1 else "disabled"),
                command=self._open_sub_in_editor)
            m.add_separator()

            # ── Sub 2 ─────────────────────────────────────────────
            m.add_command(label="── Sub 2  (överkant) ──", state="disabled")
            m.add_command(label=f"{chk(not cur_sub2)}Off",
                          command=self._clear_sub2)
            for lbl, path in self._sub_tracks:
                if path == self._active_sub1:
                    continue   # skip same as sub1
                active = (cur_sub2 == path)
                m.add_command(
                    label=f"{chk(active)}{lbl}",
                    command=lambda p=path, l=lbl: self._choose_sub2(p, l))
            m.add_separator()

            # ── Top toggle ────────────────────────────────────────
            m.add_command(label=f"{chk(sub_top)}Top  (sub vid överkant)",
                          command=self._toggle_sub_top)
            m.add_separator()

            # ── Sync ──────────────────────────────────────────────
            sync_entry  = (self.sub_sync.get(self._current_file, {})
                          if self._current_file else {})
            n_points    = (len(sync_entry.get("points", []))
                          if sync_entry.get("sub_path") == self._active_sub1 else 0)
            sync_label  = (f"🔧  Sync subtitle...  ({n_points} point"
                          f"{'s' if n_points != 1 else ''})" if n_points
                          else "🔧  Sync subtitle...")
            m.add_command(label=sync_label,
                          state=("normal" if self._active_sub1 else "disabled"),
                          command=self._open_sync_dialog)
            try:
                cur_delay = float(self._player.sub_delay or 0) if self._player else 0.0
            except Exception:
                cur_delay = 0.0
            m.add_command(
                label=(f"💾  Save sub-delay {cur_delay:+.3f} s into file...  (S)"
                       if abs(cur_delay) >= 0.0005
                       else "💾  Save sub-delay into file...  (S)"),
                state=("normal" if abs(cur_delay) >= 0.0005 else "disabled"),
                command=self._sub_delay_save_prompt)
            m.add_separator()

        # ── Off ───────────────────────────────────────────────────
        m.add_command(label=f"{chk(sub_off)}Off  (denna film)",
                      command=self._toggle_sub_off)

    def _open_sub_in_editor(self) -> None:
        """Open the active Sub 1 file in Meditor; if Meditor cannot be found
        or started, in Windows' own text editor (Notepad).  Popen only - the
        player must not freeze while the editor is open.  The file is opened
        as it is on disk (not the temp copy used for replacements/resync)."""
        path = self._active_sub1
        if not path or not os.path.isfile(path):
            auto_close_popup(self.root, "Subtitle file not found on disk.")
            return
        try:
            if _launch_my_app("Meditor", path):
                return
        except Exception:
            pass
        try:
            subprocess.Popen(["notepad.exe", path])
        except Exception as e:
            auto_close_popup(self.root, f"Couldn't open the editor:\n{e}",
                             delay_ms=2500)

    def _show_sub_menu(self) -> None:
        """Build and display the subtitle selection popup menu."""
        m = tk.Menu(self.root, tearoff=False,
                    bg=C_BG2, fg=C_FG,
                    activebackground=C_BG3, activeforeground=C_FG,
                    font=("Segoe UI", 9))

        self._populate_sub_menu(m)

        # Post above button
        try:
            b = self._btn_sub
            b.update_idletasks()
            m.tk_popup(b.winfo_rootx(),
                       b.winfo_rooty() - m.winfo_reqheight())
        except Exception:
            pass
        finally:
            try:
                m.grab_release()
            except Exception:
                pass

    def _open_sync_dialog(self) -> None:
        """Open (or re-focus) the multi-point subtitle sync dialog for the
        active primary subtitle track - see DEL 20b (SubSyncDialog) for the
        dialog itself and DEL 04f for the underlying time-remap engine.
        Pauses playback and marks the current position as a candidate
        anchor point."""
        if self._sync_dialog is not None:
            try:
                self._sync_dialog.lift()
                self._sync_dialog.focus_force()
                self._sync_dialog._mark_here()
                return
            except Exception:
                self._sync_dialog = None
        if not self._current_file or not self._active_sub1:
            auto_close_popup(self.root, "Load a film with a subtitle first.")
            return
        if not os.path.isfile(self._active_sub1):
            auto_close_popup(self.root, "Subtitle file not found on disk.")
            return
        cues = parse_subtitle_cues(self._active_sub1)
        if not cues:
            auto_close_popup(self.root,
                             "Couldn't read any lines from this subtitle "
                             "(only .srt / .ass / .ssa are supported).",
                             delay_ms=2000)
            return
        self._sync_dialog = SubSyncDialog(self, self._active_sub1, cues)

    def _choose_sub1(self, path: str, label: str) -> None:
        if not self._current_file:
            return
        entry = self.sub_settings.setdefault(self._current_file, {})
        entry["sub_off"] = False
        if path != self._active_sub1:
            self._clear_stale_sub_delay()    # the , / . nudge belonged to the OLD sub
        self._active_sub1 = path
        if self._active_sub2 == path:
            self._active_sub2 = None
            entry.pop("sub2_path", None)
            entry.pop("sub2_label", None)
        save_sub_settings(self.sub_settings)
        self._reload_subs()
        self._update_sub_button()

    def _choose_sub2(self, path: str, label: str) -> None:
        if not self._current_file:
            return
        self._active_sub2 = path
        entry = self.sub_settings.setdefault(self._current_file, {})
        entry["sub2_path"]  = path
        entry["sub2_label"] = label
        save_sub_settings(self.sub_settings)
        self._reload_subs()
        self._update_sub_button()

    def _clear_sub2(self) -> None:
        self._active_sub2 = None
        if self._current_file:
            entry = self.sub_settings.setdefault(self._current_file, {})
            entry.pop("sub2_path",  None)
            entry.pop("sub2_label", None)
            save_sub_settings(self.sub_settings)
        self._reload_subs()
        self._update_sub_button()

    def _toggle_sub_top(self) -> None:
        if not self._current_file:
            return
        entry = self.sub_settings.setdefault(self._current_file, {})
        entry["sub_top"] = not entry.get("sub_top", False)
        save_sub_settings(self.sub_settings)
        self._apply_sub_settings()
        self._update_sub_button()

    def _toggle_sub_off(self) -> None:
        if not self._current_file:
            return
        entry = self.sub_settings.setdefault(self._current_file, {})
        off_now = not entry.get("sub_off", False)
        entry["sub_off"] = off_now
        save_sub_settings(self.sub_settings)
        if off_now:
            try:
                if self._player:
                    self._player.command("set", "sub-visibility", "no")
                    self._player.command("set", "secondary-sub-visibility", "no")
            except Exception:
                pass
        else:
            self._reload_subs()
        self._update_sub_button()

    def _reload_subs(self) -> None:
        """Remove all external sub tracks and reload active ones."""
        if not self._player:
            return
        film_entry = (self.sub_settings.get(self._current_file, {})
                      if self._current_file else {})
        if film_entry.get("sub_off"):
            try:
                self._player.command("set", "sub-visibility", "no")
                self._player.command("set", "secondary-sub-visibility", "no")
            except Exception:
                pass
            return

        # Remove all previously loaded external subtitle tracks
        try:
            self._player.command("sub-remove")
        except Exception:
            pass

        # Load primary
        if self._active_sub1:
            try:
                eff1 = self._get_effective_sub_path(self._active_sub1)
                self._player.command("sub-add", eff1, "select")
                self._record_sub_mtime(self._active_sub1)  # watch original, not temp
            except Exception:
                pass

        # Load secondary (added as non-selecting track)
        if self._active_sub2:
            try:
                eff2 = self._get_effective_sub_path(self._active_sub2)
                self._player.command("sub-add", eff2, "auto")
                self._record_sub_mtime(self._active_sub2)  # watch original, not temp
                # Give mpv time to register the track, then hook it up
                self.root.after(350, self._attach_secondary_sub)
            except Exception:
                pass

        self._apply_sub_settings()

    def _attach_secondary_sub(self) -> None:
        """Find the last loaded external sub track and assign as secondary-sid."""
        if not self._player or not self._active_sub2:
            return
        try:
            track_list = self._player.track_list
            ext_subs = [t for t in track_list
                        if t.get("type") == "sub" and t.get("external", False)]
            if not ext_subs:
                return
            # primary sid is the selected one; secondary = any other external
            try:
                cur_sid = int(self._player.sid or -1)
            except Exception:
                cur_sid = -1
            others = [t for t in ext_subs if t.get("id") != cur_sid]
            target_id = (others[-1]["id"] if others else ext_subs[-1]["id"])
            self._player.command("set", "secondary-sid", str(target_id))
            self._apply_sub_settings()
        except Exception:
            pass

    def _apply_sub_settings(self) -> None:
        if not self._player:
            return
        film_entry = (self.sub_settings.get(self._current_file, {})
                      if self._current_file else {})

        if film_entry.get("sub_off"):
            try:
                self._player.command("set", "sub-visibility", "no")
                self._player.command("set", "secondary-sub-visibility", "no")
            except Exception:
                pass
            return

        scale   = float(film_entry.get("sub_scale",
                        self.settings.get("sub_scale", SUB_SCALE_DEFAULT)))
        pos     = int(film_entry.get("sub_pos",
                      self.settings.get("sub_pos", SUB_POS_DEFAULT)))
        plain   = bool(self.settings.get("sub_plain_text", True))
        sub_top = film_entry.get("sub_top", False)

        top_pos = self._derive_top_pos(pos)

        try:
            self._player.sub_scale = scale
            self._player.sub_pos   = top_pos if sub_top else pos
            self._player.command("set", "sub-ass-override",
                                 "strip" if plain else "no")
            self._player.command("set", "sub-visibility", "yes")
        except Exception:
            pass

        # Secondary sub — always displayed at top
        if self._active_sub2:
            try:
                self._player.command("set", "secondary-sub-pos",
                                     str(top_pos))
                self._player.command("set", "secondary-sub-scale",
                                     str(scale))
                self._player.command("set", "secondary-sub-visibility", "yes")
            except Exception:
                pass

    # ---- Settings dialog ----
    def _show_settings(self) -> None:
        top = tk.Toplevel(self.root)
        top.title("Settings")
        top.configure(bg=C_BG)
        top.resizable(True, True)
        top.transient(self.root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda _: top.destroy())
        _place_top_center(top, 520, 620)

        import tkinter.ttk as ttk

        _B = dict(bg=C_BTN, fg="white", activebackground=C_BTN_HOV,
                  activeforeground="white", relief="flat",
                  padx=8, pady=4, font=("Segoe UI", 9), cursor="hand2")

        # ── Style the Notebook tabs ─────────────────────────────
        style = ttk.Style(top)
        style.theme_use("default")
        style.configure("TNotebook",
                        background=C_BG, borderwidth=0)
        style.configure("TNotebook.Tab",
                        background=C_BG2, foreground=C_FG_DIM,
                        padding=[12, 5],
                        font=("Segoe UI", 9))
        style.map("TNotebook.Tab",
                  background=[("selected", C_BG3)],
                  foreground=[("selected", C_FG)])
        style.configure("TFrame", background=C_BG)

        nb = ttk.Notebook(top)
        nb.pack(fill="both", expand=True, padx=8, pady=8)

        # Helper: scrollable tab frame
        def make_tab(label):
            outer = ttk.Frame(nb)
            nb.add(outer, text=label)
            canvas = tk.Canvas(outer, bg=C_BG, highlightthickness=0,
                               borderwidth=0)
            sb = tk.Scrollbar(outer, orient="vertical",
                              command=canvas.yview)
            canvas.configure(yscrollcommand=sb.set)
            inner = tk.Frame(canvas, bg=C_BG)
            win_id = canvas.create_window((0, 0), window=inner, anchor="nw")
            def _on_configure(e):
                canvas.configure(scrollregion=canvas.bbox("all"))
                canvas.itemconfig(win_id, width=canvas.winfo_width())
            inner.bind("<Configure>", _on_configure)
            canvas.bind("<Configure>",
                        lambda e: canvas.itemconfig(win_id,
                                                    width=e.width))
            def _scroll(e, c=canvas):
                if c.winfo_exists():
                    c.yview_scroll(-1 * (e.delta // 120), "units")
            canvas.bind("<Enter>",
                        lambda e, c=canvas, s=_scroll:
                            c.bind_all("<MouseWheel>", s))
            canvas.bind("<Leave>",
                        lambda e, c=canvas:
                            c.unbind_all("<MouseWheel>"))
            canvas.pack(side="left", fill="both", expand=True)
            sb.pack(side="right", fill="y")
            return inner

        def section(parent, title):
            tk.Label(parent, text=title, bg=C_BG, fg=C_ACCENT,
                     font=("Segoe UI", 10, "bold")).pack(
                         pady=(14, 2), padx=18, anchor="w")
            tk.Frame(parent, bg=C_SEP, height=1).pack(
                fill="x", padx=14, pady=(0, 6))

        def slider_row(parent, label, var, from_, to, resolution, fmt,
                       width=14):
            row = tk.Frame(parent, bg=C_BG)
            row.pack(fill="x", padx=18, pady=2)
            tk.Label(row, text=label, bg=C_BG, fg=C_FG,
                     font=("Segoe UI", 9), width=width,
                     anchor="w").pack(side="left")
            val_lbl = tk.Label(row, text=fmt(var.get()),
                               bg=C_BG, fg=C_FG_DIM,
                               font=("Segoe UI", 9), width=7, anchor="e")
            val_lbl.pack(side="right")
            sc = tk.Scale(row, variable=var,
                          from_=from_, to=to, resolution=resolution,
                          orient="horizontal",
                          bg=C_BG, fg=C_FG, troughcolor=C_TROUGH,
                          highlightthickness=0, sliderrelief="flat",
                          sliderlength=16, width=10, showvalue=False,
                          command=lambda v, l=val_lbl, f=fmt:
                              l.config(text=f(float(v))))
            sc.pack(fill="x", expand=True, side="left", padx=(6, 6))
            return sc, val_lbl

        def chk_row(parent, label, var, tip=""):
            row = tk.Frame(parent, bg=C_BG)
            row.pack(fill="x", padx=18, pady=3)
            cb = tk.Checkbutton(row, text=label, variable=var,
                                bg=C_BG, fg=C_FG, selectcolor=C_BG2,
                                activebackground=C_BG, activeforeground=C_FG,
                                font=("Segoe UI", 9), anchor="w",
                                relief="flat", bd=0)
            cb.pack(side="left")
            if tip:
                tk.Label(row, text=tip, bg=C_BG, fg=C_FG_DIM,
                         font=("Segoe UI", 7, "italic")).pack(
                             side="left", padx=6)
            return cb

        # ════════════════════════════════════════════════════════
        # TAB 1 — SUBTITLE
        # ════════════════════════════════════════════════════════
        t_sub = make_tab("Subtitle")

        sub_scale_var = tk.DoubleVar(
            value=float(self.settings.get("sub_scale", SUB_SCALE_DEFAULT)))
        sub_pos_var   = tk.IntVar(
            value=int(self.settings.get("sub_pos", SUB_POS_DEFAULT)))
        sub_plain_var = tk.BooleanVar(
            value=bool(self.settings.get("sub_plain_text", True)))

        section(t_sub, "Appearance")
        chk_row(t_sub, "Plain text  (ignore bold, italic, colour)", sub_plain_var)

        sc_scale, lbl_scale = slider_row(
            t_sub, "Size:", sub_scale_var,
            0.3, 3.0, 0.05, lambda v: f"{v:.2f}×")

        # Position: use Entry + Scale so exact value is always typeable
        section(t_sub, "Position  (0 = top · 100 = bottom · >100 = below bottom)")
        pos_row = tk.Frame(t_sub, bg=C_BG)
        pos_row.pack(fill="x", padx=18, pady=2)
        tk.Label(pos_row, text="Position:", bg=C_BG, fg=C_FG,
                 font=("Segoe UI", 9), width=14, anchor="w").pack(side="left")

        # Spinbox for exact value input (avoids slider snapping)
        pos_spin = tk.Spinbox(pos_row, from_=0, to=150, increment=1,
                              textvariable=sub_pos_var,
                              width=5, bg=C_BG2, fg=C_FG,
                              buttonbackground=C_BTN,
                              insertbackground=C_FG,
                              relief="flat",
                              font=("Segoe UI", 9))
        pos_spin.pack(side="right", padx=(6, 0))

        sc_pos = tk.Scale(pos_row, variable=sub_pos_var,
                          from_=0, to=150, resolution=1,
                          orient="horizontal",
                          bg=C_BG, fg=C_FG, troughcolor=C_TROUGH,
                          highlightthickness=0, sliderrelief="flat",
                          sliderlength=16, width=10, showvalue=False)
        sc_pos.pack(fill="x", expand=True, side="left", padx=(6, 6))

        # Reset button
        def reset_sub_defaults():
            sub_scale_var.set(SUB_SCALE_DEFAULT)
            sub_pos_var.set(SUB_POS_DEFAULT)
            lbl_scale.config(text=f"{SUB_SCALE_DEFAULT:.2f}×")

        section(t_sub, "Per-film override")
        film_name  = (os.path.basename(self._current_file)
                      if self._current_file else None)
        has_override = (self._current_file in self.sub_settings
                        if self._current_file else False)

        info_txt = (f"Current file:  {film_name}"
                    if film_name else "No file open.")
        tk.Label(t_sub, text=info_txt, bg=C_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 8, "italic"),
                 anchor="w", wraplength=380).pack(
                     padx=18, anchor="w", pady=(0, 3))

        if has_override:
            e = self.sub_settings[self._current_file]
            _sc = e.get('sub_scale')
            _po = e.get('sub_pos')
            scale_str = f"{_sc:.2f}" if _sc is not None else "-"
            pos_str   = str(_po)     if _po is not None else "-"
            ov_txt = f"  Saved override:  size {scale_str}×  ·  position {pos_str} %"
            tk.Label(t_sub, text=ov_txt, bg=C_BG, fg="#80d080",
                     font=("Segoe UI", 8)).pack(
                         padx=18, anchor="w", pady=(0, 6))

        film_btn_row = tk.Frame(t_sub, bg=C_BG)
        film_btn_row.pack(fill="x", padx=18, pady=(0, 4))

        def save_film_sub():
            if not self._current_file:
                messagebox.showinfo("Info", "No file is open.", parent=top)
                return
            self.sub_settings[self._current_file] = {
                "sub_scale": round(sub_scale_var.get(), 2),
                "sub_pos"  : sub_pos_var.get(),
            }
            save_sub_settings(self.sub_settings)
            self._apply_sub_settings()
            auto_close_popup(
                self.root,
                f"✓  Saved for  {os.path.basename(self._current_file)}")
            top.destroy()

        def remove_film_sub():
            if not self._current_file:
                return
            if self._current_file in self.sub_settings:
                del self.sub_settings[self._current_file]
                save_sub_settings(self.sub_settings)
                self._apply_sub_settings()
                auto_close_popup(self.root,
                                 "✓  Film-specific override removed")
            top.destroy()

        b_save_film = tk.Button(film_btn_row,
            text="💾  Save for this film", command=save_film_sub,
            state="normal" if self._current_file else "disabled", **_B)
        b_save_film.pack(side="left", padx=(0, 6))
        _bind_hover(b_save_film)

        b_rm_film = tk.Button(film_btn_row,
            text="✕  Remove film override", command=remove_film_sub,
            state="normal" if has_override else "disabled", **_B)
        b_rm_film.pack(side="left")
        _bind_hover(b_rm_film)

        b_reset = tk.Button(film_btn_row,
            text="↺  Reset to defaults",
            command=reset_sub_defaults, **_B)
        b_reset.pack(side="left", padx=(12, 0))
        _bind_hover(b_reset)

        tk.Label(t_sub,
                 text=f"Defaults:  size {SUB_SCALE_DEFAULT:.2f}×  ·  "
                      f"position {SUB_POS_DEFAULT}",
                 bg=C_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 7, "italic")).pack(
                     padx=18, anchor="w", pady=(2, 10))

        # ── Live word-replacement ────────────────────────────────
        section(t_sub, "Live word replacement")
        tk.Label(t_sub,
                 text="Replaces words in .srt/.ass in real time (via temp copy).\n"
                      "Separate word lists per language – matched against the directory language label.",
                 bg=C_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 8, "italic"),
                 justify="left").pack(padx=18, anchor="w", pady=(0, 4))

        sub_live_var = tk.BooleanVar(
            value=bool(self.settings.get("sub_live_replace", True)))
        chk_row(t_sub, "Enable live replacement  (default: on)", sub_live_var)

        tk.Button(t_sub,
                  text="📝  Edit word lists…",
                  command=lambda: self._show_replace_editor(top),
                  **_B).pack(padx=18, pady=(6, 2), anchor="w")

        # ════════════════════════════════════════════════════════
        # TAB 2 — PLAYBACK
        # ════════════════════════════════════════════════════════
        t_play = make_tab("Playback")

        auto_next_var  = tk.BooleanVar(
            value=bool(self.settings.get("auto_play_next", True)))
        skip_var       = tk.IntVar(
            value=int(self.settings.get("skip_seconds", 10)))
        arrow_var      = tk.IntVar(
            value=int(self.settings.get("arrow_skip", 5)))
        sync_step_var  = tk.IntVar(
            value=int(self.settings.get("sync_step_ms", 100)))

        section(t_play, "Auto-play")
        chk_row(t_play, "Play next file automatically  (alphabetical order)",
                auto_next_var)

        section(t_play, "Seek")
        slider_row(t_play, "← → Arrow (s):", arrow_var,
                   1, 60, 1, lambda v: f"{int(v)} s")
        slider_row(t_play, "PgUp/PgDn (s):", skip_var,
                   1, 60, 1, lambda v: f"{int(v)} s")

        section(t_play, "Sync  ( , / .  och  Shift+, / Shift+. )")
        slider_row(t_play, "Sync step (ms):", sync_step_var,
                   10, 500, 10, lambda v: f"{int(v)} ms")
        tk.Label(t_play,
                 text=",  /  .  = subtitle     Shift+,  /  Shift+.  = audio"
                      "     -  = reset sub     _  (Shift+-)  = reset audio"
                      "     S  = save sub delay into file",
                 bg=C_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 7, "italic")).pack(
                     padx=18, anchor="w", pady=(0, 10))

        start_fs_var   = tk.BooleanVar(
            value=bool(self.settings.get("start_fullscreen", True)))
        fs_on_play_var = tk.BooleanVar(
            value=bool(self.settings.get("fullscreen_on_play", True)))
        win_on_pause_var = tk.BooleanVar(
            value=bool(self.settings.get("windowed_on_pause", True)))

        section(t_play, "Window mode")
        chk_row(t_play, "Start in F11 mode (fullscreen)", start_fs_var)
        chk_row(t_play, "Go to F11 when playback starts", fs_on_play_var)
        chk_row(t_play, "Go to small window on Pause", win_on_pause_var)

        default_max_mode_var = tk.StringVar(
            value=str(self.settings.get("default_max_mode", "stretch")))

        dmm_row = tk.Frame(t_play, bg=C_BG)
        dmm_row.pack(fill="x", padx=18, pady=(6, 0))
        tk.Label(dmm_row, text="Default fill mode:", bg=C_BG, fg=C_FG,
                 font=("Segoe UI", 9), width=14, anchor="w").pack(
                     side="left", anchor="n")
        dmm_opts = tk.Frame(dmm_row, bg=C_BG)
        dmm_opts.pack(side="left", fill="x", expand=True)
        for _lbl, _val in (
                ("Fill screen (stretched)",        "stretch"),
                ("Fill screen (crop, no stretch)", "fill"),
                ("Show full frame (black bars)",   "letterbox")):
            tk.Radiobutton(dmm_opts, text=_lbl, value=_val,
                           variable=default_max_mode_var,
                           bg=C_BG, fg=C_FG, selectcolor=C_BG2,
                           activebackground=C_BG, activeforeground=C_FG,
                           font=("Segoe UI", 9), relief="flat", bd=0,
                           anchor="w", justify="left").pack(anchor="w", pady=1)
        tk.Label(t_play,
                 text="Used when a film starts playing (requires 'Go to F11\n"
                      "when playback starts' above).  Square videos always\n"
                      "use 'crop, no stretch', whatever is chosen here.",
                 bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 7, "italic"),
                 justify="left").pack(padx=18, anchor="w", pady=(2, 8))

        auto_reload_subs_var = tk.BooleanVar(
            value=bool(self.settings.get("auto_reload_subs", True)))
        hide_cursor_var = tk.BooleanVar(
            value=bool(self.settings.get("hide_cursor_on_play", True)))

        section(t_play, "Other")
        chk_row(t_play, "Auto-reload subtitle if file changes on disk",
                auto_reload_subs_var)
        chk_row(t_play, "Hide mouse cursor during playback  (default: on)",
                hide_cursor_var)

        # ── Mark for deletion ────────────────────────────────────
        section(t_play, "Mark for deletion  (🗑 Mark button)")
        tk.Label(t_play,
                 text="The 🗑 Mark button renames the loaded file by adding the\n"
                      "marker below.  Nothing is ever deleted automatically – you\n"
                      "remove the marked files yourself, later.",
                 bg=C_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 8, "italic"),
                 justify="left").pack(padx=18, anchor="w", pady=(0, 4))

        del_marker_var = tk.StringVar(
            value=str(self.settings.get("delete_marker", "0---DELETE-")))
        del_mode_var = tk.StringVar(
            value=str(self.settings.get("delete_marker_mode", "prefix")))

        dm_row = tk.Frame(t_play, bg=C_BG)
        dm_row.pack(fill="x", padx=18, pady=(2, 0))
        tk.Label(dm_row, text="Marker text:", bg=C_BG, fg=C_FG,
                 font=("Segoe UI", 9), width=14, anchor="w").pack(side="left")
        dm_entry = tk.Entry(dm_row, textvariable=del_marker_var,
                            bg=C_BG2, fg=C_FG, insertbackground=C_FG,
                            insertofftime=0, insertontime=9999999,
                            relief="flat", font=("Segoe UI", 9))
        dm_entry.pack(side="left", fill="x", expand=True, padx=(6, 0))

        mode_row = tk.Frame(t_play, bg=C_BG)
        mode_row.pack(fill="x", padx=18, pady=(4, 6))
        tk.Label(mode_row, text="Add as:", bg=C_BG, fg=C_FG,
                 font=("Segoe UI", 9), width=14, anchor="w").pack(side="left")
        for _lbl, _val in (("Prefix", "prefix"), ("Suffix", "suffix")):
            tk.Radiobutton(mode_row, text=_lbl, value=_val,
                           variable=del_mode_var,
                           bg=C_BG, fg=C_FG, selectcolor=C_BG2,
                           activebackground=C_BG, activeforeground=C_FG,
                           font=("Segoe UI", 9), relief="flat",
                           bd=0).pack(side="left", padx=(6, 10))

        # ── Clock overlay ────────────────────────────────────────
        section(t_play, "Clock overlay  (brief time display)")
        tk.Label(t_play,
                 text="Flash the current time (HH:MM) briefly in the bottom-left corner\n"
                      "at regular intervals while the player is open.",
                 bg=C_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 8, "italic"),
                 justify="left").pack(padx=18, anchor="w", pady=(0, 4))

        clock_enabled_var = tk.BooleanVar(
            value=bool(self.settings.get("clock_overlay", False)))
        chk_row(t_play, "Enable clock overlay  (default: off)", clock_enabled_var)

        # Start time: hour (dropdown 0–23) + minute (radio buttons)
        clk_start_hour_var = tk.IntVar(
            value=int(self.settings.get("clock_start_hour", 0)))
        clk_start_var = tk.IntVar(
            value=int(self.settings.get("clock_start_minute", 0)))

        stime_row = tk.Frame(t_play, bg=C_BG)
        stime_row.pack(fill="x", padx=18, pady=(6, 0))
        tk.Label(stime_row, text="Start time:", bg=C_BG, fg=C_FG,
                 font=("Segoe UI", 9), width=14, anchor="w").pack(side="left")

        import tkinter.ttk as _ttk_clk
        _hour_values = [f"{h:02d}" for h in range(24)]
        clk_hour_cb = _ttk_clk.Combobox(
            stime_row, textvariable=tk.StringVar(),
            values=_hour_values, state="readonly", width=4)
        clk_hour_cb.set(f"{clk_start_hour_var.get():02d}")
        clk_hour_cb.pack(side="left", padx=(0, 4))

        def _on_hour_select(_evt=None):
            try:
                clk_start_hour_var.set(int(clk_hour_cb.get()))
            except Exception:
                pass
        clk_hour_cb.bind("<<ComboboxSelected>>", _on_hour_select)

        tk.Label(stime_row, text=":", bg=C_BG, fg=C_FG,
                 font=("Segoe UI", 9)).pack(side="left", padx=(0, 6))
        for _sm in (0, 15, 30, 45):
            tk.Radiobutton(
                stime_row, text=f"{_sm:02d}", variable=clk_start_var, value=_sm,
                bg=C_BG, fg=C_FG, selectcolor=C_BG2,
                activebackground=C_BG, activeforeground=C_FG,
                font=("Segoe UI", 9), relief="flat"
            ).pack(side="left", padx=(0, 8))

        # Interval (radio buttons: 15, 30, 60)
        clk_interval_var = tk.IntVar(
            value=int(self.settings.get("clock_interval_min", 15)))
        intv_row = tk.Frame(t_play, bg=C_BG)
        intv_row.pack(fill="x", padx=18, pady=(6, 0))
        tk.Label(intv_row, text="Repeat every:", bg=C_BG, fg=C_FG,
                 font=("Segoe UI", 9), width=14, anchor="w").pack(side="left")
        for _iv, _lbl in ((15, "15 min"), (30, "30 min"), (60, "1 hour")):
            tk.Radiobutton(
                intv_row, text=_lbl, variable=clk_interval_var, value=_iv,
                bg=C_BG, fg=C_FG, selectcolor=C_BG2,
                activebackground=C_BG, activeforeground=C_FG,
                font=("Segoe UI", 9), relief="flat"
            ).pack(side="left", padx=(0, 10))

        # Display duration slider (500 – 2500 ms)
        clk_dur_var = tk.DoubleVar(
            value=float(self.settings.get("clock_duration_ms", 1000)))

        def _dur_fmt(v):
            ms = int(round(float(v) / 500) * 500)
            return f"{ms / 1000:.1f} s"

        slider_row(t_play, "Display time:", clk_dur_var,
                   500, 2500, 500, _dur_fmt)

        clock_show_left_var = tk.BooleanVar(
            value=bool(self.settings.get("clock_show_time_left", False)))
        chk_row(t_play, "Show time left  (e.g. \"20:30   -37 min\")", clock_show_left_var)

        tk.Label(t_play,
                 text="Start time sets the first trigger (e.g. 23:30). The clock then repeats\n"
                      "at the chosen interval. With 15 min interval all quarter-hours are shown.",
                 bg=C_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 7, "italic"),
                 justify="left").pack(padx=18, anchor="w", pady=(4, 10))

        # ── Elapsed-time overlay ─────────────────────────────────
        section(t_play, "Elapsed time overlay")
        tk.Label(t_play,
                 text="Flash how many minutes you have been watching at regular intervals.\n"
                      "The text '30 min', '45 min' etc. appears in the same spot as the clock overlay.",
                 bg=C_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 8, "italic"),
                 justify="left").pack(padx=18, anchor="w", pady=(0, 4))

        elapsed_enabled_var = tk.BooleanVar(
            value=bool(self.settings.get("elapsed_overlay", False)))
        chk_row(t_play, "Enable elapsed-time overlay  (default: off)", elapsed_enabled_var)

        # Interval slider 3–60 minutes
        elapsed_interval_var = tk.IntVar(
            value=int(self.settings.get("elapsed_interval_min", 5)))

        def _elapsed_intv_fmt(v):
            return f"{int(round(float(v)))} min"

        slider_row(t_play, "Repeat every:", elapsed_interval_var,
                   3, 60, 1, _elapsed_intv_fmt)

        # Mode: wallclock vs watchtime
        elapsed_mode_var = tk.StringVar(
            value=self.settings.get("elapsed_mode", "wallclock"))
        mode_row = tk.Frame(t_play, bg=C_BG)
        mode_row.pack(fill="x", padx=18, pady=(6, 2))
        tk.Label(mode_row, text="Measure:", bg=C_BG, fg=C_FG,
                 font=("Segoe UI", 9), width=14, anchor="w").pack(side="left")
        for _emv, _eml in (
            ("wallclock", "Minutes since session start"),
            ("watchtime",  "Minutes of film watching"),
        ):
            tk.Radiobutton(
                mode_row, text=_eml, variable=elapsed_mode_var, value=_emv,
                bg=C_BG, fg=C_FG, selectcolor=C_BG2,
                activebackground=C_BG, activeforeground=C_FG,
                font=("Segoe UI", 9), relief="flat",
            ).pack(side="left", padx=(0, 14))

        tk.Label(t_play,
                 text="'Since session start' counts from when the first file was opened (pauses included).\n"
                      "'Film watching' counts actual playback time only (pauses excluded).",
                 bg=C_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 7, "italic"),
                 justify="left").pack(padx=18, anchor="w", pady=(4, 10))

        # ── Hårdvaruacceleration ─────────────────────────────────
        section(t_play, "Hardware acceleration (hwdec)")
        tk.Label(t_play,
                 text="Controls how the GPU is used for video decoding.\n"
                      "auto-safe = mpv chooses safely (default) · auto = more aggressive\n"
                      "no = CPU only · d3d11va/nvdec = specify GPU method.",
                 bg=C_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 7, "italic"),
                 justify="left").pack(padx=18, anchor="w", pady=(0, 4))

        _HWDEC_OPTIONS = ["auto-safe", "auto", "no", "d3d11va", "nvdec", "vaapi"]
        hwdec_var = tk.StringVar(
            value=self.settings.get("hwdec", "auto-safe"))

        hwdec_row = tk.Frame(t_play, bg=C_BG)
        hwdec_row.pack(fill="x", padx=18, pady=(0, 8))
        tk.Label(hwdec_row, text="Method:", bg=C_BG, fg=C_FG,
                 font=("Segoe UI", 9), width=14, anchor="w").pack(side="left")
        import tkinter.ttk as _ttk2
        hwdec_cb = _ttk2.Combobox(
            hwdec_row, textvariable=hwdec_var,
            values=_HWDEC_OPTIONS, state="readonly", width=14)
        hwdec_cb.pack(side="left", padx=(0, 8))
        tk.Label(hwdec_row,
                 text="(takes effect at next playback)",
                 bg=C_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 7, "italic")).pack(side="left")

        # ── Video-rendering & artefaktskydd ──────────────────────
        section(t_play, "Video – rendering & artefact protection")
        tk.Label(t_play,
                 text="Change these if you see ghost-lag, bubbling, or parts of the image\n"
                      "drifting the wrong way. Takes effect at next playback.",
                 bg=C_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 7, "italic"),
                 justify="left").pack(padx=18, anchor="w", pady=(0, 6))

        def _combo_row(parent, label, var, options, tip=""):
            row = tk.Frame(parent, bg=C_BG)
            row.pack(fill="x", padx=18, pady=3)
            tk.Label(row, text=label, bg=C_BG, fg=C_FG,
                     font=("Segoe UI", 9), width=16, anchor="w").pack(side="left")
            import tkinter.ttk as _ttk3
            cb = _ttk3.Combobox(row, textvariable=var,
                                values=options, state="readonly", width=18)
            cb.pack(side="left", padx=(0, 8))
            if tip:
                tk.Label(row, text=tip, bg=C_BG, fg=C_FG_DIM,
                         font=("Segoe UI", 7, "italic")).pack(side="left")
            return cb

        gpu_api_var = tk.StringVar(
            value=self.settings.get("gpu_api", "auto"))
        _combo_row(t_play, "GPU-backend (gpu-api):", gpu_api_var,
                   ["auto", "d3d11", "opengl", "vulkan"],
                   "auto=mpv chooses · d3d11=safest Win · vulkan=modern")

        video_sync_var = tk.StringVar(
            value=self.settings.get("video_sync", "audio"))
        _combo_row(t_play, "Frame timing (video-sync):", video_sync_var,
                   ["audio", "display-resample", "display-vdrop"],
                   "audio=safe · display-resample=smoother but may ghost")

        framedrop_var = tk.StringVar(
            value=self.settings.get("framedrop", "vo"))
        _combo_row(t_play, "Framedrop:", framedrop_var,
                   ["no", "vo", "decoder+vo"],
                   "no=never drop · vo=standard · decoder+vo=aggressive")

        interpolation_var = tk.BooleanVar(
            value=bool(self.settings.get("interpolation", False)))
        chk_row(t_play,
                "Interpolation  ← turn OFF if you see ghost/bubbling",
                interpolation_var,
                "NOTE: requires video-sync=display-resample for effect")

        # ── Audio language priority ──────────────────────────────
        section(t_play, "Audio – language priority")
        tk.Label(t_play,
                 text="One priority per line. Matched against the track language code or title\n"
                      "(case-insensitive, substring match).\n"
                      "Example:  swe   svenska   eng   English",
                 bg=C_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 8, "italic"),
                 justify="left").pack(padx=18, anchor="w", pady=(0, 4))

        audio_prio_frame = tk.Frame(t_play, bg=C_BG)
        audio_prio_frame.pack(fill="x", padx=18, pady=(0, 6))

        audio_prio_txt = tk.Text(
            audio_prio_frame, bg=C_BG2, fg=C_FG,
            font=("Consolas", 9),
            insertbackground=C_FG, relief="flat",
            width=32, height=6,
            padx=6, pady=4)
        audio_prio_txt.pack(side="left", fill="x", expand=True)
        no_blink(audio_prio_txt)

        _prio_list = self.settings.get("audio_lang_priority", [])
        audio_prio_txt.insert("1.0", "\n".join(_prio_list))

        def _audio_prio_reset():
            audio_prio_txt.delete("1.0", "end")
            audio_prio_txt.insert("1.0",
                "\n".join(DEFAULT_SETTINGS["audio_lang_priority"]))

        tk.Button(audio_prio_frame, text="↺", command=_audio_prio_reset,
                  bg=C_BTN, fg="white",
                  activebackground=C_BTN_HOV, activeforeground="white",
                  relief="flat", padx=6, pady=4,
                  font=("Segoe UI", 10), cursor="hand2",
                  ).pack(side="left", padx=(6, 0), anchor="n")

        # ════════════════════════════════════════════════════════
        # TAB 3 — BUTTONS
        # ════════════════════════════════════════════════════════
        t_btns = make_tab("Buttons")

        section(t_btns, "Visibility and order")
        tk.Label(t_btns,
                 text="Check to show the button.  Use ▲▼ to change order.\n"
                      "Order goes left → right in the control bar.",
                 bg=C_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 8, "italic"),
                 justify="left").pack(padx=18, anchor="w", pady=(0, 6))

        btn_order_list = list(self.settings.get("btn_order", list(_BTN_ORDER_DEFAULT)))
        btn_visible_dict = self.settings.get("btn_visible", {})
        # {key: BooleanVar}
        btn_chk_vars = {k: tk.BooleanVar(value=btn_visible_dict.get(k, True))
                        for k in _BTN_DEFS}

        # Scrollable list of rows
        btn_list_outer = tk.Frame(t_btns, bg=C_BG)
        btn_list_outer.pack(fill="both", expand=True, padx=14, pady=(0, 4))

        btn_rows_canvas = tk.Canvas(btn_list_outer, bg=C_BG,
                                    highlightthickness=0, borderwidth=0)
        btn_rows_sb = tk.Scrollbar(btn_list_outer, orient="vertical",
                                   command=btn_rows_canvas.yview)
        btn_rows_canvas.configure(yscrollcommand=btn_rows_sb.set)
        btn_rows_inner = tk.Frame(btn_rows_canvas, bg=C_BG)
        _bwin = btn_rows_canvas.create_window((0, 0), window=btn_rows_inner,
                                              anchor="nw")

        def _btn_rows_resize(e):
            btn_rows_canvas.configure(scrollregion=btn_rows_canvas.bbox("all"))
            btn_rows_canvas.itemconfig(_bwin, width=btn_rows_canvas.winfo_width())
        btn_rows_inner.bind("<Configure>", _btn_rows_resize)
        btn_rows_canvas.bind("<Configure>",
                             lambda e: btn_rows_canvas.itemconfig(
                                 _bwin, width=e.width))

        btn_rows_canvas.pack(side="left", fill="both", expand=True)
        btn_rows_sb.pack(side="right", fill="y")

        def _btn_scroll(e, c=btn_rows_canvas):
            if c.winfo_exists():
                c.yview_scroll(-1 * (e.delta // 120), "units")
        btn_rows_canvas.bind("<Enter>",
                             lambda e, c=btn_rows_canvas, s=_btn_scroll:
                                 c.bind_all("<MouseWheel>", s))
        btn_rows_canvas.bind("<Leave>",
                             lambda e, c=btn_rows_canvas:
                                 c.unbind_all("<MouseWheel>"))

        # One row per button
        _row_widgets = {}   # key -> tk.Frame (the row)

        def _build_btn_list():
            for w in btn_rows_inner.winfo_children():
                w.destroy()
            _row_widgets.clear()
            for key in btn_order_list:
                if key not in _BTN_DEFS:
                    continue
                row = tk.Frame(btn_rows_inner, bg=C_BG2, pady=1)
                row.pack(fill="x", pady=2, padx=2)
                _row_widgets[key] = row
                cb = tk.Checkbutton(row, variable=btn_chk_vars[key],
                                    bg=C_BG2, fg=C_FG,
                                    selectcolor=C_BG,
                                    activebackground=C_BG2, activeforeground=C_FG,
                                    relief="flat", bd=0,
                                    font=("Segoe UI", 9))
                cb.pack(side="left", padx=(6, 2))
                name_lbl = _BTN_DEFS[key]
                tk.Label(row, text=f"{name_lbl}",
                         bg=C_BG2, fg=C_FG,
                         font=("Segoe UI", 9), width=16,
                         anchor="w").pack(side="left", padx=4)
                # Move up / down
                def mk_up(k=key):
                    i = btn_order_list.index(k)
                    if i > 0:
                        btn_order_list[i-1], btn_order_list[i] = \
                            btn_order_list[i], btn_order_list[i-1]
                        _build_btn_list()
                def mk_dn(k=key):
                    i = btn_order_list.index(k)
                    if i < len(btn_order_list) - 1:
                        btn_order_list[i+1], btn_order_list[i] = \
                            btn_order_list[i], btn_order_list[i+1]
                        _build_btn_list()
                _bB = dict(bg=C_BTN, fg="white", relief="flat",
                           activebackground=C_BTN_HOV, activeforeground="white",
                           font=("Segoe UI", 8), padx=5, pady=1, cursor="hand2")
                b_up = tk.Button(row, text="▲", command=mk_up, **_bB)
                b_up.pack(side="left", padx=(0, 2))
                b_dn = tk.Button(row, text="▼", command=mk_dn, **_bB)
                b_dn.pack(side="left")

        _build_btn_list()

        # ════════════════════════════════════════════════════════
        # TAB 4 — VIDEO / APPEARANCE
        # ════════════════════════════════════════════════════════
        t_vid = make_tab("Video")

        panscan_var = tk.DoubleVar(
            value=float(self.settings.get("panscan", 0.0)))

        def _pan_label(val):
            v = float(val)
            if v < 0.05:
                return "Visible (keep aspect ratio)"
            elif v > 0.95:
                return "Gone (fill screen, crop)"
            else:
                return f"Partial ({int(v * 100)} %)"

        section(t_vid, "Black bars")
        vid_row = tk.Frame(t_vid, bg=C_BG)
        vid_row.pack(fill="x", padx=18, pady=(0, 4))
        tk.Label(vid_row, text="Black bars:",
                 bg=C_BG, fg=C_FG,
                 font=("Segoe UI", 9)).pack(side="left")
        pan_lbl = tk.Label(vid_row, text=_pan_label(panscan_var.get()),
                           bg=C_BG, fg=C_FG_DIM,
                           font=("Segoe UI", 9, "italic"),
                           width=34, anchor="w")
        pan_lbl.pack(side="right")

        tk.Scale(t_vid, variable=panscan_var,
                 from_=0.0, to=1.0, resolution=0.05, orient="horizontal",
                 bg=C_BG, fg=C_FG, troughcolor=C_TROUGH,
                 highlightthickness=0, sliderrelief="flat",
                 sliderlength=16, width=10, showvalue=False,
                 command=lambda v: pan_lbl.config(
                     text=_pan_label(v))).pack(
                         fill="x", padx=18, pady=(0, 12))

        # ---- HDR brightness stability ----
        section(t_vid, "HDR brightness")
        hdr_peak_var = tk.BooleanVar(
            value=bool(self.settings.get("hdr_peak_detect", False)))
        tk.Checkbutton(
            t_vid,
            text="Auto-adjust HDR brightness per scene (may flicker)",
            variable=hdr_peak_var,
            bg=C_BG, fg=C_FG, selectcolor=C_BG2,
            activebackground=C_BG, activeforeground=C_FG,
            font=("Segoe UI", 9)).pack(anchor="w", padx=18, pady=(0, 2))
        tk.Label(t_vid,
                 text="Leave OFF for a stable picture. The sudden brightness "
                      "jumps in HDR films come from the player, not the file.",
                 bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 justify="left", wraplength=520).pack(
                     anchor="w", padx=18, pady=(0, 12))

        # ════════════════════════════════════════════════════════
        # TAB 4 — DIRECTORIES
        # ════════════════════════════════════════════════════════
        t_dirs = make_tab("Directories")

        section(t_dirs, "Subtitle directories  (with language labels)")
        tk.Label(t_dirs,
                 text="Searched top-to-bottom, then the film's own folder.  "
                      "Double-click to set language.",
                 bg=C_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 8, "italic")).pack(
                     padx=18, anchor="w", pady=(0, 4))

        # data: list of [path, lang_label]
        dir_data = []
        langs_saved = self.settings.get("subtitle_dir_langs", {})
        for d in self.settings.get("subtitle_dirs", []):
            dir_data.append([d, langs_saved.get(d, "")])

        list_frame = tk.Frame(t_dirs, bg=C_BG)
        list_frame.pack(fill="x", padx=14)

        sb_lb = tk.Scrollbar(list_frame, orient="vertical")
        sb_lb.pack(side="right", fill="y")
        lb = tk.Listbox(list_frame,
                        bg=C_BG2, fg=C_FG,
                        selectbackground=C_BG3, selectforeground=C_FG,
                        activestyle="none",
                        font=("Segoe UI", 9),
                        relief="flat", bd=0,
                        width=52, height=6,
                        yscrollcommand=sb_lb.set)
        lb.pack(side="left", fill="x", expand=True)
        sb_lb.config(command=lb.yview)

        def _lb_refresh():
            lb.delete(0, "end")
            for d, lbl in dir_data:
                display = f"[{lbl}]  {d}" if lbl else d
                lb.insert("end", display)

        _lb_refresh()

        def add_dir():
            d = filedialog.askdirectory(parent=top,
                                        title="Add subtitle directory")
            if not d:
                return
            if any(x[0] == d for x in dir_data):
                return
            lang = _ask_lang(d)
            dir_data.append([d, lang])
            _lb_refresh()

        def remove_dir():
            sel = lb.curselection()
            if sel:
                del dir_data[sel[0]]
                _lb_refresh()

        def move_up():
            sel = lb.curselection()
            if sel and sel[0] > 0:
                i = sel[0]
                dir_data[i - 1], dir_data[i] = dir_data[i], dir_data[i - 1]
                _lb_refresh()
                lb.select_set(i - 1)

        def move_down():
            sel = lb.curselection()
            if sel and sel[0] < len(dir_data) - 1:
                i = sel[0]
                dir_data[i + 1], dir_data[i] = dir_data[i], dir_data[i + 1]
                _lb_refresh()
                lb.select_set(i + 1)

        def edit_lang(_evt=None):
            sel = lb.curselection()
            if not sel:
                return
            i = sel[0]
            new_lang = _ask_lang(dir_data[i][0], current=dir_data[i][1])
            dir_data[i][1] = new_lang
            _lb_refresh()
            lb.select_set(i)

        def _ask_lang(dir_path: str, current: str = "") -> str:
            """Small popup to enter a language name for a sub directory."""
            dlg = tk.Toplevel(top)
            dlg.title("Språk för katalog")
            dlg.configure(bg=C_BG)
            dlg.resizable(False, False)
            dlg.transient(top)
            dlg.grab_set()
            short = os.path.basename(dir_path) or dir_path
            tk.Label(dlg, text=f"Katalog:  {short}",
                     bg=C_BG, fg=C_FG_DIM,
                     font=("Segoe UI", 8, "italic")).pack(
                         padx=14, pady=(10, 2), anchor="w")
            tk.Label(dlg, text="Språk (visas i Sub-knappen):",
                     bg=C_BG, fg=C_FG,
                     font=("Segoe UI", 9)).pack(
                         padx=14, anchor="w")
            var = tk.StringVar(value=current)
            e = tk.Entry(dlg, textvariable=var, bg=C_BG2, fg=C_FG,
                         insertbackground=C_FG, relief="flat",
                         font=("Segoe UI", 9), width=22)
            no_blink(e); e.pack(padx=14, pady=4)
            e.focus_set(); e.select_range(0, "end")
            result = [current]
            def _ok(_=None):
                result[0] = var.get().strip()
                dlg.destroy()
            def _cancel(_=None):
                dlg.destroy()
            br = tk.Frame(dlg, bg=C_BG)
            br.pack(pady=(2, 10))
            ok_b = tk.Button(br, text="OK",     command=_ok,     **_B)
            ca_b = tk.Button(br, text="Avbryt", command=_cancel, **_B)
            ok_b.pack(side="left", padx=4); _bind_hover(ok_b)
            ca_b.pack(side="left", padx=4); _bind_hover(ca_b)
            e.bind("<Return>", _ok)
            e.bind("<Escape>", _cancel)
            dlg.wait_window()
            return result[0]

        lb.bind("<Double-Button-1>", edit_lang)

        dir_btn_f = tk.Frame(t_dirs, bg=C_BG)
        dir_btn_f.pack(fill="x", padx=14, pady=(4, 2))

        for txt, cmd in [("+ Add", add_dir), ("Remove", remove_dir),
                         ("▲ Up", move_up),  ("▼ Down", move_down),
                         ("✏ Language", edit_lang)]:
            b = tk.Button(dir_btn_f, text=txt, command=cmd, **_B)
            b.pack(side="left", padx=(0, 4))
            _bind_hover(b)

        tk.Label(t_dirs,
                 text="Double-click a row to change language.",
                 bg=C_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 7, "italic")).pack(
                     padx=18, anchor="w", pady=(0, 10))

        # ── Ignored prefixes/suffixes (subtitle matching) ──────────────
        section(t_dirs, "Ignored prefixes/suffixes  (subtitle matching)")
        tk.Label(t_dirs,
                 text="Downloaded films often get an extra prefix/suffix, e.g. "
                      "'Downloaded_In_the_grey-source' instead of 'In_the_grey'. "
                      "Exact filename match is always tried first. If a film's "
                      "name starts/ends with a trigger below, subtitles are ALSO "
                      "searched for under the name with that part removed - and "
                      "used as the default only when no exact match exists.",
                 bg=C_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 8, "italic"),
                 justify="left", wraplength=460).pack(
                     padx=18, anchor="w", pady=(0, 4))

        affix_data = [dict(item) for item in
                      self.settings.get("subtitle_ignore_affixes", [])]

        aff_frame = tk.Frame(t_dirs, bg=C_BG)
        aff_frame.pack(fill="x", padx=14)
        aff_sb = tk.Scrollbar(aff_frame, orient="vertical")
        aff_sb.pack(side="right", fill="y")
        aff_lb = tk.Listbox(aff_frame,
                            bg=C_BG2, fg=C_FG,
                            selectbackground=C_BG3, selectforeground=C_FG,
                            activestyle="none",
                            font=("Segoe UI", 9),
                            relief="flat", bd=0,
                            width=52, height=4,
                            yscrollcommand=aff_sb.set)
        aff_lb.pack(side="left", fill="x", expand=True)
        aff_sb.config(command=aff_lb.yview)

        def _aff_refresh():
            aff_lb.delete(0, "end")
            for item in affix_data:
                kind = "Prefix" if item.get("type") == "prefix" else "Suffix"
                aff_lb.insert("end", f"[{kind}]  {item.get('text', '')}")

        _aff_refresh()

        def _ask_affix(current_text: str = "", current_type: str = "prefix"):
            """Small popup to enter an ignored prefix/suffix + its type."""
            dlg = tk.Toplevel(top)
            dlg.title("Ignored prefix/suffix")
            dlg.configure(bg=C_BG)
            dlg.resizable(False, False)
            dlg.transient(top)
            dlg.grab_set()
            tk.Label(dlg, text="Text to ignore  (e.g. Downloaded_ or -source):",
                     bg=C_BG, fg=C_FG,
                     font=("Segoe UI", 9)).pack(
                         padx=14, pady=(10, 2), anchor="w")
            var = tk.StringVar(value=current_text)
            e = tk.Entry(dlg, textvariable=var, bg=C_BG2, fg=C_FG,
                         insertbackground=C_FG, relief="flat",
                         font=("Segoe UI", 9), width=28)
            no_blink(e); e.pack(padx=14, pady=4)
            e.focus_set(); e.select_range(0, "end")

            type_var = tk.StringVar(value=current_type)
            mode_row = tk.Frame(dlg, bg=C_BG)
            mode_row.pack(padx=14, pady=(4, 0), anchor="w")
            tk.Label(mode_row, text="Add as:", bg=C_BG, fg=C_FG,
                     font=("Segoe UI", 9)).pack(side="left")
            for _lbl, _val in (("Prefix", "prefix"), ("Suffix", "suffix")):
                tk.Radiobutton(mode_row, text=_lbl, value=_val,
                               variable=type_var,
                               bg=C_BG, fg=C_FG, selectcolor=C_BG2,
                               activebackground=C_BG, activeforeground=C_FG,
                               font=("Segoe UI", 9), relief="flat",
                               bd=0).pack(side="left", padx=(6, 6))

            result = [None]
            def _ok(_=None):
                text = var.get().strip()
                if text:
                    result[0] = {"text": text, "type": type_var.get()}
                dlg.destroy()
            def _cancel(_=None):
                dlg.destroy()
            br = tk.Frame(dlg, bg=C_BG)
            br.pack(pady=(8, 10))
            ok_b = tk.Button(br, text="OK",     command=_ok,     **_B)
            ca_b = tk.Button(br, text="Cancel", command=_cancel, **_B)
            ok_b.pack(side="left", padx=4); _bind_hover(ok_b)
            ca_b.pack(side="left", padx=4); _bind_hover(ca_b)
            e.bind("<Return>", _ok)
            e.bind("<Escape>", _cancel)
            dlg.wait_window()
            return result[0]

        def add_affix():
            item = _ask_affix()
            if item and not any(i["type"] == item["type"] and
                                i["text"].lower() == item["text"].lower()
                                for i in affix_data):
                affix_data.append(item)
                _aff_refresh()

        def edit_affix(_evt=None):
            sel = aff_lb.curselection()
            if not sel:
                return
            i = sel[0]
            item = _ask_affix(affix_data[i]["text"], affix_data[i]["type"])
            if item:
                affix_data[i] = item
                _aff_refresh()
                aff_lb.select_set(i)

        def remove_affix():
            sel = aff_lb.curselection()
            if sel:
                del affix_data[sel[0]]
                _aff_refresh()

        aff_lb.bind("<Double-Button-1>", edit_affix)

        aff_btn_f = tk.Frame(t_dirs, bg=C_BG)
        aff_btn_f.pack(fill="x", padx=14, pady=(4, 10))
        for txt, cmd in [("+ Add", add_affix), ("✏ Edit", edit_affix),
                         ("Remove", remove_affix)]:
            b = tk.Button(aff_btn_f, text=txt, command=cmd, **_B)
            b.pack(side="left", padx=(0, 4))
            _bind_hover(b)

        tk.Label(t_dirs,
                 text="Always on, no setting needed: Roman/Arabic numerals "
                      "(..._2 ↔ ..._II) and a leading 'The_' (↔ '...,_The') "
                      "are also tried automatically - see Help for details.",
                 bg=C_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 7, "italic"),
                 justify="left", wraplength=460).pack(
                     padx=18, anchor="w", pady=(0, 10))

        # ── Movies directories (for Open list) ────────────────────────
        section(t_dirs, "Movies directories  (for the Open button)")
        tk.Label(t_dirs,
                 text="All video files in these directories - and in their "
                      "sub-folders - are listed in the 'Open' button, sorted A–Z.",
                 bg=C_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 8, "italic")).pack(
                     padx=18, anchor="w", pady=(0, 4))

        movies_dirs_data = list(self.settings.get("movies_dirs", []))

        mlist_frame = tk.Frame(t_dirs, bg=C_BG)
        mlist_frame.pack(fill="x", padx=14)
        msb = tk.Scrollbar(mlist_frame, orient="vertical")
        msb.pack(side="right", fill="y")
        mlb = tk.Listbox(mlist_frame,
                         bg=C_BG2, fg=C_FG,
                         selectbackground=C_BG3, selectforeground=C_FG,
                         activestyle="none",
                         font=("Segoe UI", 9),
                         relief="flat", bd=0,
                         width=52, height=5,
                         yscrollcommand=msb.set)
        mlb.pack(side="left", fill="x", expand=True)
        msb.config(command=mlb.yview)

        def _mlb_refresh():
            mlb.delete(0, "end")
            for d in movies_dirs_data:
                mlb.insert("end", d)
        _mlb_refresh()

        def madd_dir():
            d = filedialog.askdirectory(parent=top, title="Add movies directory")
            if d and d not in movies_dirs_data:
                movies_dirs_data.append(d)
                _mlb_refresh()

        def mremove_dir():
            sel = mlb.curselection()
            if sel:
                del movies_dirs_data[sel[0]]
                _mlb_refresh()

        def mmove_up():
            sel = mlb.curselection()
            if sel and sel[0] > 0:
                i = sel[0]
                movies_dirs_data[i-1], movies_dirs_data[i] = \
                    movies_dirs_data[i], movies_dirs_data[i-1]
                _mlb_refresh(); mlb.select_set(i - 1)

        def mmove_down():
            sel = mlb.curselection()
            if sel and sel[0] < len(movies_dirs_data) - 1:
                i = sel[0]
                movies_dirs_data[i+1], movies_dirs_data[i] = \
                    movies_dirs_data[i], movies_dirs_data[i+1]
                _mlb_refresh(); mlb.select_set(i + 1)

        mdir_btn_f = tk.Frame(t_dirs, bg=C_BG)
        mdir_btn_f.pack(fill="x", padx=14, pady=(4, 10))
        for txt, cmd in [("+ Add", madd_dir), ("Remove", mremove_dir),
                         ("▲ Up", mmove_up),  ("▼ Down", mmove_down)]:
            b = tk.Button(mdir_btn_f, text=txt, command=cmd, **_B)
            b.pack(side="left", padx=(0, 4))
            _bind_hover(b)

        # ── Category folders (where Good / Okay / ... films live) ─────
        section(t_dirs, "Category folders  (DB search)")
        tk.Label(t_dirs,
                 text="Where the films of each movie-database category are. "
                      "DB search looks there first, so it finds a film fast "
                      "and never scans the other disks. Several folders "
                      "(several disks) per category: separate them with a "
                      "comma - or a semicolon if a folder name contains a "
                      "comma. Sub-folders are searched too (up to "
                      f"{self._film_depth()} levels). Leave empty if the "
                      "folders above already hold everything.",
                 bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 justify="left", wraplength=460).pack(
                     padx=18, anchor="w", pady=(0, 4))

        _cdirs_saved = self.settings.get("category_dirs", {}) or {}
        cat_dir_vars = {}
        for _cat in FILM_CATEGORIES:
            _cur = []
            for _k, _v in _cdirs_saved.items():
                if _k.lower() == _cat.lower():
                    _cur += list(_v)
            _var = tk.StringVar(value=", ".join(_cur))
            cat_dir_vars[_cat] = _var
            _row = tk.Frame(t_dirs, bg=C_BG)
            _row.pack(fill="x", padx=14, pady=1)
            tk.Label(_row, text=_cat, width=6, anchor="w", bg=C_BG, fg=C_FG,
                     font=("Segoe UI", 9)).pack(side="left")
            _ent = tk.Entry(_row, textvariable=_var, bg=C_BG2, fg=C_FG,
                            insertbackground=C_FG, relief="flat",
                            font=("Segoe UI", 9))
            no_blink(_ent)
            _ent.pack(side="left", fill="x", expand=True, padx=(0, 6))

            def _browse_cat(v=_var, c=_cat):
                d = filedialog.askdirectory(parent=top,
                                            title=f"Add a folder for '{c}'")
                if d:
                    cur = ft_split_dirs(v.get())
                    if d not in cur:
                        cur.append(d)
                    v.set(("; " if any("," in x for x in cur) else ", ").join(cur))
            _bb = tk.Button(_row, text="Add…", command=_browse_cat, **_B)
            _bb.pack(side="left")
            _bind_hover(_bb)
        tk.Frame(t_dirs, bg=C_BG, height=8).pack()

        # ── Private folders (kept out of every history) ───────────────
        section(t_dirs, "Private folders  (no history)")
        tk.Label(t_dirs,
                 text="Films in these folders - and in any subfolder - are kept out of "
                      "every history: the Latest ▾ list, the Last button, the play "
                      "statistics and the 'Latest 25%' column in the movie DB.\n"
                      "Their playback POSITION is still remembered, in a separate file "
                      "where the key is a hash, so no title is readable there.\n"
                      "Saving also wipes what these films have already left behind; "
                      "their positions are moved over, not lost.",
                 bg=C_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 8, "italic"),
                 justify="left", wraplength=460).pack(
                     padx=18, anchor="w", pady=(0, 4))

        private_dirs_data = list(self.settings.get("private_dirs", []))

        plist_frame = tk.Frame(t_dirs, bg=C_BG)
        plist_frame.pack(fill="x", padx=14)
        psb = tk.Scrollbar(plist_frame, orient="vertical")
        psb.pack(side="right", fill="y")
        plb = tk.Listbox(plist_frame,
                         bg=C_BG2, fg=C_FG,
                         selectbackground=C_BG3, selectforeground=C_FG,
                         activestyle="none",
                         font=("Segoe UI", 9),
                         relief="flat", bd=0,
                         width=52, height=4,
                         yscrollcommand=psb.set)
        plb.pack(side="left", fill="x", expand=True)
        psb.config(command=plb.yview)

        def _plb_refresh():
            plb.delete(0, "end")
            for d in private_dirs_data:
                plb.insert("end", d)
        _plb_refresh()

        def padd_dir():
            d = filedialog.askdirectory(parent=top, title="Add private folder")
            if d and d not in private_dirs_data:
                private_dirs_data.append(d)
                _plb_refresh()

        def premove_dir():
            sel = plb.curselection()
            if sel:
                del private_dirs_data[sel[0]]
                _plb_refresh()

        pdir_btn_f = tk.Frame(t_dirs, bg=C_BG)
        pdir_btn_f.pack(fill="x", padx=14, pady=(4, 10))
        for txt, cmd in [("+ Add", padd_dir), ("Remove", premove_dir)]:
            b = tk.Button(pdir_btn_f, text=txt, command=cmd, **_B)
            b.pack(side="left", padx=(0, 4))
            _bind_hover(b)

        # ── Movie DB path ──────────────────────────────────────────────
        section(t_dirs, "Movie Database (movies.db)")
        db_path_var = tk.StringVar(
            value=self.settings.get("movies_db", "") or MOVIES_DB_DEFAULT)
        db_row = tk.Frame(t_dirs, bg=C_BG)
        db_row.pack(fill="x", padx=14, pady=(0, 4))
        db_entry = tk.Entry(db_row, textvariable=db_path_var,
                            bg=C_BG2, fg=C_FG, insertbackground=C_FG,
                            relief="flat", font=("Segoe UI", 9))
        no_blink(db_entry)
        db_entry.pack(side="left", fill="x", expand=True, padx=(0, 6))
        def _browse_db():
            p = filedialog.askopenfilename(
                parent=top, title="Select movies.db",
                filetypes=[("SQLite database", "*.db"), ("All files", "*.*")])
            if p:
                db_path_var.set(p)
        b_db = tk.Button(db_row, text="Browse…", command=_browse_db, **_B)
        b_db.pack(side="left")
        _bind_hover(b_db)

        # ════════════════════════════════════════════════════════
        # BOTTOM SAVE / CLOSE BAR
        # ════════════════════════════════════════════════════════
        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x", padx=0)

        def save_and_close():
            self.settings["subtitle_dirs"]     = [d for d, _ in dir_data]
            self.settings["subtitle_dir_langs"] = {d: lbl for d, lbl in dir_data if lbl}
            self.settings["subtitle_ignore_affixes"] = list(affix_data)
            self.settings["movies_dirs"]        = list(movies_dirs_data)
            self.settings["category_dirs"]      = {
                c: ft_split_dirs(v.get()) for c, v in cat_dir_vars.items()
                if ft_split_dirs(v.get())}
            self._film_index().clear()      # folders may have changed: read again
            # Private folders: store them, then scrub what their films have
            # already left in the histories (positions are moved, not deleted).
            self.settings["private_dirs"]       = list(private_dirs_data)
            _purged = self._purge_private_history(private_dirs_data)
            self.settings["panscan"]        = round(panscan_var.get(), 2)
            self.settings["hdr_peak_detect"] = bool(hdr_peak_var.get())
            self.settings["sub_scale"]      = round(sub_scale_var.get(), 2)
            self.settings["sub_pos"]        = int(sub_pos_var.get())
            self.settings["sub_plain_text"] = sub_plain_var.get()
            self.settings["sub_live_replace"] = sub_live_var.get()
            self.settings["auto_play_next"] = auto_next_var.get()
            self.settings["skip_seconds"]   = skip_var.get()
            self.settings["arrow_skip"]     = arrow_var.get()
            self.settings["sync_step_ms"]      = sync_step_var.get()
            self.settings["start_fullscreen"]   = start_fs_var.get()
            self.settings["fullscreen_on_play"] = fs_on_play_var.get()
            self.settings["windowed_on_pause"]  = win_on_pause_var.get()
            self.settings["default_max_mode"]   = default_max_mode_var.get()
            self.settings["movies_db"]          = db_path_var.get().strip()
            self.settings["auto_reload_subs"]   = auto_reload_subs_var.get()
            self.settings["hide_cursor_on_play"]= hide_cursor_var.get()
            self.settings["delete_marker"]      = (del_marker_var.get().strip()
                                                   or "0---DELETE-")
            self.settings["delete_marker_mode"] = del_mode_var.get()
            self.settings["clock_overlay"]      = clock_enabled_var.get()
            self.settings["clock_start_hour"]   = clk_start_hour_var.get()
            self.settings["clock_start_minute"] = clk_start_var.get()
            self.settings["clock_interval_min"] = clk_interval_var.get()
            self.settings["clock_duration_ms"]  = int(round(clk_dur_var.get() / 500) * 500)
            self.settings["clock_show_time_left"] = clock_show_left_var.get()
            self.settings["elapsed_overlay"]      = elapsed_enabled_var.get()
            self.settings["elapsed_interval_min"] = elapsed_interval_var.get()
            self.settings["elapsed_mode"]         = elapsed_mode_var.get()
            self.settings["hwdec"]              = hwdec_var.get()
            self.settings["gpu_api"]            = gpu_api_var.get()
            self.settings["video_sync"]         = video_sync_var.get()
            self.settings["framedrop"]          = framedrop_var.get()
            self.settings["interpolation"]      = interpolation_var.get()
            # Audio language priority
            raw = audio_prio_txt.get("1.0", "end").strip()
            self.settings["audio_lang_priority"] = [
                ln.strip() for ln in raw.splitlines() if ln.strip()]
            # Button order/visibility from the Buttons tab
            self.settings["btn_order"]   = list(btn_order_list)
            self.settings["btn_visible"] = {k: v.get() for k, v in btn_chk_vars.items()}
            save_settings(self.settings)
            self._apply_video_settings()
            self._apply_sub_settings()
            self._update_skip_labels()
            self._build_btn_row()
            top.destroy()
            if _purged:
                auto_close_popup(
                    self.root,
                    f"Private folders: cleared {_purged} history entr"
                    f"{'y' if _purged == 1 else 'ies'}.",
                    delay_ms=2000)

        bot = tk.Frame(top, bg=C_BG2)
        bot.pack(fill="x", pady=0)
        save_btn = tk.Button(bot, text="Save & close",
                             command=save_and_close, **_B)
        save_btn.pack(pady=8)
        _bind_hover(save_btn)


    # ---- Transport ----

    def _toggle_play(self) -> None:
        if not self._current_file:
            # Nothing loaded (e.g. just started, or after Stop) - SPACE
            # starts the most recently opened file instead of pause/play.
            self._play_latest()
            return
        if self._player:
            try:
                self._check_replace_mtimes()
                self._player.pause = not self._player.pause
            except Exception:
                pass

    def _play_latest(self) -> None:
        """Open the most recently played file still on disk (SPACE, idle)."""
        for path in self._recent_files():
            if os.path.isfile(path):
                self._open_path(path)
                return

    def _stop(self) -> None:
        self._stats_end_session()
        self._check_replace_mtimes()
        if self._player:
            try:
                self._player.stop()
            except Exception:
                pass
        self._current_file = None
        self._active_sub1  = None
        self._active_sub2  = None
        self._sub_tracks   = []
        self._audio_tracks    = []
        self._active_audio_id = None
        self._seek_var.set(0)
        self._duration = 0.0
        self._time_lbl.configure(text="0:00 / 0:00")
        self._sync_pp_btn(True)
        self._update_sub_button()
        self._update_audio_button()

    # ---- Mark for deletion (rename only; never deletes) ----

    def _mark_for_deletion(self) -> None:
        """Rename the currently loaded file so it is flagged for manual deletion.
        The program NEVER deletes anything itself – it only adds a marker to the
        filename (prefix or suffix, configurable in Settings)."""
        path = self._current_file
        if not path or not os.path.isfile(path):
            auto_close_popup(self.root, "No file loaded to mark.", delay_ms=1200)
            return
        marker = (self.settings.get("delete_marker") or "0---DELETE-").strip()
        mode   = self.settings.get("delete_marker_mode", "prefix")
        folder = os.path.dirname(path)
        name   = os.path.basename(path)
        stem, ext = os.path.splitext(name)
        # Already marked?  Don't double-mark.
        if (mode == "prefix" and name.startswith(marker)) or \
           (mode == "suffix" and stem.endswith(marker)):
            auto_close_popup(self.root, "Already marked for deletion.",
                             delay_ms=1200)
            return
        new_name = (marker + name) if mode == "prefix" else (stem + marker + ext)
        new_path = os.path.join(folder, new_name)
        if os.path.exists(new_path):
            auto_close_popup(self.root, "Target name already exists.",
                             delay_ms=1500)
            return
        # Remember position so playback can resume seamlessly after the rename.
        pos = None
        if self._player:
            try:
                pos = self._player.time_pos
            except Exception:
                pos = None
        # mpv locks the file on Windows – release the handle before renaming.
        self._stats_end_session()
        if self._player:
            try:
                self._player.stop()
            except Exception:
                pass
        self._do_mark_rename(path, new_path, pos, attempts=0)

    def _do_mark_rename(self, old_path: str, new_path: str,
                        pos, attempts: int) -> None:
        """Retry the rename while mpv finishes releasing the file handle."""
        try:
            os.rename(old_path, new_path)
        except OSError:
            if attempts < 20:               # ~1 s total of 50 ms retries
                self.root.after(50, lambda: self._do_mark_rename(
                    old_path, new_path, pos, attempts + 1))
                return
            auto_close_popup(self.root,
                             "Could not rename (file still in use).",
                             delay_ms=1800)
            self._open_path(old_path)        # re-open original; don't leave blank
            return
        # Renamed OK – reload under the new name and resume position.
        self._remember_opened(new_path)
        self._current_file         = new_path
        self._open_path(new_path, resume=False)
        if pos and pos > 1:
            self.root.after(900, lambda p=pos: self._seek_abs(p))
        auto_close_popup(self.root,
                         f"Marked: {os.path.basename(new_path)}", delay_ms=1500)

    def _seek_rel(self, delta: float) -> None:
        if self._player:
            try:
                from_pos = self._player.time_pos or 0.0
                self._player.seek(delta, reference="relative",
                                   precision="keyframes")
                if delta > 0:
                    to_pos = from_pos + delta
                    self._stats_record_ff(from_pos, to_pos, "skip_btn")
            except Exception:
                pass

    def _toggle_mute(self) -> None:
        if self._player:
            try:
                self._player.mute = not self._player.mute
            except Exception:
                pass

    # ---- Volume ----

    def _apply_volume(self, val=None) -> None:
        vol = int(float(val)) if val is not None else self._vol_var.get()
        if self._player:
            try:
                self._player.volume = vol
            except Exception:
                pass
        self.settings["volume"] = vol

    def _vol_delta(self, d: int) -> None:
        self._vol_var.set(max(0, min(200, self._vol_var.get() + d)))
        self._apply_volume()

    # ---- Subtitle / audio sync (like PotPlayer) ----

    def _sub_delay_delta(self, direction: int) -> None:
        """Adjust subtitle delay.  direction: +1 or -1."""
        if not self._player:
            return
        step = self.settings.get("sync_step_ms", 100) / 1000.0
        try:
            cur = float(self._player.sub_delay or 0)
            new_val = round(cur + direction * step, 3)
            self._player.sub_delay = new_val
            auto_close_popup(self.root,
                f"Sub-delay:  {new_val:+.3f} s", delay_ms=700)
        except Exception:
            pass

    def _audio_delay_delta(self, direction: int) -> None:
        """Adjust audio delay.  direction: +1 or -1."""
        if not self._player:
            return
        step = self.settings.get("sync_step_ms", 100) / 1000.0
        try:
            cur = float(self._player.audio_delay or 0)
            new_val = round(cur + direction * step, 3)
            self._player.audio_delay = new_val
            auto_close_popup(self.root,
                f"Audio-delay:  {new_val:+.3f} s", delay_ms=700)
        except Exception:
            pass

    def _ensure_subs_visible(self) -> None:
        """Force sub-visibility on – mpv can silently turn it off on resize."""
        if not self._player:
            return
        film_entry = (self.sub_settings.get(self._current_file, {})
                      if self._current_file else {})
        if film_entry.get("sub_off"):
            return
        try:
            self._player.command("set", "sub-visibility", "yes")
            if self._active_sub2:
                self._player.command("set", "secondary-sub-visibility", "yes")
        except Exception:
            pass
        self._update_sub_button()

    def _sub_delay_reset(self) -> None:
        """Reset subtitle delay to 0."""
        if not self._player:
            return
        try:
            self._player.sub_delay = 0.0
            auto_close_popup(self.root, "Sub-delay:  +0.000 s  (reset)", delay_ms=700)
        except Exception:
            pass

# *************** DEL 12d - SAVE THE , / . SUB-DELAY INTO THE SUBTITLE FILE (S key) ***
# ToDo (2026-11-14): Lars nudges the subtitle with , and . until it fits, then
# presses S.  ONLY when a sub-delay is actually set: the film pauses (the normal
# pause behaviour - small window or stays fullscreen, per Settings), a small
# dialog asks "update the subtitle file?", Enter = Yes.  Yes: the old file is
# copied to BACKUP-<name>, every time in the real file is shifted by the delay
# (together with any sync points of the Sync dialog, which are then cleared),
# the temporary delay goes back to 0 and the subtitle is loaded again - the
# picture on screen is unchanged, but the file is now correct.  No / Esc: nothing
# is touched and the delay stays.  Playback resumes if it was running.
# Still open: only the primary subtitle (Sub 1) is written, never Sub 2.

    def _clear_stale_sub_delay(self) -> None:
        """mpv keeps its sub-delay when another subtitle or film is loaded, so a
        nudge made for one subtitle would silently ride along to the next (and
        S would then bake it into the wrong file).  Called when the primary
        subtitle changes or a new film opens: the nudge goes back to 0."""
        if not self._player:
            return
        try:
            if abs(float(self._player.sub_delay or 0)) >= 0.0005:
                self._player.sub_delay = 0.0
                auto_close_popup(self.root,
                                 "Sub-delay reset  (new subtitle)", delay_ms=900)
        except Exception:
            pass

    def _sub_delay_save_prompt(self, event=None) -> None:
        """S key.  Silent no-op unless a , / . delay is set (Lars: ONLY then)."""
        if isinstance(getattr(event, "widget", None), (tk.Entry, tk.Text)):
            return                       # typing a letter in a text box
        if self._sub_save_busy or not self._player or not self._current_file:
            return
        try:
            delay = float(self._player.sub_delay or 0)
        except Exception:
            delay = 0.0
        if abs(delay) < 0.0005:
            return
        sub = self._active_sub1
        if not sub or not os.path.isfile(sub):
            auto_close_popup(self.root, "No subtitle file to update.")
            return
        if os.path.splitext(sub)[1].lower() not in (".srt", ".ass", ".ssa"):
            auto_close_popup(self.root,
                             "Only .srt / .ass / .ssa files can be updated.",
                             delay_ms=1800)
            return
        self._sub_save_busy = True
        try:
            was_playing = not bool(self._player.pause)
        except Exception:
            was_playing = False
        try:
            self._player.pause = True    # observer applies "small window on pause"
        except Exception:
            pass
        # Wait a moment so the window has settled in its pause size first.
        self.root.after(250, lambda: self._show_sub_delay_save_dialog(
            sub, delay, was_playing))

    def _show_sub_delay_save_dialog(self, sub: str, delay: float,
                                    was_playing: bool) -> None:
        name  = os.path.basename(sub)
        short = name if len(name) <= 56 else name[:26] + "…" + name[-27:]
        top = tk.Toplevel(self.root)
        self._sub_save_dlg = top
        top.title("Update subtitle file")
        top.configure(bg=C_BG)
        top.resizable(False, False)
        top.transient(self.root)
        W, H = 500, 250
        try:
            self.root.update_idletasks()
            x = self.root.winfo_rootx() + max(0, (self.root.winfo_width()  - W) // 2)
            y = self.root.winfo_rooty() + max(0, (self.root.winfo_height() - H) // 2)
        except Exception:
            x, y = 200, 200
        top.geometry(f"{W}x{H}+{x}+{y}")

        def finish() -> None:
            """Close the dialog, give the keys back to the player, resume."""
            self._sub_save_dlg  = None
            self._sub_save_busy = False
            try:
                top.destroy()
            except Exception:
                pass
            if was_playing and self._player:
                try:
                    self._player.pause = False
                except Exception:
                    pass
            try:
                self.root.focus_force()
            except Exception:
                pass

        def do_yes() -> None:
            self._bake_sub_delay(sub, delay, top)
            finish()

        hdr = tk.Frame(top, bg=C_BG3)
        hdr.pack(fill="x")
        tk.Label(hdr, text="  Update the subtitle file?", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 10, "bold")).pack(side="left", pady=8)
        tk.Label(top, bg=C_BG, fg=C_FG, justify="left", anchor="nw",
                 wraplength=W - 40, font=("Segoe UI", 10),
                 text=(f"The subtitle is shifted {delay:+.3f} s.\n\n"
                       f"Write this into the file\n{short}\n"
                       "and set the delay back to 0?\n\n"
                       f"The old file is kept as BACKUP-{short}")
                 ).pack(fill="both", expand=True, padx=20, pady=(12, 0))

        row = tk.Frame(top, bg=C_BG)
        row.pack(fill="x", padx=20, pady=14)
        yes_btn = tk.Button(row, text="Yes  (Enter)", command=do_yes,
                            bg=C_ACCENT, fg="white", activebackground=C_ACCENT,
                            activeforeground="white", relief="flat",
                            padx=18, pady=6, font=("Segoe UI", 10, "bold"),
                            cursor="hand2", width=12)
        yes_btn.pack(side="left")
        no_btn = tk.Button(row, text="No  (Esc)", command=finish,
                           bg=C_BTN, fg="white", activebackground=C_BTN_HOV,
                           activeforeground="white", relief="flat",
                           padx=18, pady=6, font=("Segoe UI", 10),
                           cursor="hand2", width=12)
        no_btn.pack(side="left", padx=(10, 0))
        _bind_hover(no_btn)

        # Modal, in the house order: grab_set -> focus_force -> Escape.
        try:
            top.wait_visibility()
            top.grab_set()
        except Exception:
            pass
        top.focus_force()
        yes_btn.focus_set()
        top.bind("<Escape>",    lambda _: finish())
        top.bind("<Return>",    lambda _: do_yes())
        top.bind("<KP_Enter>",  lambda _: do_yes())
        top.protocol("WM_DELETE_WINDOW", finish)

    def _bake_sub_delay(self, sub: str, delay: float, parent) -> bool:
        """Write the sub-delay (plus any Sync-dialog points) into *sub*, back
        up the old file, reset the delay to 0 and load the subtitle again.
        Returns True on success; on failure shows why and changes nothing."""
        entry  = self.sub_sync.get(self._current_file, {})
        points = entry.get("points") if entry.get("sub_path") == sub else None
        base_remap = build_sync_remap(points) if points else (lambda t: t)
        remap = lambda t: max(0.0, base_remap(t) + delay)

        backup, err = bake_subtitle_file(sub, remap)
        if err:
            try:
                messagebox.showerror("Update subtitle file", err, parent=parent)
            except Exception:
                pass
            return False

        # The file now holds the corrected times for real - drop everything
        # that would apply the same correction a second time on top of it.
        if points:
            self.sub_sync.pop(self._current_file, None)
            save_sub_sync(self.sub_sync)
        if self._sync_dialog is not None:
            try:
                self._sync_dialog._on_close()    # its points/cues are stale now
            except Exception:
                self._sync_dialog = None
        try:
            self._player.sub_delay = 0.0
        except Exception:
            pass
        self._reload_subs()                      # also re-records the file's mtime
        try:
            temp = os.path.join(SUB_SYNC_TEMP, f"_sync_{os.path.basename(sub)}")
            if os.path.isfile(temp):
                os.remove(temp)
        except Exception:
            pass
        auto_close_popup(self.root,
                         "✓ Subtitle file updated  (old one = BACKUP-)",
                         delay_ms=1800)
        return True

    def _audio_delay_reset(self) -> None:
        """Reset audio delay to 0."""
        if not self._player:
            return
        try:
            self._player.audio_delay = 0.0
            auto_close_popup(self.root, "Audio-delay:  +0.000 s  (reset)", delay_ms=700)
        except Exception:
            pass

    def _play_next_file(self) -> None:
        """Manually trigger play-next."""
        if self._current_file:
            nxt = self._find_next_file(self._current_file)
            if nxt:
                self._open_path(nxt)
            else:
                auto_close_popup(self.root, "No next file in folder")

    def _update_skip_labels(self) -> None:
        """Update << / >> button labels when skip_seconds changes."""
        s = int(self.settings.get("skip_seconds", 10))
        try:
            self._btn_rw.configure(text=f"<< -{s}s")
            self._btn_fw.configure(text=f"+{s}s >>")
        except Exception:
            pass

    def _build_btn_row(self) -> None:
        """(Re-)pack the left button cluster per btn_order / btn_visible."""
        order   = self.settings.get("btn_order",   list(_BTN_ORDER_DEFAULT))
        visible = self.settings.get("btn_visible", {})

        # Destroy old separators
        for w in self._left_frame.winfo_children():
            if isinstance(w, tk.Frame):
                w.destroy()
            else:
                w.pack_forget()

        prev_group = None
        for key in order:
            if visible.get(key, True) is False:
                continue
            grp = _BTN_GROUPS.get(key, 99)
            if prev_group is not None and grp != prev_group:
                tk.Frame(self._left_frame, bg=C_SEP, width=1).pack(
                    side="left", fill="y", padx=5, pady=4)
            w = self._all_btns.get(key)
            if w:
                w.pack(side="left", padx=2)
            prev_group = grp

    def _seek_frac_from_x(self, x: int) -> float:
        """Map an x pixel on the seek bar to a 0.0–1.0 fraction, accounting for
        the slider handle width so a click lands exactly under the pointer."""
        w = self._seek_bar.winfo_width()
        sl = 18                      # sliderlength set on the Scale
        travel = max(1, w - sl)      # the handle centre travels over this span
        return max(0.0, min(1.0, (x - sl / 2) / travel))

    def _on_seek_click(self, event) -> None:
        """Jump immediately to the clicked position, and prepare for a drag."""
        self._seeking = True
        # Capture pre-click position for FF stats
        if self._player:
            try:
                p = self._player.time_pos
                self._stats_seek_from = float(p) if p is not None else None
            except Exception:
                self._stats_seek_from = None
        self._seek_to_frac(self._seek_frac_from_x(event.x))
        return "break"               # suppress tk.Scale's default page-step

    def _on_seek_motion(self, event) -> None:
        """Live scrub while dragging anywhere on the bar."""
        if not self._seeking:
            return "break"
        self._seek_to_frac(self._seek_frac_from_x(event.x))
        return "break"

    def _seek_to_frac(self, frac: float) -> None:
        """Move both the slider and the player to the given 0.0–1.0 fraction."""
        self._seek_var.set(frac * 1000.0)
        if not self._player:
            return
        try:
            dur = self._player.duration or self._duration or 0.0
            if dur > 0:
                pos = frac * dur
                self._player.seek(pos, reference="absolute",
                                  precision="keyframes")
                self._time_lbl.configure(
                    text=f"{fmt_time(pos)} / {fmt_time(dur)}")
        except Exception:
            pass

    def _on_seek_drag(self, val) -> None:
        """Scale 'command' callback – kept for keyboard/programmatic var changes."""
        if not self._seeking or not self._player:
            return
        dur = self._player.duration or self._duration or 0.0
        if dur <= 0:
            return
        pos = float(val) / 1000.0 * dur
        self._time_lbl.configure(text=f"{fmt_time(pos)} / {fmt_time(dur)}")
        try:
            self._player.seek(pos, reference="absolute", precision="keyframes")
        except Exception:
            pass

    def _on_seek_release(self, _e) -> None:
        """Exact-precision seek on mouse-up for frame-accurate landing."""
        if self._player:
            dur = self._player.duration or self._duration or 0.0
            if dur > 0:
                pos = self._seek_var.get() / 1000.0 * dur
                try:
                    self._player.seek(pos, reference="absolute",
                                       precision="exact")
                except Exception:
                    pass
                # Record as FF if user jumped forward by more than threshold
                from_pos = self._stats_seek_from
                if from_pos is not None and pos > from_pos:
                    self._stats_record_ff(from_pos, pos, "seek_drag")
        self._stats_seek_from = None
        self._seeking = False

    # ---- Periodic resume save (every 30 s) ----

    def _schedule_resume_save(self) -> None:
        self._do_save_resume()
        self._save_id = self.root.after(30_000, self._schedule_resume_save)

    def _do_save_resume(self) -> None:
        if self._player and self._current_file:
            try:
                pos = self._player.time_pos
                dur = self._player.duration or self._duration or 0.0
                if pos and pos > 5:
                    # Routes a private film to its own hashed store.
                    self._resume_set(self._current_file, pos, dur)
            except Exception:
                pass


# *************** DEL 12c - BLUETOOTH BUTTON (headphones) ***************
# The 🎧 button, far right.  Click = (re)connect the headset chosen earlier.
# First click with nothing chosen opens the chooser.  Choose another headset
# later with the right-click menu.  The Win32 work is in DEL 21 and runs in a
# worker thread; tk is only touched from the poll below (main thread).

    def _bt_set_label(self, text: str) -> None:
        try:
            self._all_btns["bluetooth"].configure(text=text)
        except Exception:
            pass

    def _bt_reset_label_later(self, ms: int = 3500) -> None:
        if self._bt_label_id:
            try:
                self.root.after_cancel(self._bt_label_id)
            except Exception:
                pass
        self._bt_label_id = self.root.after(
            ms, lambda: self._bt_set_label(_BTN_DEFS["bluetooth"]))

    def _bt_button_click(self) -> None:
        """Connect the chosen headset, or ask which one to use the first time."""
        if self._bt_busy:
            return
        if not self.settings.get("bt_device_addr"):
            self._bt_choose_device(connect_after=True)
            return
        self._bt_start_connect()

    def _bt_start_connect(self) -> None:
        addr = self.settings.get("bt_device_addr", "")
        if not addr or self._bt_busy:
            return
        self._bt_busy = True
        self._bt_result = None
        self._bt_set_label("🎧 Wait…")

        def work():
            try:
                self._bt_result = bt_connect(addr)
            except Exception as exc:                 # never leave the UI waiting
                self._bt_result = (False, f"Bluetooth error: {exc}")

        threading.Thread(target=work, daemon=True).start()
        self.root.after(250, self._bt_poll_result)

    def _bt_poll_result(self) -> None:
        if self._bt_result is None:
            self.root.after(250, self._bt_poll_result)
            return
        ok, msg = self._bt_result
        self._bt_busy = False
        if ok:
            self._bt_set_label("🎧 Connected")
            self._bt_reset_label_later()
            # Make a running film pick up the headset as its sound output.
            if self._player:
                try:
                    self._player.command("ao-reload")
                except Exception:
                    pass
        else:
            self._bt_set_label("🎧 Failed")
            self._bt_reset_label_later(6000)
            messagebox.showwarning("Bluetooth", msg, parent=self.root)

    def _bt_choose_device(self, connect_after: bool = False) -> None:
        """Modal list of the headsets paired in Windows; the pick is saved."""
        try:
            devices = bt_list_devices()
        except Exception as exc:
            messagebox.showerror("Bluetooth", f"Could not read the Bluetooth "
                                 f"devices:\n{exc}", parent=self.root)
            return
        if not devices:
            messagebox.showwarning(
                "Bluetooth",
                "Windows shows no paired Bluetooth devices (or no working "
                "Bluetooth adapter).\n\nPair the headset once in Windows > "
                "Settings > Bluetooth & devices, then try again.",
                parent=self.root)
            return

        top = tk.Toplevel(self.root)
        top.title("Choose Bluetooth headphones")
        top.configure(bg=C_BG)
        _place_top_center(top, 460, 380)
        top.resizable(False, False)
        top.transient(self.root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda _: top.destroy())

        tk.Label(top, text="Paired in Windows - pick the headphones this "
                           "button should connect:",
                 bg=C_BG, fg=C_FG, font=("Segoe UI", 10),
                 wraplength=420, justify="left").pack(
                     anchor="w", padx=14, pady=(12, 6))

        show_all = tk.BooleanVar(value=not any(d["audio"] for d in devices))
        lb = tk.Listbox(top, bg=C_BG2, fg=C_FG, selectbackground="#e94560",
                        selectforeground="white", activestyle="none",
                        font=("Segoe UI", 11), relief="flat",
                        highlightthickness=0, exportselection=False)
        lb.pack(fill="both", expand=True, padx=14, pady=4)
        shown = []

        def fill():
            lb.delete(0, "end")
            shown.clear()
            cur = self.settings.get("bt_device_addr", "")
            sel = 0
            for d in devices:
                if not (d["audio"] or show_all.get()):
                    continue
                mark = "●" if d["connected"] else "○"
                star = "   (chosen)" if d["addr"] == cur else ""
                lb.insert("end", f" {mark}  {d['name']}{star}")
                if d["addr"] == cur:
                    sel = len(shown)
                shown.append(d)
            if shown:
                lb.selection_set(sel)
                lb.see(sel)

        fill()
        tk.Checkbutton(top, text="Show devices that are not headphones/speakers",
                       variable=show_all, command=fill,
                       bg=C_BG, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG, activeforeground=C_FG,
                       font=("Segoe UI", 9)).pack(anchor="w", padx=12)
        tk.Label(top, text="●  connected right now      ○  paired, not connected",
                 bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 8)).pack(
                     anchor="w", padx=14)

        def use():
            sel = lb.curselection()
            if not sel:
                return
            d = shown[sel[0]]
            self.settings["bt_device_addr"] = d["addr"]
            self.settings["bt_device_name"] = d["name"]
            save_settings(self.settings)
            top.destroy()
            if connect_after:
                self._bt_start_connect()

        row = tk.Frame(top, bg=C_BG)
        row.pack(pady=10)
        _B = dict(bg=C_BTN, fg="white", activebackground=C_BTN_HOV,
                  activeforeground="white", relief="flat", padx=12, pady=5,
                  font=("Segoe UI", 10), cursor="hand2")
        b1 = tk.Button(row, text="Use this one" + (" + connect" if connect_after
                                                   else ""),
                       command=use, **_B)
        b1.pack(side="left", padx=6)
        _bind_hover(b1)
        b2 = tk.Button(row, text="Cancel", command=top.destroy, **_B)
        b2.pack(side="left", padx=6)
        _bind_hover(b2)
        lb.bind("<Double-Button-1>", lambda _: use())
        lb.bind("<Return>", lambda _: use())
        lb.focus_set()

    def _bt_context_entries(self, m: tk.Menu) -> None:
        """Bluetooth lines for the right-click menu."""
        name = self.settings.get("bt_device_name", "")
        if self.settings.get("bt_device_addr"):
            m.add_command(label=f"🎧  Connect  {name}",
                          command=self._bt_button_click)
            m.add_command(label="🎧  Choose other Bluetooth headphones...",
                          command=lambda: self._bt_choose_device(False))
        else:
            m.add_command(label="🎧  Choose Bluetooth headphones...",
                          command=lambda: self._bt_choose_device(True))


# *************** DEL 13 - AUTO-HIDE CONTROLS ***************

    def _on_mouse_move(self, event) -> None:
        """Show controls when cursor is in the bottom zone; hide immediately
        when it leaves. In non-fullscreen modes controls are always visible."""
        # Always restore cursor on movement; reschedule hide if playing
        if self._cursor_hidden:
            self._show_cursor()
        self._schedule_cursor_hide()

        if not self._is_fullscreen:
            if self._hide_id:
                self.root.after_cancel(self._hide_id)
                self._hide_id = None
            self._show_controls()
            return

        # --- Fullscreen only: show/hide based on bottom zone ---
        try:
            abs_y    = event.widget.winfo_rooty() + event.y
            root_top = self.root.winfo_rooty()
            root_h   = self.root.winfo_height()
            in_zone  = (abs_y - root_top) >= root_h - CTRL_SHOW_ZONE
        except Exception:
            in_zone = False

        if in_zone:
            if self._hide_id:
                self.root.after_cancel(self._hide_id)
                self._hide_id = None
            self._show_controls()
        else:
            # Hide immediately when cursor leaves the zone
            if self._ctrl_visible:
                self._hide_controls()

    def _show_controls(self) -> None:
        self._ctrl_visible = True
        self.ctrl_bar.place(relx=0, rely=1.0, anchor="sw", relwidth=1.0)
        self.ctrl_bar.lift()

    def _hide_controls(self) -> None:
        self._ctrl_visible = False
        self.ctrl_bar.place_forget()

    # ── Cursor hide / show ────────────────────────────────────────

    def _hide_cursor(self) -> None:
        """Hide mouse cursor (only when playing + hide_cursor_on_play enabled)."""
        if not self.settings.get("hide_cursor_on_play", True):
            return
        if self._player:
            try:
                paused = self._player.pause
            except Exception:
                paused = True
            if paused:
                return
        self._cursor_hidden = True
        try:
            self.root.config(cursor="none")
        except Exception:
            pass

    def _show_cursor(self) -> None:
        """Restore mouse cursor."""
        self._cursor_hidden = False
        try:
            self.root.config(cursor="")
        except Exception:
            pass

    def _schedule_cursor_hide(self) -> None:
        """Schedule cursor hide 2 s after last movement (only during playback)."""
        if not self.settings.get("hide_cursor_on_play", True):
            return
        self._cancel_cursor_hide()
        self._cursor_hide_id = self.root.after(2000, self._hide_cursor)

    def _cancel_cursor_hide(self) -> None:
        if self._cursor_hide_id:
            try:
                self.root.after_cancel(self._cursor_hide_id)
            except Exception:
                pass
            self._cursor_hide_id = None

    # ── Subtitle mtime auto-reload ────────────────────────────────

    def _check_sub_mtimes(self) -> None:
        """Reload active subtitle tracks if their files have changed on disk."""
        if not self.settings.get("auto_reload_subs", True):
            return
        changed = False
        for path in (self._active_sub1, self._active_sub2):
            if not path or not os.path.isfile(path):
                continue
            try:
                mt = os.path.getmtime(path)
            except Exception:
                continue
            prev = self._sub_mtimes.get(path)
            if prev is None:
                self._sub_mtimes[path] = mt
            elif mt != prev:
                self._sub_mtimes[path] = mt
                changed = True
        if changed:
            self._reload_subs()
            auto_close_popup(self.root, "↺  Subtitle reloaded", delay_ms=900)

    def _record_sub_mtime(self, path: str) -> None:
        if path and os.path.isfile(path):
            try:
                self._sub_mtimes[path] = os.path.getmtime(path)
            except Exception:
                pass

    def _check_replace_mtimes(self) -> None:
        """Reload active subtitles if any replace-JSON in SUB_REPLACE_DIR has changed.

        Called at play/pause/stop — not on a timer.
        """
        if not self.settings.get("sub_live_replace", True):
            return
        if not self._active_sub1:
            return
        changed = False
        try:
            for fname in os.listdir(SUB_REPLACE_DIR):
                if not fname.endswith(".json"):
                    continue
                fpath = os.path.join(SUB_REPLACE_DIR, fname)
                try:
                    mt = os.path.getmtime(fpath)
                except Exception:
                    continue
                prev = self._replace_mtimes.get(fpath)
                if prev is None:
                    self._replace_mtimes[fpath] = mt
                elif mt != prev:
                    self._replace_mtimes[fpath] = mt
                    changed = True
        except Exception:
            pass
        if changed:
            self._reload_subs()
            auto_close_popup(self.root, "↺  Replace list updated", delay_ms=1200)

    def _show_sub_loaded_popup(self) -> None:
        """Show a colored popup describing which subtitle(s) were loaded.

        Green  – exactly one sub found (unambiguous match).
        Orange – multiple subs found across directories (Sub ▾ to choose).
        No popup if no subtitles were found.
        """
        n = len(self._sub_tracks)
        if n == 0:
            return
        if n == 1:
            lbl, _path = self._sub_tracks[0]
            msg = f"▶  Subtitle: {lbl}"
            color = "#1a7a3a"   # green
        else:
            labels = "  /  ".join(l for l, _ in self._sub_tracks)
            msg = f"⚠  Multiple subtitles: {labels}"
            color = "#b85c00"   # orange
        auto_close_popup(self.root, msg, delay_ms=900, bg=color)

    # ── Subtitle live word-replacement ───────────────────────────

    def _detect_sub_lang(self, sub_path: str) -> str:
        """Return lower-case language name for a subtitle file, or '' if unknown.

        Priority:
        1. Label already resolved in _sub_tracks (set when the film was opened).
           This is the most reliable source — no path-normalisation needed.
        2. The subtitle directory's language label (Settings → Directories),
           checked from the most-specific (longest) path to the least-specific
           so that a child ENG-dir beats a parent SWE-dir.
        3. Auto-detect from file content — ONLY if no directory label applies at
           all (i.e. the file is not in any of the configured subtitle dirs).
        """
        norm_sub = os.path.normcase(os.path.abspath(sub_path))

        # 1. Direct lookup in the already-resolved track list
        for lbl, path in getattr(self, "_sub_tracks", []):
            if os.path.normcase(os.path.abspath(path)) == norm_sub:
                if lbl and lbl != "(film)":
                    return lbl.lower()
                # Sub is in the film folder — no language label → skip to step 3
                break

        # 2. Directory label lookup (longest / most-specific path wins)
        langs = self.settings.get("subtitle_dir_langs", {})
        sub_dir_norm = os.path.normcase(os.path.abspath(os.path.dirname(sub_path)))
        dir_matched = False
        for d, lang in sorted(langs.items(), key=lambda x: len(x[0]), reverse=True):
            if not lang:
                continue
            d_norm = os.path.normcase(os.path.abspath(d))
            if norm_sub.startswith(d_norm + os.sep) or sub_dir_norm == d_norm:
                dir_matched = True
                return lang.lower()

        # 3. Auto-detect — only when the sub is not inside any labeled directory.
        #    A labeled directory with no matching word-list is fine (replacements
        #    simply won't fire), but we must NOT let content-sniffing override an
        #    explicit language label (e.g. English subs that contain Swedish names).
        if dir_matched:
            return ""
        try:
            with open(sub_path, "r", encoding="utf-8", errors="ignore") as fh:
                sample = fh.read(5000).lower()
            if any(c in sample for c in "åäö"):
                return "svenska"
            if _re.search(r'\b(yes|no)\b', sample):
                return "english"
        except Exception:
            pass
        return ""

    def _apply_sub_replacements(self, sub_path: str, lang: str) -> str:
        """Return path to a processed temp copy of *sub_path* with replacements applied.

        Falls back to the original path if: no replacements defined, no changes
        made, or any error occurs.  Supports .srt and .ass/.ssa formats.
        """
        replacements = load_replace_list(lang)
        if not replacements:
            return sub_path

        # Build a single combined regex (longest keys first to avoid partial matches)
        try:
            pattern = _re.compile(
                r'\b(' + '|'.join(
                    _re.escape(k) for k in sorted(replacements, key=len, reverse=True)
                ) + r')\b',
                _re.IGNORECASE | _re.UNICODE,
            )
        except Exception:
            return sub_path

        def _repl(m):
            token = m.group(0)
            replacement = replacements.get(token.lower(), token)
            # Preserve capitalisation of original token
            if token.isupper():
                return replacement.upper()
            if token[0].isupper():
                return replacement[0].upper() + replacement[1:]
            return replacement

        try:
            with open(sub_path, "r", encoding="utf-8", errors="ignore") as fh:
                content = fh.read()
        except Exception:
            return sub_path

        ext = os.path.splitext(sub_path)[1].lower()

        if ext == ".srt":
            lines = content.splitlines(keepends=True)
            out = []
            for line in lines:
                s = line.strip()
                # Leave blank lines, index lines, and timestamp lines untouched
                if (not s
                        or s.isdigit()
                        or _re.match(r'^\d{2}:\d{2}:\d{2}[.,]\d{3}\s*-->', s)):
                    out.append(line)
                else:
                    out.append(pattern.sub(_repl, line))
            new_content = "".join(out)

        elif ext in (".ass", ".ssa"):
            lines = content.splitlines(keepends=True)
            out = []
            for line in lines:
                if line.startswith("Dialogue:"):
                    # ASS dialogue format: Dialogue: layer,start,end,...,text
                    # Text begins after the 9th comma (index 9 in 10-part split)
                    parts = line.split(",", 9)
                    if len(parts) == 10:
                        parts[9] = pattern.sub(_repl, parts[9])
                        out.append(",".join(parts))
                    else:
                        out.append(line)
                else:
                    out.append(line)
            new_content = "".join(out)

        else:
            return sub_path   # unsupported format

        if new_content == content:
            return sub_path   # nothing changed – skip temp file

        lang_key = _lang_file_key(lang)
        base = os.path.basename(sub_path)
        temp_path = os.path.join(SUB_REPLACE_TEMP, f"_{lang_key}_{base}")
        try:
            with open(temp_path, "w", encoding="utf-8") as fh:
                fh.write(new_content)
            return temp_path
        except Exception:
            return sub_path

    def _get_effective_sub_path(self, sub_path: str) -> str:
        """Return the sub path that should actually be fed to mpv.

        Two independent temp-copy steps are chained, each skipped when it
        doesn't apply:
          1. Sync time-remap  - if anchor points exist for this film+sub
             (see DEL 20b / SubSyncDialog), rewrite every timestamp through
             the piecewise mapping built from them.
          2. Live word-replacement - if enabled and a matching word list
             exists for the detected language.
        Returns *sub_path* unchanged if neither step produces a change.
        """
        if not sub_path or not os.path.isfile(sub_path):
            return sub_path

        path = self._apply_sub_resync(sub_path)

        if self.settings.get("sub_live_replace", True):
            lang = self._detect_sub_lang(sub_path)   # detect from the ORIGINAL path
            if lang:
                path = self._apply_sub_replacements(path, lang)

        return path

    def _apply_sub_resync(self, sub_path: str) -> str:
        """Return path to a time-remapped temp copy of *sub_path*, based on
        saved sync anchor points for the current film - or *sub_path*
        unchanged if no anchors are defined for this exact film+sub pair."""
        if not self._current_file:
            return sub_path
        entry = self.sub_sync.get(self._current_file, {})
        if entry.get("sub_path") != sub_path or not entry.get("points"):
            return sub_path

        remap = build_sync_remap(entry["points"])
        new_content = rewrite_subtitle_times(sub_path, remap)
        if new_content is None:
            return sub_path   # unsupported format - leave subtitle untouched

        base = os.path.basename(sub_path)
        temp_path = os.path.join(SUB_SYNC_TEMP, f"_sync_{base}")
        try:
            with open(temp_path, "w", encoding="utf-8") as fh:
                fh.write(new_content)
            return temp_path
        except Exception:
            return sub_path

    # ── Private folders ───────────────────────────────────────────

    def _is_private(self, path: str) -> bool:
        """True for a film that must stay out of every history."""
        return is_private_path(path, self.settings.get("private_dirs", []))

    def _resume_get(self, path: str):
        """Saved position for a film, from whichever store it belongs in."""
        if self._is_private(path):
            return get_resume_pos(self.resume_private, private_key(path))
        return get_resume_pos(self.resume_data, path)

    def _resume_set(self, path: str, pos: float, dur: float) -> None:
        if self._is_private(path):
            set_resume_pos(self.resume_private, private_key(path), pos, dur)
            save_private_resume(self.resume_private)
        else:
            set_resume_pos(self.resume_data, path, pos, dur)
            save_resume(self.resume_data)

    def _resume_clear(self, path: str) -> None:
        """Drop the saved position (film watched to the end)."""
        if self._is_private(path):
            if self.resume_private.pop(private_key(path), None) is not None:
                save_private_resume(self.resume_private)
        else:
            if self.resume_data.pop(path, None) is not None:
                save_resume(self.resume_data)

    def _remember_opened(self, path: str) -> None:
        """Record 'last file' + 'last dir' - unless the film is private.
        A private film must not steer the Open dialog to its folder either,
        so last_dir is skipped as well."""
        if self._is_private(path):
            return
        self.settings["last_dir"]  = os.path.dirname(path)
        self.settings["last_file"] = path

    def _purge_private_history(self, private_dirs) -> int:
        """Delete every existing history trace for films that are now private.
        Playback positions are MOVED to the private store, not thrown away.
        Returns how many entries were cleaned."""
        removed = 0

        # 0. A film from a folder just made private may be playing RIGHT NOW.
        #    Drop its open session so _stats_end_session writes nothing.
        if self._stats_session and is_private_path(
                self._stats_session.get("_path", ""), private_dirs):
            self._stats_session = None

        # 1. Latest menu
        recent = self.settings.get("recent_files", [])
        keep   = [p for p in recent if not is_private_path(p, private_dirs)]
        removed += len(recent) - len(keep)
        self.settings["recent_files"] = keep

        # 2. "Last" button
        last = self.settings.get("last_file", "")
        if last and is_private_path(last, private_dirs):
            self.settings["last_file"] = ""
            self.settings["last_dir"]  = ""
            removed += 1

        # 3. Play statistics (also feeds the DB "Latest 25%" column and the
        #    "· N min" suffix in the Open list)
        films = self._stats_data.get("films", {})
        gone  = [p for p in films if is_private_path(p, private_dirs)]
        for p in gone:
            films.pop(p, None)
        if gone:
            removed += len(gone)
            save_stats_data(self._stats_data)

        # 4. Resume positions - move across instead of deleting
        moved = [p for p in self.resume_data if is_private_path(p, private_dirs)]
        for p in moved:
            self.resume_private[private_key(p)] = self.resume_data.pop(p)
        if moved:
            removed += len(moved)
            save_resume(self.resume_data)
            save_private_resume(self.resume_private)

        if removed:
            save_settings(self.settings)
        return removed

    # ── Recent files ──────────────────────────────────────────────

    def _add_to_recent(self, path: str) -> None:
        """Add path to front of recent_files list (max 5, no duplicates).
        Films in a private folder are never added."""
        if self._is_private(path):
            return
        recent = self.settings.get("recent_files", [])
        recent = [p for p in recent if p != path]
        recent.insert(0, path)
        self.settings["recent_files"] = recent[:5]

    def _recent_files(self) -> list:
        """The Latest list, with anything private filtered out.  Nothing
        private is ever written to it, but a settings file copied in from
        elsewhere could still hold some."""
        recent = self.settings.get("recent_files", [])
        if not self.settings.get("private_dirs"):
            return list(recent)
        return [p for p in recent if not self._is_private(p)]

    def _populate_latest_menu(self, m: tk.Menu) -> None:
        """Fill menu m with the recently opened files.  Shared by the Latest
        button (_show_latest_menu) and the right-click context menu."""
        recent = self._recent_files()
        if not recent:
            m.add_command(label="  (no recent files)", state="disabled")
            return
        for p in recent:
            lbl = os.path.basename(p)
            if len(lbl) > 60:
                lbl = lbl[:57] + "…"
            exists = os.path.isfile(p)
            m.add_command(
                label=("  " if exists else "✕ ") + lbl,
                state="normal" if exists else "disabled",
                command=lambda fp=p: self._open_path(fp))
        m.add_separator()
        m.add_command(label="  Clear list",
                      command=self._clear_recent)

    def _show_latest_menu(self) -> None:
        """Show popup menu of the 5 most recently opened files."""
        m = tk.Menu(self.root, tearoff=False,
                    bg=C_BG2, fg=C_FG,
                    activebackground=C_BG3, activeforeground=C_FG,
                    font=("Segoe UI", 9))
        self._populate_latest_menu(m)
        try:
            b = self._all_btns["latest"]
            b.update_idletasks()
            m.tk_popup(b.winfo_rootx(),
                       b.winfo_rooty() - m.winfo_reqheight())
        except Exception:
            pass
        finally:
            try:
                m.grab_release()
            except Exception:
                pass

    def _clear_recent(self) -> None:
        self.settings["recent_files"] = []

    # ── Plan list ─────────────────────────────────────────────────

    def _show_plan(self) -> None:
        """Dialog to manage a watchlist of up to 10 planned films."""
        top = tk.Toplevel(self.root)
        top.title("Watchlist  –  Planned Films")
        top.configure(bg=C_BG)
        _place_top_center(top, 540, 400)
        top.resizable(True, True)
        top.transient(self.root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda _: top.destroy())

        _B = dict(bg=C_BTN, fg="white", activebackground=C_BTN_HOV,
                  activeforeground="white", relief="flat",
                  padx=8, pady=4, font=("Segoe UI", 9), cursor="hand2")

        plan = list(self.settings.get("plan_list", []))  # local copy

        def _refresh(lb, plan):
            lb.delete(0, "end")
            for i, item in enumerate(plan):
                exists = os.path.isfile(item.get("path", ""))
                prefix = "✓ " if exists else "○ "
                lb.insert("end", f"{prefix}{item.get('title','')}")
                lb.itemconfig(i, fg=(C_FG if exists else C_FG_DIM))

        def _save():
            self.settings["plan_list"] = plan

        # Header
        tk.Label(top, text="Watchlist  (max 10 titles)",
                 bg=C_BG, fg=C_ACCENT,
                 font=("Segoe UI", 11, "bold")).pack(pady=(12, 4))

        # List
        lf = tk.Frame(top, bg=C_BG)
        lf.pack(fill="both", expand=True, padx=12, pady=(0, 6))
        sb = tk.Scrollbar(lf, orient="vertical")
        sb.pack(side="right", fill="y")
        lb = tk.Listbox(lf, bg=C_BG2, fg=C_FG,
                        selectbackground=C_BG3, selectforeground=C_FG,
                        activestyle="none", font=("Segoe UI", 10),
                        relief="flat", bd=0, height=10,
                        yscrollcommand=sb.set)
        lb.pack(side="left", fill="both", expand=True)
        sb.config(command=lb.yview)
        _refresh(lb, plan)

        # Buttons row
        bf = tk.Frame(top, bg=C_BG)
        bf.pack(fill="x", padx=12, pady=(0, 8))

        def add_file():
            if len(plan) >= 10:
                auto_close_popup(self.root, "List is full (max 10)")
                return
            init_dir = self.settings.get("last_dir", "")
            if not os.path.isdir(init_dir):
                init_dir = ""
            path = filedialog.askopenfilename(
                parent=top, initialdir=init_dir,
                title="Add Film",
                filetypes=[("Video files",
                             "*.mkv *.mp4 *.avi *.mov *.wmv *.flv *.webm "
                             "*.ts *.m2ts *.m4v *.3gp *.ogv"),
                            ("All files", "*.*")])
            if path:
                title = os.path.splitext(os.path.basename(path))[0]
                plan.append({"title": title, "path": path})
                _save()
                _refresh(lb, plan)

        def add_current():
            if not self._current_file:
                auto_close_popup(self.root, "No file open")
                return
            if len(plan) >= 10:
                auto_close_popup(self.root, "List is full (max 10)")
                return
            path  = self._current_file
            title = os.path.splitext(os.path.basename(path))[0]
            if any(x.get("path") == path for x in plan):
                auto_close_popup(self.root, "Already in list")
                return
            plan.append({"title": title, "path": path})
            _save()
            _refresh(lb, plan)

        def play_selected():
            sel = lb.curselection()
            if not sel:
                return
            item = plan[sel[0]]
            p = item.get("path", "")
            if os.path.isfile(p):
                top.destroy()
                self._open_path(p)
            else:
                auto_close_popup(self.root, "File not found")

        def remove_selected():
            sel = lb.curselection()
            if not sel:
                return
            del plan[sel[0]]
            _save()
            _refresh(lb, plan)

        def move_up():
            sel = lb.curselection()
            if sel and sel[0] > 0:
                i = sel[0]
                plan[i-1], plan[i] = plan[i], plan[i-1]
                _save()
                _refresh(lb, plan)
                lb.select_set(i - 1)

        def move_down():
            sel = lb.curselection()
            if sel and sel[0] < len(plan) - 1:
                i = sel[0]
                plan[i+1], plan[i] = plan[i], plan[i+1]
                _save()
                _refresh(lb, plan)
                lb.select_set(i + 1)

        btn_data = [
            ("+ Fil",           add_file),
            ("+ Current",       add_current),
            ("▶ Play",           play_selected),
            ("✕ Remove",        remove_selected),
            ("▲ Up",             move_up),
            ("▼ Down",           move_down),
        ]
        for txt, cmd in btn_data:
            b = tk.Button(bf, text=txt, command=cmd, **_B)
            b.pack(side="left", padx=(0, 4))
            _bind_hover(b)

        lb.bind("<Double-Button-1>", lambda _: play_selected())
        lb.bind("<Return>", lambda _: play_selected())

        tk.Label(top, text="✓ = file found  ·  ○ = file missing  ·  Double-click to play",
                 bg=C_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 7, "italic")).pack(pady=(0, 10))


# *************** DEL 14 - WINDOW MODES ***************
#
#   Key 1          -> windowed       normal window,  aspect ratio restored
#   Enter          -> maximized      fills screen minus taskbar, aspect ratio
#   Ctrl+Enter     -> stretch-max    fills screen minus taskbar, NO black bars
#   F / F11        -> fullscreen     true fullscreen (covers taskbar)
#   Esc            -> exit FS  OR    close player if already windowed
#   (auto, on play)-> fullscreen using Settings > Playback > Default fill
#                     mode (stretch / fill-crop / letterbox); square videos
#                     always use fill-crop.  See _enter_fullscreen_default.

    def _on_escape(self) -> None:
        if self._is_fullscreen:
            self._exit_fullscreen()
        else:
            self._on_close()

    def _toggle_fullscreen(self) -> None:
        if self._is_fullscreen:
            self._exit_fullscreen()
        else:
            self._enter_fullscreen()

    def _enter_fullscreen(self) -> None:
        self._is_fullscreen   = True
        self._pre_fs_state    = self.root.state()
        self._pre_fs_geometry = self.root.geometry()
        self.root.config(menu="")
        # attributes('-fullscreen') uses the Windows WM API correctly:
        # covers taskbar, works with DPI scaling, no overrideredirect needed.
        self.root.attributes("-fullscreen", True)
        self.root.lift()
        self._hide_controls()

    def _exit_fullscreen(self) -> None:
        self._is_fullscreen      = False
        self._fullscreen_stretch = False
        self.root.attributes("-fullscreen", False)
        self.root.config(menu=self._menubar)
        try:
            if self._pre_fs_state == "zoomed":
                self.root.state("zoomed")
            else:
                self.root.geometry(self._pre_fs_geometry)
                self.root.state("normal")
        except Exception:
            self.root.state("normal")
        if self._player:
            try:
                self._player.keepaspect = True
                self._player.panscan    = 0.0
            except Exception:
                pass
        if self._hide_id:
            self.root.after_cancel(self._hide_id)
            self._hide_id = None
        self._show_controls()

    def _toggle_fullscreen_stretch(self) -> None:
        """Ctrl+F11 - toggle fullscreen-stretch (no black bars, covers taskbar)."""
        if self._is_fullscreen and self._fullscreen_stretch:
            self._exit_fullscreen()
        else:
            self._enter_fullscreen_stretch()

    def _enter_fullscreen_stretch(self) -> None:
        """True fullscreen + keepaspect=False so video fills every pixel."""
        self._is_fullscreen      = True
        self._fullscreen_stretch = True
        self._pre_fs_state       = self.root.state()
        self._pre_fs_geometry    = self.root.geometry()
        self.root.config(menu="")
        self.root.attributes("-fullscreen", True)
        if self._player:
            try:
                self._player.keepaspect = False
            except Exception:
                pass
        self.root.lift()
        self._hide_controls()

    # ---- Default fill mode (used automatically when a film starts) ----

    def _is_square_video(self) -> bool:
        """True if the loaded video's picture is roughly square (1:1)."""
        if not self._player:
            return False
        try:
            w = self._player.dwidth or self._player.width
            h = self._player.dheight or self._player.height
            if not w or not h:
                return False
            ratio = w / float(h)
            return 0.85 <= ratio <= 1.15
        except Exception:
            return False

    def _enter_fullscreen_default(self) -> None:
        """Enter fullscreen using the configured default fill mode
        (Settings > Playback > "Default fill mode").  Called automatically
        when a film starts playing — including when the window is already
        in fullscreen (e.g. start_fullscreen=True at app startup), so that
        keepaspect/panscan are always set correctly for the chosen mode.

        Square videos always use "fill" (crop, no stretch) no matter what
        is configured: letterboxing a square picture would add bars on
        the sides instead of top/bottom, while "fill" only crops the top
        and bottom and loses nothing left/right.
        """
        mode = self.settings.get("default_max_mode", "stretch")
        if self._is_square_video():
            mode = "fill"

        already_fs = self._is_fullscreen
        self._is_fullscreen      = True
        self._fullscreen_stretch = (mode == "stretch")
        # Only save pre-fullscreen state when we're actually transitioning
        # into fullscreen; if we're already there, keep the saved state intact
        # so Esc can restore the window correctly.
        if not already_fs:
            self._pre_fs_state    = self.root.state()
            self._pre_fs_geometry = self.root.geometry()
            self.root.config(menu="")
            self.root.attributes("-fullscreen", True)

        # Always apply the fill-mode settings to mpv
        if self._player:
            try:
                if mode == "stretch":
                    self._player.keepaspect = False
                    self._player.panscan    = 0.0
                elif mode == "fill":
                    self._player.keepaspect = True
                    self._player.panscan    = 1.0
                else:  # "letterbox"
                    self._player.keepaspect = True
                    self._player.panscan    = 0.0
            except Exception:
                pass
        self.root.lift()
        self._hide_controls()

    def _go_windowed(self) -> None:
        """Key 1 - small 480x320 window."""
        was_fs = self._is_fullscreen
        self._is_fullscreen = False
        if was_fs:
            self.root.attributes("-fullscreen", False)
            self.root.config(menu=self._menubar)
        self.root.state("normal")
        self.root.geometry("480x320")
        if self._player:
            try:
                self._player.keepaspect = True
                self._player.panscan    = 0.0
            except Exception:
                pass
        if self._hide_id:
            self.root.after_cancel(self._hide_id)
            self._hide_id = None
        self._show_controls()

    def _go_maximized(self) -> None:
        """Enter - maximize (respects taskbar), using the configured Default fill mode.

        Same fill modes as fullscreen: stretch / fill-crop / letterbox.
        Square videos always use "fill" regardless of the setting.
        """
        mode = self.settings.get("default_max_mode", "stretch")
        if self._is_square_video():
            mode = "fill"
        was_fs = self._is_fullscreen
        self._is_fullscreen = False
        if was_fs:
            self.root.attributes("-fullscreen", False)
            self.root.config(menu=self._menubar)
        self.root.state("zoomed")
        if self._player:
            try:
                if mode == "stretch":
                    self._player.keepaspect = False
                    self._player.panscan    = 0.0
                elif mode == "fill":
                    self._player.keepaspect = True
                    self._player.panscan    = 1.0
                else:  # "letterbox"
                    self._player.keepaspect = True
                    self._player.panscan    = 0.0
            except Exception:
                pass
        if self._hide_id:
            self.root.after_cancel(self._hide_id)
            self._hide_id = None
        self._show_controls()

    def _go_maximized_stretch(self) -> None:
        """Ctrl+Enter - maximize and stretch to fill (no black bars)."""
        was_fs = self._is_fullscreen
        self._is_fullscreen = False
        if was_fs:
            self.root.attributes("-fullscreen", False)
            self.root.config(menu=self._menubar)
        self.root.state("zoomed")
        if self._player:
            try:
                self._player.keepaspect = False
            except Exception:
                pass
        if self._hide_id:
            self.root.after_cancel(self._hide_id)
            self._hide_id = None
        self._show_controls()



# *************** DEL 14b - PLAY STATISTICS ***************

    def _stats_start_session(self, path: str) -> None:
        """Begin a new play session for the given file."""
        self._stats_end_session()          # close any previous session first
        # A film in a private folder is never counted: no session is opened,
        # so _stats_end_session has nothing to write and no FF event is kept.
        if self._is_private(path):
            return
        now = datetime.datetime.now()
        start_pos = 0.0
        if self._player:
            try:
                p = self._player.time_pos
                if p and p > 0:
                    start_pos = round(float(p), 1)
            except Exception:
                pass
        self._stats_session = {
            "date"       : now.strftime("%Y-%m-%d"),
            "started_at" : now.isoformat(timespec="seconds"),
            "ended_at"   : None,
            "start_pos_s": start_pos,
            "end_pos_s"  : start_pos,
            "duration_s" : 0.0,
            "ff_events"  : [],
            "_path"      : path,          # internal, removed before save
        }

    def _stats_end_session(self) -> None:
        """Close the current session and persist it."""
        if not self._stats_session:
            return
        sess = self._stats_session
        self._stats_session = None
        path = sess.pop("_path", None)
        if not path:
            return

        now = datetime.datetime.now()
        sess["ended_at"] = now.isoformat(timespec="seconds")

        # Grab final position from player
        end_pos = sess["start_pos_s"]
        if self._player:
            try:
                p = self._player.time_pos
                if p and p > 0:
                    end_pos = round(float(p), 1)
            except Exception:
                pass
        sess["end_pos_s"] = end_pos

        # Calculate wall-clock watch time for this session
        try:
            t0 = datetime.datetime.fromisoformat(sess["started_at"])
            sess["duration_s"] = round((now - t0).total_seconds(), 1)
        except Exception:
            sess["duration_s"] = 0.0

        # Ensure film entry exists
        films = self._stats_data.setdefault("films", {})
        entry = films.setdefault(path, {
            "title"   : os.path.basename(path),
            "sessions": [],
        })
        entry["title"] = os.path.basename(path)   # keep fresh
        entry["sessions"].append(sess)
        save_stats_data(self._stats_data)

    def _stats_record_ff(self, from_s: float, to_s: float,
                         ff_type: str) -> None:
        """Record a fast-forward event in the current session."""
        if not self._stats_session:
            return
        if to_s - from_s < 5.0:           # ignore tiny jumps
            return
        self._stats_session["ff_events"].append({
            "at"    : datetime.datetime.now().isoformat(timespec="seconds"),
            "from_s": round(from_s, 1),
            "to_s"  : round(to_s,   1),
            "skip_s": round(to_s - from_s, 1),
            "type"  : ff_type,             # "skip_btn" | "seek_drag"
        })

# *************** DEL 15 - CLOSE / CLEANUP ***************

    def _toggle_vkb(self) -> None:
        """Öppna / stäng det virtuella tangentbordet."""
        if self._vkb is None:
            self._vkb = VirtualKeyboard(self.root, default_lang="SV")
        # Skicka alltid senaste kända mål till tangentbordet vid visning
        if self._vkb_last_target is not None:
            self._vkb.set_target(self._vkb_last_target)
        self._vkb.toggle()

    def _vkb_focus_in(self, event) -> None:
        """Spara vilket Entry/Text-fält som senast fick fokus."""
        if isinstance(event.widget, (tk.Entry, tk.Text)):
            self._vkb_last_target = event.widget
            if self._vkb is not None:
                self._vkb.set_target(event.widget)

    def _on_close(self) -> None:
        """Save everything and shut down cleanly."""
        self._stats_end_session()
        # Save window geometry (only valid when in normal state)
        if not self._is_fullscreen:
            try:
                if self.root.state() == "normal":
                    self.settings["window_geometry"] = self.root.geometry()
            except Exception:
                pass
        save_settings(self.settings)

        # Persist current playback position
        self._do_save_resume()
        save_resume(self.resume_data)
        save_private_resume(self.resume_private)
        save_sub_settings(self.sub_settings)

        # Cancel all pending after() timers
        for h in (self._poll_id, self._save_id, self._hide_id,
                  self._cursor_hide_id):
            if h:
                try:
                    self.root.after_cancel(h)
                except Exception:
                    pass

        # Terminate mpv
        if self._player:
            try:
                self._player.terminate()
            except Exception:
                pass
            self._player = None

        # Clean up processed subtitle temp files
        try:
            for fn in os.listdir(SUB_REPLACE_TEMP):
                try:
                    os.remove(os.path.join(SUB_REPLACE_TEMP, fn))
                except Exception:
                    pass
        except Exception:
            pass

        self.root.destroy()


    # ──────────────────────────────────────────────────────────────
    # DEL 19 – MOVIE DATABASE SEARCH
    # ──────────────────────────────────────────────────────────────

    def _get_db_path(self) -> str:
        """Return the configured or default movies.db path."""
        p = self.settings.get("movies_db", "").strip()
        if p and os.path.isfile(p):
            return p
        default = os.path.normpath(MOVIES_DB_DEFAULT)
        if os.path.isfile(default):
            return default
        return ""

    def _show_db_search(self) -> None:
        db_path = self._get_db_path()
        if not db_path:
            messagebox.showwarning(
                "Database not found",
                "movies.db was not found.\n\n"
                "Set the path in Settings → Directories → Movie Database.",
                parent=self.root)
            return

        try:
            con = sqlite3.connect(db_path)
            con.row_factory = sqlite3.Row
        except Exception as exc:
            messagebox.showerror("DB error", str(exc), parent=self.root)
            return

        top = tk.Toplevel(self.root)
        top.title("🎬  Movie Database Search")
        top.configure(bg=C_BG)
        _place_top_center(top, 1400, 640)
        top.transient(self.root)
        # grab_set() utelämnat – virtuella tangentbordet måste kunna ta emot klick
        top.focus_force()
        top.bind("<Escape>", lambda _: (con.close(), top.destroy()))
        top.protocol("WM_DELETE_WINDOW", lambda: (con.close(), top.destroy()))

        _B = dict(bg=C_BTN, fg="white", activebackground=C_BTN_HOV,
                  activeforeground="white", relief="flat",
                  padx=8, pady=4, font=("Segoe UI", 9), cursor="hand2")

        import tkinter.ttk as ttk

        # ── Load lookup data ──────────────────────────────────────────────
        _notes = load_notes()
        _seen25 = build_seen25_lookup(self._stats_data, self.resume_data)
        try:
            _EXCLUDED_GENRES = {"adult", "news", "reality-tv", "short", "talk-show"}
            all_genres = sorted({
                g.strip()
                for row in con.execute("SELECT genres FROM movie WHERE genres IS NOT NULL AND genres!=''")
                for g in row[0].split(",")
                if g.strip() and g.strip().lower() not in _EXCLUDED_GENRES
            })
            all_actors = sorted({
                row[0] for row in con.execute(
                    "SELECT DISTINCT p.name FROM person p "
                    "JOIN credit c ON c.person_id=p.id WHERE c.role='actor'")
            })
            all_cats = [""] + ["Shit","Bad","Okay","Good","Best","Rest"]
            all_formats = [""] + [
                row[0] for row in con.execute(
                    "SELECT DISTINCT videoformat FROM movie "
                    "WHERE videoformat IS NOT NULL AND videoformat!='' ORDER BY videoformat")
            ]
        except Exception as exc:
            messagebox.showerror("DB error", str(exc), parent=top)
            con.close(); top.destroy(); return

        DECADES = ["", "60's","70's","80's","90's","00's","10's","20's"]

        # ── Filter row ───────────────────────────────────────────────────
        filt = tk.Frame(top, bg=C_BG2, padx=10, pady=8)
        filt.pack(fill="x")

        def lbl(parent, text):
            tk.Label(parent, text=text, bg=C_BG2, fg=C_FG_DIM,
                     font=("Segoe UI", 8)).pack(anchor="w")

        def col(parent):
            f = tk.Frame(parent, bg=C_BG2)
            f.pack(side="left", padx=6, anchor="n")
            return f

        # Title search
        c0 = col(filt); lbl(c0, "Title")
        title_var = tk.StringVar()
        te = tk.Entry(c0, textvariable=title_var, bg=C_BG, fg=C_FG,
                      insertbackground=C_FG, relief="flat",
                      font=("Segoe UI", 9), width=22)
        no_blink(te); te.pack()

        # Category
        c1 = col(filt); lbl(c1, "Category")
        cat_var = tk.StringVar(value="")
        cat_cb = tk.OptionMenu(c1, cat_var, *all_cats)
        cat_cb.configure(bg=C_BG, fg=C_FG, activebackground=C_BG3,
                         activeforeground=C_FG, relief="flat",
                         highlightthickness=0, font=("Segoe UI", 9))
        cat_cb["menu"].configure(bg=C_BG, fg=C_FG)
        cat_cb.pack(fill="x")

        # Decade
        c2 = col(filt); lbl(c2, "Decade")
        dec_var = tk.StringVar(value="")
        dec_cb = tk.OptionMenu(c2, dec_var, *DECADES)
        dec_cb.configure(bg=C_BG, fg=C_FG, activebackground=C_BG3,
                         activeforeground=C_FG, relief="flat",
                         highlightthickness=0, font=("Segoe UI", 9))
        dec_cb["menu"].configure(bg=C_BG, fg=C_FG)
        dec_cb.pack(fill="x")

        # Year (exact, overrides decade)
        c2b = col(filt); lbl(c2b, "Exact year")
        year_var = tk.StringVar()
        ye = tk.Entry(c2b, textvariable=year_var, bg=C_BG, fg=C_FG,
                      insertbackground=C_FG, relief="flat",
                      font=("Segoe UI", 9), width=6)
        no_blink(ye); ye.pack()

        # Genre (multi-select – AND-logik: valda genres måste ALLA finnas)
        c3 = col(filt); lbl(c3, "Genre")
        genre_lb_frame = tk.Frame(c3, bg=C_BG)
        genre_lb_frame.pack(fill="x")
        genre_lb = tk.Listbox(
            genre_lb_frame, selectmode="multiple",
            bg=C_BG, fg=C_FG,
            selectbackground=C_BG3, selectforeground=C_FG,
            relief="flat", font=("Segoe UI", 9),
            height=5, exportselection=False,
            highlightthickness=0, borderwidth=0,
            activestyle="none"
        )
        genre_lb_scroll = tk.Scrollbar(genre_lb_frame, orient="vertical",
                                        command=genre_lb.yview,
                                        bg=C_BG, troughcolor=C_BG2,
                                        relief="flat", width=8)
        genre_lb.configure(yscrollcommand=genre_lb_scroll.set)
        genre_lb_scroll.pack(side="right", fill="y")
        genre_lb.pack(side="left", fill="x", expand=True)
        for _g in all_genres:
            genre_lb.insert("end", _g)

        # Exclude genre (multi-select – filmer som INTE har dessa genres visas)
        c3b = col(filt); lbl(c3b, "Excl. genre")
        excl_genre_lb_frame = tk.Frame(c3b, bg=C_BG)
        excl_genre_lb_frame.pack(fill="x")
        excl_genre_lb = tk.Listbox(
            excl_genre_lb_frame, selectmode="multiple",
            bg=C_BG, fg="#e07070",
            selectbackground="#5a1a1a", selectforeground=C_FG,
            relief="flat", font=("Segoe UI", 9),
            height=5, exportselection=False,
            highlightthickness=0, borderwidth=0,
            activestyle="none"
        )
        excl_genre_lb_scroll = tk.Scrollbar(excl_genre_lb_frame, orient="vertical",
                                            command=excl_genre_lb.yview,
                                            bg=C_BG, troughcolor=C_BG2,
                                            relief="flat", width=8)
        excl_genre_lb.configure(yscrollcommand=excl_genre_lb_scroll.set)
        excl_genre_lb_scroll.pack(side="right", fill="y")
        excl_genre_lb.pack(side="left", fill="x", expand=True)
        for _g in all_genres:
            excl_genre_lb.insert("end", _g)

        # Actor
        c4 = col(filt); lbl(c4, "Actor")
        actor_var = tk.StringVar()
        ae = tk.Entry(c4, textvariable=actor_var, bg=C_BG, fg=C_FG,
                      insertbackground=C_FG, relief="flat",
                      font=("Segoe UI", 9), width=22)
        no_blink(ae); ae.pack()

        # Format
        c5 = col(filt); lbl(c5, "Format")
        fmt_var = tk.StringVar(value="")
        fmt_cb = tk.OptionMenu(c5, fmt_var, *all_formats)
        fmt_cb.configure(bg=C_BG, fg=C_FG, activebackground=C_BG3,
                         activeforeground=C_FG, relief="flat",
                         highlightthickness=0, font=("Segoe UI", 9))
        fmt_cb["menu"].configure(bg=C_BG, fg=C_FG)
        fmt_cb.pack(fill="x")

        # Min rating
        c6 = col(filt); lbl(c6, "Min rating")
        rating_var = tk.StringVar()
        re2 = tk.Entry(c6, textvariable=rating_var, bg=C_BG, fg=C_FG,
                       insertbackground=C_FG, relief="flat",
                       font=("Segoe UI", 9), width=5)
        no_blink(re2); re2.pack()

        # Watch status filter
        WATCH_VALUES = ["", "See Soon", "Later", "Yes", "No"]
        c6b = col(filt); lbl(c6b, "Watch")
        watch_filt_var = tk.StringVar(value="")
        watch_filt_cb = tk.OptionMenu(c6b, watch_filt_var, *WATCH_VALUES)
        watch_filt_cb.configure(bg=C_BG, fg=C_FG, activebackground=C_BG3,
                                activeforeground=C_FG, relief="flat",
                                highlightthickness=0, font=("Segoe UI", 9))
        watch_filt_cb["menu"].configure(bg=C_BG, fg=C_FG)
        watch_filt_cb.pack(fill="x")

        # Buttons
        c7 = col(filt)
        tk.Label(c7, text=" ", bg=C_BG2).pack()
        btn_search = tk.Button(c7, text="Search", command=lambda: _do_search(), **_B)
        btn_search.pack(fill="x", pady=(0, 3))
        _bind_hover(btn_search)
        btn_reset = tk.Button(c7, text="Clear", **_B,
                              command=lambda: (
                                  title_var.set(""), cat_var.set(""),
                                  dec_var.set(""), year_var.set(""),
                                  genre_lb.selection_clear(0, "end"),
                                  excl_genre_lb.selection_clear(0, "end"),
                                  actor_var.set(""),
                                  fmt_var.set(""), rating_var.set(""),
                                  watch_filt_var.set(""),
                                  _do_search()))
        btn_reset.pack(fill="x")
        _bind_hover(btn_reset)

        # ── Result count label ───────────────────────────────────────────
        status_var = tk.StringVar(value="")
        tk.Label(top, textvariable=status_var, bg=C_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 8, "italic"),
                 anchor="w").pack(fill="x", padx=12, pady=(4, 0))

        # ── Treeview ─────────────────────────────────────────────────────
        tv_frame = tk.Frame(top, bg=C_BG)
        tv_frame.pack(fill="both", expand=True, padx=8, pady=4)

        cols = ("category","title","year","rating","genres","actors","videoformat","imdb_id","last_seen","watch","comment","mins")
        hdrs = ("Cat",     "Title","Year","Rating","Genres","Actor",       "Format","IMDb",  "Latest 25%","Watch","Commentary","Mins")
        widths = (50, 240, 45, 55, 160, 240, 70, 80, 90, 80, 200, 45)

        # Build normalized-title -> total watch minutes from stats
        _stats_mins_db: dict = {}
        for _sp, _se in self._stats_data.get("films", {}).items():
            _ts = sum(s.get("duration_s", 0) for s in _se.get("sessions", []))
            if _ts > 0:
                _key = _normalize_title(os.path.basename(_sp))
                _stats_mins_db[_key] = _stats_mins_db.get(_key, 0) + int(_ts // 60)

        style = ttk.Style(top)
        style.theme_use("default")
        style.configure("DB.Treeview",
                        background=C_BG2, foreground=C_FG,
                        fieldbackground=C_BG2,
                        rowheight=22, font=("Segoe UI", 9))
        style.configure("DB.Treeview.Heading",
                        background=C_BG3, foreground=C_FG,
                        font=("Segoe UI", 9, "bold"))
        style.map("DB.Treeview", background=[("selected", C_BG3)])

        vsb = tk.Scrollbar(tv_frame, orient="vertical")
        hsb = tk.Scrollbar(tv_frame, orient="horizontal")
        vsb.pack(side="right", fill="y")
        hsb.pack(side="bottom", fill="x")

        tv = ttk.Treeview(tv_frame, columns=cols, show="headings",
                          style="DB.Treeview",
                          yscrollcommand=vsb.set, xscrollcommand=hsb.set)
        for c, h, w in zip(cols, hdrs, widths):
            tv.heading(c, text=h)
            tv.column(c, width=w, minwidth=30, stretch=(c == "title"))
        vsb.config(command=tv.yview)
        hsb.config(command=tv.xview)
        tv.pack(fill="both", expand=True)

        # Row tags for watch status colouring
        WATCH_CYCLE = ["", "See Soon", "Later", "Yes", "No"]
        WATCH_COLORS = {
            "See Soon": "#e8a020",   # orange
            "Later":    "#6080c0",   # blue-grey
            "Yes":      "#40b060",   # green
            "No":       "#b04040",   # red
        }
        tv.tag_configure("watch_seesoon", foreground="#e8a020")
        tv.tag_configure("watch_later",   foreground="#6080c0")
        tv.tag_configure("watch_yes",     foreground="#40b060")
        tv.tag_configure("watch_no",      foreground="#b04040")

        def _watch_tag(status):
            return {
                "See Soon": "watch_seesoon",
                "Later":    "watch_later",
                "Yes":      "watch_yes",
                "No":       "watch_no",
            }.get(status, "")

        def _apply_row_tags():
            """Re-colour all rows based on current watch value."""
            for item in tv.get_children():
                vals = tv.item(item, "values")
                # watch is now index 10 (mins column added)
                w = vals[9] if len(vals) > 9 else ""
                tag = _watch_tag(w)
                tv.item(item, tags=(tag,) if tag else ())

        def _on_tv_click(event):
            """Cycle watch status when user clicks the Watch column."""
            region = tv.identify_region(event.x, event.y)
            if region != "cell":
                return
            col_id = tv.identify_column(event.x)
            # Watch column is #10 (1-based; cols index 9)
            if col_id != "#10":
                return
            item = tv.identify_row(event.y)
            if not item:
                return
            idx = tv.index(item)
            if idx >= len(_results):
                return
            row = _results[idx]
            imdb = row["imdb_id"] or ""
            if not imdb:
                return
            current = _notes.get(imdb, {}).get("watch", "")
            # Cycle to next value
            try:
                next_idx = (WATCH_CYCLE.index(current) + 1) % len(WATCH_CYCLE)
            except ValueError:
                next_idx = 1
            new_status = WATCH_CYCLE[next_idx]
            # Update in-memory notes
            if imdb not in _notes:
                _notes[imdb] = {}
            _notes[imdb]["watch"] = new_status
            save_notes(_notes)
            # Update treeview cell
            vals = list(tv.item(item, "values"))
            vals[9] = new_status
            tv.item(item, values=vals)
            tag = _watch_tag(new_status)
            tv.item(item, tags=(tag,) if tag else ())
            # Show confirmation popup
            title_disp = vals[1] if len(vals) > 1 else imdb
            label = new_status if new_status else "(cleared)"
            color = WATCH_COLORS.get(new_status, "#555555")
            auto_close_popup(self.root,
                             f"Watch: {label}  ·  {title_disp[:40]}",
                             delay_ms=900, bg=color)

        tv.bind("<ButtonRelease-1>", _on_tv_click)

        # ── Bottom bar ───────────────────────────────────────────────────
        bot = tk.Frame(top, bg=C_BG2)
        bot.pack(fill="x")
        hint = tk.Label(bot,
                        text="Double-click or select+Enter to open file  ·  Click Watch column to cycle status",
                        bg=C_BG2, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"))
        hint.pack(side="left", padx=10, pady=6)
        btn_open = tk.Button(bot, text="Open file…",
                             command=lambda: _open_selected(), **_B)
        btn_open.pack(side="right", padx=10, pady=6)
        _bind_hover(btn_open)
        btn_imdb = tk.Button(bot, text="IMDb",
                             command=lambda: _open_imdb(), **_B)
        btn_imdb.pack(side="right", padx=4, pady=6)
        _bind_hover(btn_imdb)
        tk.Button(bot, text="Close",
                  command=lambda: (con.close(), top.destroy()), **_B).pack(
                      side="right", padx=4, pady=6)

        # ── Search logic ─────────────────────────────────────────────────
        _results: list = []   # list of sqlite3.Row

        def _do_search(_evt=None):
            nonlocal _results
            tv.delete(*tv.get_children())
            _results.clear()

            # Build SQL
            wheres, params = [], []

            # Title
            t = title_var.get().strip()
            if t:
                wheres.append("(m.title LIKE ? OR m.extratitle LIKE ?)")
                params += [f"%{t}%", f"%{t}%"]

            # Category  – minimum logic: vald kategori + alla högre
            # Shit < Bad < Okay < Good < Best   (Rest = exakt matchning)
            cat = cat_var.get().strip()
            if cat:
                CAT_ORDER = ["Shit", "Bad", "Okay", "Good", "Best"]
                if cat in CAT_ORDER:
                    cats_in = CAT_ORDER[CAT_ORDER.index(cat):]
                    placeholders = ",".join("?" * len(cats_in))
                    wheres.append(f"m.category IN ({placeholders})")
                    params.extend(cats_in)
                else:
                    # "Rest" eller okänd kategori – exakt matchning
                    wheres.append("m.category=?")
                    params.append(cat)

            # Year / decade
            yr = year_var.get().strip()
            dec = dec_var.get().strip()
            if yr and yr.isdigit():
                wheres.append("m.year=?")
                params.append(int(yr))
            elif dec:
                decade_start = {"60's":1960,"70's":1970,"80's":1980,
                                "90's":1990,"00's":2000,"10's":2010,"20's":2020}.get(dec)
                if decade_start:
                    wheres.append("m.year BETWEEN ? AND ?")
                    params += [decade_start, decade_start + 9]

            # Genre (AND-logik: alla valda genres måste finnas i filmen)
            sel_genres = [all_genres[i] for i in genre_lb.curselection()]
            for g in sel_genres:
                wheres.append("m.genres LIKE ?")
                params.append(f"%{g}%")

            # Exclude genre (NOT-logik: ingen av de valda genres får finnas i filmen)
            excl_genres = [all_genres[i] for i in excl_genre_lb.curselection()]
            for g in excl_genres:
                wheres.append("(m.genres NOT LIKE ? OR m.genres IS NULL)")
                params.append(f"%{g}%")

            # Format
            fmt = fmt_var.get().strip()
            if fmt:
                wheres.append("m.videoformat=?")
                params.append(fmt)

            # Rating
            rat = rating_var.get().strip()
            if rat:
                try:
                    wheres.append("CAST(m.rating AS REAL) >= ?")
                    params.append(float(rat))
                except ValueError:
                    pass

            # Actor (joins credit/person, post-filter)
            actor_q = actor_var.get().strip().lower()

            where_sql = ("WHERE " + " AND ".join(wheres)) if wheres else ""

            sql = f"""
                SELECT m.id, m.category, m.title, m.extratitle,
                       m.year, m.rating, m.genres, m.videoformat, m.imdb_id,
                       m.runtime,
                       GROUP_CONCAT(DISTINCT p.name) AS actors
                FROM movie m
                LEFT JOIN credit c ON c.movie_id=m.id AND c.role='actor'
                LEFT JOIN person p ON p.id=c.person_id
                {where_sql}
                GROUP BY m.id
                ORDER BY m.category, m.title
            """
            try:
                rows = con.execute(sql, params).fetchall()
            except Exception as exc:
                status_var.set(f"SQL error: {exc}")
                return

            # Post-filter on actor name (substring)
            if actor_q:
                rows = [r for r in rows
                        if r["actors"] and actor_q in r["actors"].lower()]

            # Post-filter on watch status
            watch_filt = watch_filt_var.get().strip()
            if watch_filt:
                rows = [r for r in rows
                        if (_notes.get(r["imdb_id"] or "", {}).get("watch", "") == watch_filt)]

            _results[:] = rows
            for r in rows:
                title_disp = r["title"]
                if r["extratitle"]:
                    title_disp += f"  [{r['extratitle']}]"
                actors_short = (r["actors"] or "")
                if len(actors_short) > 60:
                    actors_short = actors_short[:57] + "…"
                # Last seen ≥25%: fuzzy match by normalized title
                norm_title = _normalize_title(r["title"] or "")
                last_seen = _seen25.get(norm_title, "")
                # Runtime from DB
                mins_disp = str(r["runtime"]) if r["runtime"] else ""
                # Watch status and comment: keyed by imdb_id
                imdb = r["imdb_id"] or ""
                note_entry = _notes.get(imdb, {}) if imdb else {}
                watch_status = note_entry.get("watch", "")
                comment = note_entry.get("comment", "")
                tv.insert("", "end", values=(
                    r["category"] or "",
                    title_disp,
                    r["year"] or "",
                    r["rating"] or "",
                    r["genres"] or "",
                    actors_short,
                    r["videoformat"] or "",
                    imdb,
                    last_seen,
                    watch_status,
                    comment,
                    mins_disp,
                ))
            status_var.set(f"{len(rows)} result{'s' if len(rows)!=1 else ''}")
            _apply_row_tags()

        def _selected_row():
            sel = tv.selection()
            if not sel:
                return None
            idx = tv.index(sel[0])
            return _results[idx] if idx < len(_results) else None

        def _open_selected(_evt=None):
            row = _selected_row()
            if not row:
                return
            title = row["title"] or ""
            extra = row["extratitle"] or ""
            try:
                db_year = int(row["year"]) if row["year"] else None
            except (TypeError, ValueError):
                db_year = None
            category = (row["category"] or "").strip()
            hint_name = f"{title} {db_year or ''}".strip()
            titles = ft_title_variants(title, extra)

            # ── Look for the file (DEL 04g): the category folders first,
            #    every other folder only if the film is not there ──────────
            top.configure(cursor="watch")
            top.update_idletasks()
            try:
                found = self._film_lookup(titles, category)
            finally:
                top.configure(cursor="")

            def _year_ok(fe):
                return (fe.year is None or db_year is None
                        or abs(fe.year - db_year) <= 1)

            def _play(path):
                con.close(); top.destroy()
                self._open_path(path)

            if found:
                top_score = found[0][0]
                best = [fe for sc, fe in found if sc == top_score]
                if top_score >= 3:
                    # A clear match.  Narrow by year; start at once only when
                    # exactly one file is left and its year does not clash.
                    if len(best) > 1 and db_year:
                        same = [fe for fe in best if fe.year == db_year]
                        if len(same) == 1:
                            best = same
                    if len(best) == 1 and _year_ok(best[0]):
                        _play(best[0].path)
                        return
                note = ""
                if top_score >= 3 and len(best) == 1:
                    note = (f"The file says {best[0].year}, the database says "
                            f"{db_year} - is it the right film?")
                label = {4: "", 3: "[folder]  ", 2: "[similar]  ", 1: "[maybe]  "}
                items = [(label[sc] + fe.path
                          + (f"   ({fe.year})" if fe.year else ""), fe.path)
                         for sc, fe in found[:60]]
                if len(found) > 60:
                    note = (note + "  " if note else "") + f"Showing the best 60 of {len(found)}."
                choice = self._pick_film_file(top, hint_name, items, note)
                if choice and choice != "browse":
                    _play(choice)
                    return
                if choice != "browse":
                    return
            else:
                scanned = self._film_groups_for(category)
                n_roots = len({r for g in scanned for r in g})
                if not n_roots:
                    messagebox.showinfo(
                        "No folders",
                        "No movie folders are set up.\n\nAdd them under:\n"
                        "  ⚙ Settings → Directories → Movies directories /\n"
                        "  Category folders", parent=top)
                    return
                if not messagebox.askyesno(
                        "Not found",
                        f"No file found for  \"{hint_name}\"\n"
                        f"in {n_roots} folder{'s' if n_roots != 1 else ''} "
                        f"(category {category or '-'}).\n\n"
                        "Browse for it yourself?", parent=top):
                    return

            # Browse by hand
            best_dir = next((d for d in self.settings.get("movies_dirs", [])
                             if os.path.isdir(d)), "")
            init_dir = best_dir or self.settings.get("last_dir", "")
            if not os.path.isdir(init_dir):
                init_dir = ""
            path = filedialog.askopenfilename(
                parent=top,
                initialdir=init_dir,
                title=f"Open:  {hint_name}",
                filetypes=[
                    ("Video files",
                     "*.mkv *.mp4 *.avi *.mov *.wmv *.flv *.webm "
                     "*.ts *.m2ts *.m4v *.3gp *.ogv"),
                    ("All files", "*.*"),
                ])
            if path:
                _play(path)

        def _open_imdb(_evt=None):
            import webbrowser
            row = _selected_row()
            if not row:
                messagebox.showinfo("IMDb", "Markera en rad först.", parent=top)
                return
            if not row["imdb_id"]:
                messagebox.showinfo("IMDb",
                    f"Ingen IMDb-länk finns sparad för:\n{row['title']}",
                    parent=top)
                return
            open_url(f"https://www.imdb.com/title/{row['imdb_id']}/")

        tv.bind("<Double-1>",   _open_selected)
        tv.bind("<Return>",     _open_selected)
        te.bind("<Return>",     lambda _: _do_search())
        ye.bind("<Return>",     lambda _: _do_search())
        ae.bind("<Return>",     lambda _: _do_search())

        # Initial load – show all (can be slow on huge DB, so only on Search click)
        status_var.set("Set filters and click Search")


# *************** DEL 15b - STATS VIEWER ***************

    def _show_stats_dialog(self) -> None:
        """Show play-statistics popup."""
        films = self._stats_data.get("films", {})
        # Nothing private is ever written here, but a stats file carried over
        # from another machine could still hold some: never show it.
        if self.settings.get("private_dirs"):
            films = {p: e for p, e in films.items() if not self._is_private(p)}

        top = tk.Toplevel(self.root)
        top.title("📊  Play Statistics")
        top.configure(bg=C_BG)
        _place_top_center(top, 860, 580)
        top.transient(self.root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda _: top.destroy())

        _B = dict(bg=C_BTN, fg="white",
                  activebackground=C_BTN_HOV, activeforeground="white",
                  relief="flat", padx=10, pady=4,
                  font=("Segoe UI", 9), cursor="hand2")

        # ── Helper ──────────────────────────────────────────────
        def hms(s):
            if s is None:
                return "–"
            s = int(s)
            h, r = divmod(s, 3600)
            m, sc = divmod(r, 60)
            return f"{h}:{m:02d}:{sc:02d}" if h else f"{m}:{sc:02d}"

        def pct(pos_s, path):
            """Return position as percentage of known duration if possible."""
            entry = films.get(path, {})
            sessions = entry.get("sessions", [])
            # Use longest known duration from sessions
            dur = 0.0
            for s in sessions:
                ep = s.get("end_pos_s", 0)
                if ep > dur:
                    dur = ep
            if dur > 60:
                return f"  ({int(pos_s / dur * 100)} %)"
            return ""

        # ── Split layout: film list (left) | detail (right) ─────
        pane = tk.Frame(top, bg=C_BG)
        pane.pack(fill="both", expand=True, padx=10, pady=(10, 4))

        # Left: film list
        left = tk.Frame(pane, bg=C_BG, width=270)
        left.pack(side="left", fill="y", padx=(0, 8))
        left.pack_propagate(False)

        tk.Label(left, text="Films", bg=C_BG, fg=C_ACCENT,
                 font=("Segoe UI", 9, "bold")).pack(anchor="w", pady=(0, 4))

        lf = tk.Frame(left, bg=C_BG)
        lf.pack(fill="both", expand=True)
        film_sb = tk.Scrollbar(lf, orient="vertical")
        film_sb.pack(side="right", fill="y")
        film_lb = tk.Listbox(lf, bg=C_BG2, fg=C_FG,
                             selectbackground=C_BG3, selectforeground=C_FG,
                             activestyle="none",
                             selectmode="extended",
                             font=("Segoe UI", 9),
                             relief="flat", bd=0,
                             yscrollcommand=film_sb.set)
        film_lb.pack(side="left", fill="both", expand=True)
        film_sb.config(command=film_lb.yview)
        film_lb.bind("<MouseWheel>",
                     lambda e: film_lb.yview_scroll(-1*(e.delta//120), "units"))

        # Right: detail panel
        right = tk.Frame(pane, bg=C_BG)
        right.pack(side="left", fill="both", expand=True)

        tk.Label(right, text="Session details", bg=C_BG, fg=C_ACCENT,
                 font=("Segoe UI", 9, "bold")).pack(anchor="w", pady=(0, 4))

        det_outer = tk.Frame(right, bg=C_BG)
        det_outer.pack(fill="both", expand=True)
        det_sb = tk.Scrollbar(det_outer, orient="vertical")
        det_sb.pack(side="right", fill="y")
        det_txt = tk.Text(det_outer, bg=C_BG2, fg=C_FG,
                          font=("Consolas", 9),
                          relief="flat", bd=0,
                          wrap="none",
                          padx=10, pady=8,
                          yscrollcommand=det_sb.set,
                          state="disabled",
                          insertofftime=0, insertontime=9999999)
        no_blink(det_txt)
        det_txt.pack(side="left", fill="both", expand=True)
        det_sb.config(command=det_txt.yview)
        det_txt.bind("<MouseWheel>",
                     lambda e: det_txt.yview_scroll(-1*(e.delta//120), "units"))

        # Text tags for colouring
        det_txt.tag_configure("hdr",   foreground=C_ACCENT,
                              font=("Segoe UI", 10, "bold"))
        det_txt.tag_configure("sub",   foreground="#aaaacc",
                              font=("Segoe UI", 9, "bold"))
        det_txt.tag_configure("dim",   foreground=C_FG_DIM,
                              font=("Consolas", 8))
        det_txt.tag_configure("ff",    foreground="#f4a261",
                              font=("Consolas", 8))
        det_txt.tag_configure("plain", foreground=C_FG,
                              font=("Consolas", 9))

        # ── Summary row at top of film list ─────────────────────
        total_films   = len(films)
        total_sess    = sum(len(v.get("sessions", [])) for v in films.values())
        total_sec     = sum(s.get("duration_s", 0)
                           for v in films.values()
                           for s in v.get("sessions", []))
        summary_lbl = tk.Label(left,
            text=f"{total_films} films  ·  {total_sess} sessions  ·  "
                 f"{hms(total_sec)} total",
            bg=C_BG, fg=C_FG_DIM,
            font=("Segoe UI", 7, "italic"),
            wraplength=240, justify="left")
        summary_lbl.pack(anchor="w", pady=(0, 6))

        # ── Build film list ──────────────────────────────────────
        # Sort by most recently played (last session date desc)
        def last_played(item):
            sessions = item[1].get("sessions", [])
            if not sessions:
                return ""
            return sessions[-1].get("started_at", "")

        sorted_films = sorted(films.items(), key=last_played, reverse=True)
        film_paths   = []   # parallel to listbox entries

        for path, entry in sorted_films:
            sessions = entry.get("sessions", [])
            n_sess   = len(sessions)
            n_ff     = sum(len(s.get("ff_events", [])) for s in sessions)
            watch_s  = sum(s.get("duration_s", 0) for s in sessions)
            last_dt  = sessions[-1].get("date", "") if sessions else ""
            title    = entry.get("title", os.path.basename(path))
            # Truncate title for list
            short = title if len(title) <= 32 else title[:29] + "…"
            film_lb.insert("end",
                f"  {short}\n"
                f"  {last_dt}  ·  {n_sess}×  ·  {hms(watch_s)}"
                f"  ·  {n_ff} FF")
            film_paths.append(path)

        # ── Detail renderer ──────────────────────────────────────
        def show_detail(path):
            entry    = films.get(path, {})
            sessions = entry.get("sessions", [])
            title    = entry.get("title", os.path.basename(path))

            det_txt.configure(state="normal")
            det_txt.delete("1.0", "end")

            det_txt.insert("end", f"{title}\n", "hdr")
            det_txt.insert("end", f"{path}\n\n", "dim")

            n_ff    = sum(len(s.get("ff_events", [])) for s in sessions)
            watch_s = sum(s.get("duration_s", 0)      for s in sessions)
            det_txt.insert("end",
                f"Total:  {len(sessions)} sessions  ·  "
                f"{hms(watch_s)} watch time  ·  {n_ff} FF-jumps\n\n",
                "sub")

            for i, sess in enumerate(reversed(sessions), 1):
                date     = sess.get("date", "")
                started  = sess.get("started_at", "")[-8:]   # HH:MM:SS
                ended    = sess.get("ended_at",   "")[-8:]
                dur_s    = sess.get("duration_s", 0)
                start_p  = sess.get("start_pos_s", 0)
                end_p    = sess.get("end_pos_s",   0)
                ff_list  = sess.get("ff_events",   [])

                det_txt.insert("end",
                    f"  Session {len(sessions)-i+1}  –  {date}  "
                    f"{started} → {ended}  ({hms(dur_s)})\n",
                    "sub")
                det_txt.insert("end",
                    f"    Start position: {hms(start_p)}{pct(start_p, path)}"
                    f"   End position: {hms(end_p)}{pct(end_p, path)}\n",
                    "plain")

                if ff_list:
                    det_txt.insert("end",
                        f"    FF-jumps ({len(ff_list)}):\n", "plain")
                    for ff in ff_list:
                        at   = ff.get("at", "")[-8:]
                        frm  = hms(ff.get("from_s", 0))
                        to   = hms(ff.get("to_s",   0))
                        skip = hms(ff.get("skip_s", 0))
                        typ  = "Seek-drag" if ff.get("type") == "seek_drag" \
                               else "Skip button"
                        det_txt.insert("end",
                            f"      {at}  {frm} → {to}  "
                            f"(+{skip})  [{typ}]\n",
                            "ff")
                else:
                    det_txt.insert("end", "    (no FF-jumps)\n", "dim")

                det_txt.insert("end", "\n", "plain")

            det_txt.configure(state="disabled")
            det_txt.see("1.0")

        def on_film_select(_evt=None):
            sel = film_lb.curselection()
            if sel:
                show_detail(film_paths[sel[0]])

        film_lb.bind("<<ListboxSelect>>", on_film_select)

        # Auto-select currently playing film if present
        if self._current_file and self._current_file in films:
            try:
                idx = film_paths.index(self._current_file)
                film_lb.select_set(idx)
                film_lb.see(idx)
                show_detail(self._current_file)
            except ValueError:
                if film_paths:
                    film_lb.select_set(0)
                    show_detail(film_paths[0])
        elif film_paths:
            film_lb.select_set(0)
            show_detail(film_paths[0])

        if not film_paths:
            det_txt.configure(state="normal")
            det_txt.insert("end", "No statistics collected yet.\n"
                           "Play a film to start collecting data.", "dim")
            det_txt.configure(state="disabled")

        # ── Bottom bar ───────────────────────────────────────────
        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x")
        bot = tk.Frame(top, bg=C_BG2)
        bot.pack(fill="x")
        tk.Button(bot, text="Close", command=top.destroy, **_B).pack(
            side="right", padx=10, pady=6)

        def _delete_selected():
            sel = film_lb.curselection()
            if not sel:
                messagebox.showinfo("Radera", "Markera minst en titel i listan.",
                                    parent=top)
                return
            paths_to_del = [film_paths[i] for i in sel]
            names = "\n".join(
                films.get(p, {}).get("title", os.path.basename(p))
                for p in paths_to_del
            )
            if not messagebox.askyesno(
                "Bekräfta radering",
                f"Radera statistik för {len(paths_to_del)} titel(er)?\n\n{names}",
                icon="warning", parent=top
            ):
                return
            # Remove from live data and JSON
            for p in paths_to_del:
                self._stats_data.get("films", {}).pop(p, None)
            save_stats_data(self._stats_data)
            # Rebuild the film list in-place
            film_lb.delete(0, "end")
            film_paths.clear()
            det_txt.configure(state="normal")
            det_txt.delete("1.0", "end")
            det_txt.configure(state="disabled")
            remaining = {k: v for k, v in films.items()
                         if k not in paths_to_del}
            films.clear()
            films.update(remaining)
            sorted_remaining = sorted(films.items(), key=last_played, reverse=True)
            for path, entry in sorted_remaining:
                sessions = entry.get("sessions", [])
                n_sess   = len(sessions)
                n_ff     = sum(len(s.get("ff_events", [])) for s in sessions)
                watch_s  = sum(s.get("duration_s", 0) for s in sessions)
                last_dt  = sessions[-1].get("date", "") if sessions else ""
                title    = entry.get("title", os.path.basename(path))
                short    = title if len(title) <= 32 else title[:29] + "…"
                film_lb.insert("end",
                    f"  {short}\n"
                    f"  {last_dt}  ·  {n_sess}×  ·  {hms(watch_s)}"
                    f"  ·  {n_ff} FF")
                film_paths.append(path)
            # Update summary label
            tot_f = len(films)
            tot_s = sum(len(v.get("sessions", [])) for v in films.values())
            tot_t = sum(s.get("duration_s", 0)
                        for v in films.values()
                        for s in v.get("sessions", []))
            summary_lbl.configure(
                text=f"{tot_f} films  ·  {tot_s} sessions  ·  {hms(tot_t)} total")
            if film_paths:
                film_lb.select_set(0)
                show_detail(film_paths[0])

        tk.Button(bot, text="🗑  Radera markerade", command=_delete_selected,
                  bg="#7a1a2a", fg="white",
                  activebackground="#a02535", activeforeground="white",
                  relief="flat", padx=10, pady=4,
                  font=("Segoe UI", 9), cursor="hand2").pack(
            side="left", padx=10, pady=6)
        tk.Label(bot, text="Ctrl+klick / Shift+klick för flera",
                 bg=C_BG2, fg=C_FG_DIM,
                 font=("Segoe UI", 7, "italic")).pack(side="left")

# *************** DEL 15b - REPLACE-LIST EDITOR ***************

    def _show_replace_editor(self, parent=None) -> None:
        """Dialog for editing per-language subtitle word-replacement lists."""
        par = parent or self.root
        top = tk.Toplevel(par)
        top.title("Word list – live replacement")
        top.configure(bg=C_BG)
        _place_top_center(top, 620, 560)
        top.transient(par)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda _: top.destroy())

        _B2 = dict(bg=C_BTN, fg="white", activebackground=C_BTN_HOV,
                   activeforeground="white", relief="flat",
                   padx=8, pady=4, font=("Segoe UI", 9), cursor="hand2")

        # ── Collect available languages ──────────────────────────
        # All languages that have a dir-label, plus any existing JSON files
        lang_set = []
        for lbl in self.settings.get("subtitle_dir_langs", {}).values():
            if lbl and lbl.lower() not in [x.lower() for x in lang_set]:
                lang_set.append(lbl)
        # Also add any existing replace JSON files not already listed
        try:
            for fn in os.listdir(SUB_REPLACE_DIR):
                if fn.startswith("replace_") and fn.endswith(".json"):
                    key = fn[8:-5]   # strip "replace_" and ".json"
                    if key not in [_lang_file_key(x) for x in lang_set]:
                        lang_set.append(key)
        except Exception:
            pass
        if not lang_set:
            lang_set = ["svenska", "english"]

        # ── Header ──────────────────────────────────────────────
        hdr = tk.Frame(top, bg=C_BG3)
        hdr.pack(fill="x")
        tk.Label(hdr,
                 text="  Live word replacement in subtitles",
                 bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 10, "bold")).pack(side="left", pady=8)

        # ── Language selector ────────────────────────────────────
        sel_row = tk.Frame(top, bg=C_BG)
        sel_row.pack(fill="x", padx=14, pady=(10, 4))
        tk.Label(sel_row, text="Language:", bg=C_BG, fg=C_FG,
                 font=("Segoe UI", 9)).pack(side="left")

        lang_var = tk.StringVar(value=lang_set[0] if lang_set else "")
        lang_menu = tk.OptionMenu(sel_row, lang_var, *lang_set)
        lang_menu.configure(bg=C_BTN, fg="white", activebackground=C_BTN_HOV,
                            activeforeground="white", relief="flat",
                            font=("Segoe UI", 9), highlightthickness=0)
        lang_menu["menu"].configure(bg=C_BG2, fg=C_FG,
                                    activebackground=C_BG3,
                                    activeforeground=C_FG)
        lang_menu.pack(side="left", padx=8)

        # New-language entry
        new_lang_var = tk.StringVar()
        new_lang_entry = tk.Entry(sel_row, textvariable=new_lang_var,
                                  bg=C_BG2, fg=C_FG, insertbackground=C_FG,
                                  relief="flat", font=("Segoe UI", 9), width=14)
        no_blink(new_lang_entry)
        new_lang_entry.pack(side="left", padx=(20, 4))
        tk.Label(sel_row, text="← new language", bg=C_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 8, "italic")).pack(side="left")

        # ── Listbox with pairs ───────────────────────────────────
        tk.Label(top,
                 text="  Original  →  Replacement     "
                      "(double-click to edit)",
                 bg=C_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 8, "italic")).pack(anchor="w", padx=14)

        list_frame = tk.Frame(top, bg=C_BG)
        list_frame.pack(fill="both", expand=True, padx=14, pady=(2, 4))

        sb_lb = tk.Scrollbar(list_frame, orient="vertical")
        sb_lb.pack(side="right", fill="y")
        lb = tk.Listbox(list_frame, bg=C_BG2, fg=C_FG,
                        selectbackground=C_BG3, selectforeground=C_FG,
                        activestyle="none",
                        font=("Consolas", 10),
                        relief="flat", bd=0, width=60, height=16,
                        yscrollcommand=sb_lb.set)
        lb.pack(side="left", fill="both", expand=True)
        sb_lb.config(command=lb.yview)

        # Internal state: list of [original, replacement]
        pairs = []

        def _load_lang(*_):
            pairs.clear()
            lang = lang_var.get()
            if not lang:
                return
            # Try to load; also check for JSON parse errors to give user feedback
            path = os.path.join(SUB_REPLACE_DIR,
                                f"replace_{_lang_file_key(lang)}.json")
            if os.path.isfile(path):
                try:
                    with open(path, "r", encoding="utf-8") as _fh:
                        _raw = json.load(_fh)
                    data = {k.strip().lower(): str(v).strip().lower()
                            for k, v in _raw.items()
                            if k.strip() and not k.strip().startswith("__")}
                except Exception as _e:
                    lb.delete(0, "end")
                    lb.insert("end", f"  ⚠  Filen kunde inte läsas in: {_e}")
                    lb.insert("end", "  Kontrollera att JSON-syntaxen är korrekt")
                    lb.insert("end", "  (kommatecken mellan alla rader, inga dubbletter)")
                    return
            else:
                data = {}
            for orig, repl in sorted(data.items()):
                pairs.append([orig, repl])
            _refresh()

        def _refresh():
            lb.delete(0, "end")
            for orig, repl in pairs:
                lb.insert("end", f"  {orig:<22}→   {repl}")

        lang_var.trace_add("write", _load_lang)
        _load_lang()

        # ── Edit row ────────────────────────────────────────────
        edit_frame = tk.Frame(top, bg=C_BG)
        edit_frame.pack(fill="x", padx=14, pady=(0, 4))

        orig_var = tk.StringVar()
        repl_var = tk.StringVar()

        tk.Label(edit_frame, text="Original:", bg=C_BG, fg=C_FG,
                 font=("Segoe UI", 9)).pack(side="left")
        orig_entry = tk.Entry(edit_frame, textvariable=orig_var,
                              bg=C_BG2, fg=C_FG, insertbackground=C_FG,
                              relief="flat", font=("Segoe UI", 9), width=18)
        no_blink(orig_entry)
        orig_entry.pack(side="left", padx=(4, 10))

        tk.Label(edit_frame, text="→", bg=C_BG, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(side="left")

        tk.Label(edit_frame, text="Replacement:", bg=C_BG, fg=C_FG,
                 font=("Segoe UI", 9)).pack(side="left", padx=(10, 0))
        repl_entry = tk.Entry(edit_frame, textvariable=repl_var,
                              bg=C_BG2, fg=C_FG, insertbackground=C_FG,
                              relief="flat", font=("Segoe UI", 9), width=18)
        no_blink(repl_entry)
        repl_entry.pack(side="left", padx=4)

        def _add_or_update(_evt=None):
            orig = orig_var.get().strip().lower()
            repl = repl_var.get().strip().lower()   # lower-case so _repl() can preserve case
            if not orig or not repl:
                return
            # Update existing or append
            for pair in pairs:
                if pair[0] == orig:
                    pair[1] = repl
                    _refresh()
                    orig_var.set(""); repl_var.set("")
                    orig_entry.focus_set()
                    return
            pairs.append([orig, repl])
            pairs.sort(key=lambda x: x[0])
            _refresh()
            orig_var.set(""); repl_var.set("")
            orig_entry.focus_set()

        def _delete():
            sel = lb.curselection()
            if sel:
                del pairs[sel[0]]
                _refresh()

        def _on_dbl_click(_evt):
            sel = lb.curselection()
            if not sel:
                return
            orig, repl = pairs[sel[0]]
            orig_var.set(orig)
            repl_var.set(repl)
            orig_entry.focus_set()

        lb.bind("<Double-Button-1>", _on_dbl_click)
        repl_entry.bind("<Return>", _add_or_update)
        orig_entry.bind("<Return>", lambda _: repl_entry.focus_set())

        # ── Buttons ─────────────────────────────────────────────
        btn_row = tk.Frame(top, bg=C_BG)
        btn_row.pack(fill="x", padx=14, pady=(0, 4))

        def _btn(parent, label, cmd):
            b = tk.Button(parent, text=label, command=cmd, **_B2)
            _bind_hover(b)
            b.pack(side="left", padx=3)
            return b

        _btn(btn_row, "＋ Add / Update", _add_or_update)
        _btn(btn_row, "✕ Remove selected",         _delete)

        def _save_current():
            lang = new_lang_var.get().strip() or lang_var.get()
            if not lang:
                return
            data = {orig: repl for orig, repl in pairs}
            save_replace_list(lang, data)
            # Add to option menu if new
            menu = lang_menu["menu"]
            existing = [menu.entrycget(i, "label")
                        for i in range(menu.index("end") + 1)]
            if lang not in existing:
                menu.add_command(label=lang,
                                 command=lambda v=lang: lang_var.set(v))
                if lang not in lang_set:
                    lang_set.append(lang)
                lang_var.set(lang)
                new_lang_var.set("")
            auto_close_popup(self.root,
                             f"✓  Word list saved: {lang}  ({len(pairs)} words)")

        def _clear_temp():
            count = 0
            try:
                for fn in os.listdir(SUB_REPLACE_TEMP):
                    try:
                        os.remove(os.path.join(SUB_REPLACE_TEMP, fn))
                        count += 1
                    except Exception:
                        pass
            except Exception:
                pass
            auto_close_popup(self.root, f"✓  Cleared {count} temp files")

        save_row = tk.Frame(top, bg=C_BG2)
        save_row.pack(fill="x", pady=0)
        _btn(save_row, "💾  Save word list", _save_current)
        _btn(save_row, "🗑  Clear temp files", _clear_temp)
        _btn(save_row, "Close", top.destroy)

        tk.Label(top,
                 text=f"Files saved in:  {SUB_REPLACE_DIR}",
                 bg=C_BG2, fg=C_FG_DIM,
                 font=("Segoe UI", 7, "italic")).pack(
                     anchor="w", padx=14, pady=(0, 6))


# *************** DEL 16 - ABOUT ***************

    def _show_about(self) -> None:
        import webbrowser
        top = tk.Toplevel(self.root)
        top.title(f"About {self.APP_NAME}")
        top.configure(bg=C_BG3)
        top.resizable(False, False)
        top.transient(self.root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda _: top.destroy())

        tk.Label(top, text="[>]", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 38)).pack(pady=(18, 0))
        tk.Label(top, text=self.APP_NAME, bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 20, "bold")).pack()
        tk.Label(top, text=f"v{self.APP_VER}  -  libmpv-based lightweight player",
                 bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9, "italic")).pack(pady=(2, 10))

        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x", padx=20)
        tk.Label(top, text='Created by  Lars "Issu" Olsson',
                 bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 10, "bold")).pack(pady=(14, 0))

        doc = tk.Label(top, text="View documentation",
                       bg=C_BG3, fg=C_ACCENT,
                       font=("Segoe UI", 9, "underline"), cursor="hand2")
        doc.pack(pady=(6, 2))
        doc.bind("<Button-1>", lambda _: open_url(self.DOC_URL))
        doc.bind("<Enter>",    lambda _: doc.configure(fg="#b4d4ff"))
        doc.bind("<Leave>",    lambda _: doc.configure(fg=C_ACCENT))

        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x", padx=20, pady=(14, 0))
        tk.Label(top,
                 text="If you enjoy MKV Player, a small gift is always welcome!",
                 bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8, "italic"),
                 wraplength=300, justify="center").pack(pady=(10, 6))

        df = tk.Frame(top, bg="#252535", padx=16, pady=10)
        df.pack(fill="x", padx=20, pady=(0, 6))
        for lbl, url in [("Revolut", "https://revolut.me/lars72oeh"),
                          ("PayPal",  "https://paypal.me/issusbarn"),
                          ("Wise",    "https://wise.com/pay/me/larsdenniso")]:
            w = tk.Label(df, text=lbl, bg="#252535", fg=C_ACCENT,
                         font=("Segoe UI", 9, "underline"), cursor="hand2")
            w.pack(anchor="w")
            w.bind("<Button-1>", lambda _, u=url: open_url(u))
            w.bind("<Enter>",    lambda _, x=w: x.configure(fg="#b4d4ff"))
            w.bind("<Leave>",    lambda _, x=w: x.configure(fg=C_ACCENT))

        tk.Button(top, text="Close", command=top.destroy,
                  bg="grey25", fg="white",          # bg = grey25
                  activebackground="grey40", activeforeground="white",
                  relief="flat", padx=14, pady=4,
                  font=("Segoe UI", 9),
                  cursor="hand2").pack(pady=(8, 18))


# *************** DEL 17 - HELP ***************

    def _show_help(self) -> None:
        top = tk.Toplevel(self.root)
        top.title(f"{self.APP_NAME}  -  Help")
        top.configure(bg=C_BG)
        _place_top_center(top, 670, 580)
        top.transient(self.root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda _: top.destroy())

        inner = tk.Frame(top, bg=C_BG)
        inner.pack(fill="both", expand=True, padx=10, pady=10)
        sb = tk.Scrollbar(inner, orient="vertical")
        sb.pack(side="right", fill="y")
        txt = tk.Text(inner, bg=C_BG2, fg=C_FG,
                      font=("Consolas", 10),
                      yscrollcommand=sb.set,
                      wrap="word", relief="flat",
                      padx=14, pady=10,
                      insertofftime=0, insertontime=9999999)
        no_blink(txt)
        txt.pack(fill="both", expand=True)
        sb.config(command=txt.yview)
        txt.bind("<MouseWheel>",
                 lambda e: txt.yview_scroll(-1*(e.delta//120), "units"))

        HELP = """\
MKV Player  -  Help & Usage Guide
==================================

OVERVIEW
--------
MKV Player is a lightweight video player powered by libmpv.
Supports MKV, MP4, AVI, MOV, WMV, FLV, WebM, TS, M2TS and
anything FFmpeg can decode.

Required: libmpv-2.dll  (place in Helpfiles/1---Movie/)
Download: https://sourceforge.net/projects/mpv-player-windows/files/libmpv/
Install:  pip install python-mpv


OPENING A FILE
--------------
  File > Open File...   /   Browse button   /   Ctrl+O
  Open button           – searchable list of all films in configured
                          movie directories (Settings → Directories)
  Last button           – instantly replay the most recently opened file
  Latest ▾ button       – de 5 senaste öppnade filerna
  Plan 📋 button        – your watchlist (up to 10 films)

  Films in a private folder are skipped by Last and Latest ▾
  but still resume where you left them – see PRIVATE FOLDERS.


FINDING FILMS (Open list + 🎬 DB search)
----------------------------------------
Both search the registered folders AND their sub-folders (up to
5 levels), so documentaries and series in sub-folders are found.
Each folder is read once per session (the Open list fills in while
it reads); saving Settings makes it read again.

  Open list search box - words, not raw text:
    "speak no evil (2024)" finds Speak_no_evil_(2022).mkv
    (a year never has to match; matching years just come first)
    "the ring" finds Ring,_The.mkv     "spe no ev" finds it too
    a series folder name finds the episodes inside it.

  🎬 DB search, double-click / Enter on a film:
    Looks for the file by title (and extra title); "The", case,
    punctuation, "_" and a year in the name are ignored, "II" = "2",
    and Title---Extra_title files match either title.
    Settings → Directories → "Category folders": tell it where
    Good / Okay / ... live (comma-separated, several disks are fine).
    The film's own category folders are searched FIRST and the
    other folders are never read if it is found there.
    The file starts at once only when it is exactly that title and
    only one such file exists (the same file on two mirrored disks
    counts as one).  "Alien" never starts "Aliens", and "Taken" never
    starts "Taken_2": similar files are shown in a list to choose
    from.  If the year in the file name differs from the database by
    more than a year, you are asked first.


CONTROLS - AUTO-HIDE
---------------------
The playback controls hide automatically when the cursor
moves away from the bottom of the window. Move the mouse
to the bottom edge to bring them back.

  Open           – show a list of all films in configured directories
  Browse         – open a file via dialog (same as Ctrl+O)
  Last           – reopen the most recently played file
  Latest ▾       – popup with the 5 most recently opened files
  🎬 DB          – search the Movie Database (requires movies.db;
                   configure path in Settings → Directories)
  📊 Stats       – view play statistics per film (sessions, duration)
  ⚙              – open Settings
  Play / Pause   – toggle playback
  Stop           – stop and reset position
  << -Xs         – rewind X seconds  (X configurable in Settings)
  +Xs >>         – forward X seconds
  Next ▶▶        – play next file in folder (alphabetical)
  Sub ▾          – subtitle selection
  Audio ▾        – audio track selection
                   Dimmed = one track (no choice). Red = multiple tracks.
                   Auto-selects best track on open (priority in Settings).
  Plan 📋        – open/manage your watchlist (max 10 films)
  🗑 Mark        – mark the loaded file for deletion (renames it;
                   never deletes – see MARK FOR DELETION below)
  Fullscreen     – toggle fullscreen (same as F / F11)
  Close          – close the player
  🎧 Connect     – far right: (re)connect your Bluetooth headphones with
                   one click (see BLUETOOTH HEADPHONES below)
  Seek bar       – click anywhere to jump straight there, or drag
                   to scrub; video updates live
  Volume slider  – 0 to 200; or use Up/Down keys


BLUETOOTH HEADPHONES
--------------------
  If the headphones are paired in Windows but make only a little noise
  and do not really connect, click the 🎧 Connect button (far right of
  the control bar).  It does what Windows' own Connect button does, so
  you do not have to leave the film.

  First click: pick your headphones from the list of devices paired in
  Windows (pair them once in Windows > Settings > Bluetooth & devices).
  After that every click just reconnects the chosen headphones.
  Right-click anywhere > "Choose other Bluetooth headphones..." to
  change the choice.  The button shows Wait... / Connected / Failed.

  If it always fails with "no working Bluetooth adapter": open Windows
  Device Manager > Bluetooth.  An adapter with a yellow warning sign
  (e.g. a USB Bluetooth stick whose driver does not start) is the cause.


CLOSE
-----
  X button  (top-right corner, always visible)
  Esc       (when not in fullscreen - exits fullscreen first)
  File > Exit  /  Alt+F4


WINDOW MODES
------------
  Key 1           Windowed       restore normal window size
  Enter           Maximize       fills screen, respects taskbar
  Ctrl+Enter      Stretch-max    maximized + video stretched to fill
                                 (removes black bars at sides/top)
  F  /  F11       Fullscreen     covers entire screen incl. taskbar
  Ctrl+F11        FS Stretch     fullscreen + stretch (no black bars)
  Esc             Exit fullscreen  - OR -  close player

  The normal modes keep the full picture and show black bars; they no
  longer crop the sides.  If the edges still look cut off, check
  Settings > Video > Black bars (set it to "Visible / keep aspect ratio").

  When a film starts playing, it goes to fullscreen automatically (if
  "Go to F11 when playback starts" is on) using the mode chosen under
  Settings > Playback > Default fill mode: stretched / cropped-no-stretch
  / black bars.  Square videos always use cropped-no-stretch.


PICTURE / HDR BRIGHTNESS
------------------------
  If an HDR film suddenly gets much brighter or darker between scenes,
  that "flicker" comes from the player's dynamic HDR tone-mapping, not
  from the file.  It is OFF by default for a stable picture.  Toggle it
  under Settings > Video > HDR brightness.


KEYBOARD SHORTCUTS
------------------
  Spacebar        Play / Pause  (starts the Latest file if none is loaded)
  Left / Right    -5 s / +5 s
  PgUp / PgDn    -X s / +X s  (skip, configurable in Settings)
  Up / Down       Volume +5 / -5
  M               Toggle mute
  N               Play next file in folder
  ,               Subtitle delay  -step
  .               Subtitle delay  +step
  S               Write the , / . subtitle delay into the subtitle file
                  (only when a delay is set; asks first, Enter = yes;
                  the old file is kept as BACKUP-<name>)
  Shift+,  (;)    Audio delay  -step
  Shift+.  (:)    Audio delay  +step
  1               Windowed mode
  Enter           Maximize (respects taskbar)
  Ctrl+Enter      Maximize + stretch (no black bars)
  F  /  F11       True fullscreen
  Ctrl+F11        Fullscreen stretch (no black bars)
  Esc             Exit fullscreen  OR  close player
  Ctrl+O          Open file


SUBTITLE & AUDIO SYNC
----------------------
Like PotPlayer:
  ,  /  .                subtitle earlier / later
  Shift+, (;) / Shift+. (:)  audio earlier / later

Step size is set in Settings (default 100 ms).
A popup confirms the current delay after each press.

Found the right place with , and . ?  Press S (only works while a
delay is set).  The film pauses and asks "Update the subtitle file?".
Enter (Yes) rewrites the times in the subtitle file, sets the delay
back to 0 and loads the subtitle again - it looks the same, but the
file itself is now correct.  The old file is kept next to it as
BACKUP-<name>.  Esc (No) changes nothing.


LIVE WORD REPLACEMENT
----------------------
When enabled (default: on), subtitles are processed through
a per-language word list before being sent to mpv.  A temp
copy of the .srt/.ass file is created; the original is
never modified.

Language detection (in priority order):
  1. The language label set for the subtitle directory
     (Settings → Directories → double-click to label).
  2. Auto-detect from content:
       å/ä/ö found  → svenska
       "yes" / "no" → english

Word lists: Settings → Subtitle → Edit word lists…

Replacements are word-boundary-matched and case-preserving:
  "nån" → "någon"   preserves  Nån→Någon / NÅN→NÅGON

Files stored in:
  Helpfiles/MKV/sub_replace/replace_svenska.json
Temp files:
  Helpfiles/MKV/sub_temp/


SUBTITLES – PLAIN TEXT
-----------------------
Enable "Ren text" in Settings to strip all bold, italic,
color and other formatting tags from subtitles. Only the
plain text content is shown.


SUBTITLE POSITION (>100%)
--------------------------
Position goes from 0 (top) to 150 in Settings.
Values above 100 push subtitles below the natural bottom
edge - useful for 0.65× scale where a single line at 100%
sits too high.  Use per-film save to remember the setting
for each movie individually.


IGNORED PREFIXES/SUFFIXES
--------------------------
Downloaded films often get an extra prefix/suffix, e.g.
"Downloaded_In_the_grey-source" instead of "In_the_grey".

Exact filename match is always tried first.  If the film's
name starts/ends with a trigger you've added, subtitles are
ALSO searched for under the name with that part removed -
and used as the default choice only when no exact match
exists.  Both versions (if found) show up in the Sub ▾ menu,
the ignore-based one marked "(ignorerar prefix/suffix)".

Configure under Settings → Directories → Ignored prefixes/
suffixes.  Each entry is either a Prefix or a Suffix; add as
many as you need (e.g. one entry per release group).


NUMBERS & "THE" IN SUBTITLE NAMES
-----------------------------------
Always on, no setting needed.  Two extra spellings of the film's
name are automatically tried when looking for a subtitle:

  Roman <-> Arabic numerals in a trailing number are the same:
    ..._2   also looks for  ..._II          (and back again)
    ..._4   also looks for  ..._IV          (and back again)

  A leading "The_" is also looked for moved to the end:
    The_Devil_wears_prada_2  ->  Devil_wears_prada,_The_2
    The_War_2031             ->  War_2031,_The
  (a trailing number is tried both before AND after the moved
  "The", since only the file on disk can say which is right -
  compare "...,_The_2" above with "War_2031,_The").

These matches are marked "(artikel/siffra)" in the Sub ▾ menu,
and - like the ignored prefixes/suffixes above - only become the
default pick when no exact match exists at all.


AUTO-RELOAD SUBTITLES
----------------------
When enabled (default: on) MKV Player checks every ~2 s
whether the active subtitle file(s) have been modified on
disk. If so, the subtitle is automatically reloaded.
Useful when editing .srt files in an external editor while
watching. Toggle in Settings → Playback.


HIDE MOUSE CURSOR
-----------------
When enabled (default: on) the mouse cursor is hidden
2 seconds after the last movement during playback.
Moving the mouse instantly restores the cursor.
Toggle in Settings → Playback.


LATEST (5 most recent files)
------------------------
The "Latest ▾" button opens a popup menu listing the
5 most recently opened files. Click any entry to play it
directly. Missing files are shown greyed out.
"Clear list" clears the entire history.


PRIVATE FOLDERS (no history)
----------------------------
Settings → Directories → "Private folders" takes a list of
folders. A film inside one of them – or inside any subfolder
below it – leaves no trace in any history:

  • it never appears in the Latest ▾ list
  • it never becomes the "Last" file, and it does not move
    the Open dialog to its folder either
  • no play session, no watch minutes, no fast-forward events
    are recorded for it
  • it never gets a date in the "Latest 25%" column of the
    movie DB, and no "· N min" in the Open list

The one thing that IS kept is the playback POSITION, so the
film resumes where you left it. Those positions live in their
own file, MKVPlayer_resume_private.json, where the key is a
SHA-256 hash of the path – opening that file shows hex strings
and second counts, no titles and no folder names. The same
28-day rule applies as for ordinary films.

Adding a folder and pressing Save also cleans up what its
films have ALREADY left behind: Latest entries, the Last file
and their play statistics are removed, and their saved
positions are moved over to the private file – so marking a
folder private afterwards does not cost you your positions.

Removing a folder from the list only stops the rule from that
point on; the entries already cleaned are gone for good.


MARK FOR DELETION
-----------------
Click "🗑 Mark" while a file is loaded to flag it for deletion.
The file is RENAMED by adding a marker to its name – the program
never deletes anything itself; you remove the marked files
manually, later (e.g. sort by name and delete the top ones).

  Default marker:  0---DELETE-   (added as a prefix)
  Configure the marker text and prefix/suffix in
  Settings → Playback → Mark for deletion.

Playback continues from the same position right after marking.
Already-marked files are left untouched (no double-marking).


PLAN (watchlist)
----------------
The "Plan 📋" button opens your watchlist (up to 10 films).
  + File      – browse and add a video file
  + Current   – add the currently playing film
  ▶ Play      – play the selected entry
  ✕ Remove    – remove the selected entry
  ▲ / ▼       – reorder entries
  Double-click or Enter – play selected entry
  ✓ = file found on disk   ○ = file not found


BUTTON BAR CUSTOMISATION
-------------------------
In Settings → Buttons you can:
  • Show or hide individual buttons (checkbox)
  • Change the order (▲ ▼ buttons, top = leftmost)

Changes take effect when you click "Save & close".


AUTO-PLAY NEXT
--------------
When a file ends, the next file in the same folder
(alphabetical order) is played automatically.
Toggle in Settings > Playback.


RESUME POSITION
---------------
Your position in each file is saved automatically every
30 seconds and on close. When you reopen the same file
within 28 days, playback resumes from where you stopped.

A brief notification confirms the resume position.

To start from the beginning: press Stop, then seek to 0:00.

Resume database:
  Helpfiles/0---Settings/MKVPlayer_resume.json


FILES
-----
  Config:   Helpfiles/MKV/MKVPlayer_settings.json
  Resume:   Helpfiles/MKV/MKVPlayer_resume.json
  Private:  Helpfiles/MKV/MKVPlayer_resume_private.json
  SubConf:  Helpfiles/MKV/MKVPlayer_sub_settings.json
  Stats:    Helpfiles/MKV/MKVPlayer_stats.json
  Notes:    Helpfiles/MKV/MKVPlayer_movie_notes.json
  Log:      Helpfiles/0---Empty/MKVPlayer_crash.log
"""
        txt.insert("1.0", HELP)
        txt.configure(state="disabled")

        tk.Button(top, text="Close", command=top.destroy,
                  bg="grey25", fg="white",          # bg = grey25
                  activebackground="grey40", activeforeground="white",
                  relief="flat", padx=14, pady=4,
                  font=("Segoe UI", 9),
                  cursor="hand2").pack(pady=(0, 10))


# *************** DEL 18 - ENTRY POINT ***************

# *************** DEL XX - ONE INSTANCE, AND THE FILE IT WAS GIVEN ***********
# A program that OTHER programs open files with needs two things, and having
# only the first is the trap: it reads the path fine, but every file opens a
# NEW window.  Ten images from File Manager, ten windows.
#
#   1. read sys.argv[1:]            - which this program already did
#   2. hand the path to the copy that is ALREADY RUNNING, and exit
#
# The lock is a BOUND SOCKET, never a lock file: a lock file survives a crash
# and then locks you out of your own program for good.  A socket dies with the
# process, whatever killed it.
#
# Ports in use:  ExeForge 50597 · File_manager 50598 · SeeView 50599 ·
#                MKV-player 50600.  Pick the next free one for a new receiver.
#
# NOTE the queue is drained by the MAIN thread.  after() must never be called
# from the socket thread - a worker's after() only fires while mainloop
# happens to be running, and that is how the last file goes missing.
_SI_PORT = 50600


def _si_paths() -> list:
    """Paths handed to us on the command line.  A leading "-" is a flag."""
    out = []
    for a in sys.argv[1:]:
        a = (a or "").strip().strip('"')
        if a and not a.startswith("-") and os.path.exists(a):
            out.append(os.path.abspath(a))
    return out


def _si_hand_over(paths: list) -> bool:
    """Give the paths to a copy already running.  True if it took them."""
    try:
        with socket.create_connection(("127.0.0.1", _SI_PORT), timeout=1.5) as s:
            s.sendall(("\n".join(paths) + "\n").encode("utf-8"))
            return True
    except OSError:
        return False


def _si_claim():
    """Bind the port, or None when another copy already holds it."""
    try:
        srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # No SO_REUSEADDR on purpose: it would let a second copy bind too,
        # which is the one thing this must not allow.
        srv.bind(("127.0.0.1", _SI_PORT))
        srv.listen(4)
        return srv
    except OSError:
        return None


def _si_serve(srv, queue: list):
    """Background: take paths from later launches and queue them."""
    while True:
        try:
            conn, _ = srv.accept()
        except OSError:
            return
        try:
            with conn:
                conn.settimeout(2.0)
                data = b""
                while len(data) < 65536:
                    chunk = conn.recv(4096)
                    if not chunk:
                        break
                    data += chunk
            for line in data.decode("utf-8", "replace").splitlines():
                if line.strip():
                    queue.append(line.strip())
        except Exception:
            pass


def si_listen(root, on_path) -> bool:
    """Hold the port for this session and feed later launches to on_path.

    on_path is called on the MAIN thread, once per file.  False means the
    port could not be bound - the program then simply runs without the
    hand-over, which is far better than refusing to start."""
    srv = _si_claim()
    if srv is None:
        return False
    queue = []
    threading.Thread(target=_si_serve, args=(srv, queue), daemon=True).start()

    def _drain():
        while queue:
            p = queue.pop(0)
            try:
                on_path(p)
            except Exception:
                pass
            # Someone asked for this window; put it where they can see it.
            # (This lights the taskbar button rather than stealing focus -
            # Windows only lets the FOREGROUND process do more.)
            try:
                root.deiconify()
                root.lift()
                root.focus_force()
            except Exception:
                pass
        try:
            root.after(400, _drain)
        except Exception:
            pass

    root.after(300, _drain)
    return True


if __name__ == "__main__":
    try:
        # argv[0] = programmet självt, argv[1] = filen OS:et skickar med
        # (dubbelklick på en .mkv-fil, eller "Öppna med" -> MKV Player).
        # strip('"') skyddar mot ett ev. kvarvarande citationstecken om
        # kommandot i registret är felformaterat.
        _cli = _si_paths()
        if _cli and _si_hand_over(_cli):
            sys.exit(0)      # a running copy took it
        _initial_file = sys.argv[1].strip('"') if len(sys.argv) > 1 else None
        MKVPlayer(_initial_file)
    except Exception:
        crash_handler(*sys.exc_info())
