
# *************** DEL 01 – IMPORTS & TODO ***************
# ToDo:
#   - Launch GUI with dark industrial theme
#   - TWO block types:
#       1. IP  → push rule to Windows Firewall via netsh 
#       2. Domain → write redirect to Windows hosts file (127.0.0.1 as default)
#   - Manage unified JSON blocklist (add / remove / import / export)
#   - Log all actions to /Helpfiles/0---Empty/
#   - Persist window geometry + settings in /Helpfiles/0---Settings/
#   - This works even if the .py is compiled to .exe and moved elsewhere (EXE-safe paths)
#   - Crash-catcher writes full traceback to /Helpfiles/0---Empty/crash.log
#   - All "success" popups auto-close after 1 second
#   - No blinking cursors anywhere (insertofftime=0, insertontime=9999999)
#   - All UI text in English
#   - PASTE MANY (2026-11-24): paste a whole list (IPs, CIDR, domains, URLs, hosts-file
#     lines, free text) -> the program sorts it into IP / Domain, skips duplicates and
#     rubbish, shows a preview, then adds (and optionally pushes) everything in one go.
#     Pasting 2+ lines into the value field opens it automatically. See DEL 08b + DEL 16u.

import sys
import os
import json
import platform
import subprocess
import traceback
import threading
import logging
import re
import shutil
import ctypes
from datetime import datetime
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import os
import sys
import webbrowser  # the open-with block needs this at module level


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


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


# *************** DEL 02 – EXE-SAFE PATH HELPERS ***************
# Always resolve relative to the running script / frozen executable.
def get_base_dir() -> str:
    if getattr(sys, "frozen", False):
        return _program_home()
    return _program_home()

BASE_DIR      = get_base_dir()
HELPFILES_DIR = os.path.join(BASE_DIR, "Helpfiles")
LOG_DIR       = os.path.join(HELPFILES_DIR, "0---Empty")
SETTINGS_DIR  = os.path.join(HELPFILES_DIR, "0---Settings")

BLOCKLIST_FILE = os.path.join(SETTINGS_DIR, "fw_blocklist.json")
SETTINGS_FILE  = os.path.join(SETTINGS_DIR, "fw_settings.json")
LOG_FILE       = os.path.join(LOG_DIR,      "fw_firewall.log")
CRASH_FILE     = os.path.join(LOG_DIR,      "fw_crash.log")

HOSTS_FILE     = r"C:\Windows\System32\drivers\etc\hosts"
HOSTS_MARKER   = "# --- IssusFirewall ---"   # start/end tag in hosts file
HOSTS_BACKUP   = os.path.join(SETTINGS_DIR,  "fw_hosts_backup.bak")

for _d in (LOG_DIR, SETTINGS_DIR):
    os.makedirs(_d, exist_ok=True)

# *************** DEL 03 – LOGGING SETUP ***************
logging.basicConfig(
    filename=LOG_FILE,
    level=logging.DEBUG,
    format="%(asctime)s  [%(levelname)s]  %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
)
log = logging.getLogger("IssusFirewall")

def log_info(msg: str):  log.info(msg)
def log_error(msg: str): log.error(msg)

# *************** DEL 04 – CRASH CATCHER ***************
def crash_handler(exc_type, exc_value, exc_tb):
    """Global exception hook – writes crash to file and shows dialog."""
    crash_text = "".join(traceback.format_exception(exc_type, exc_value, exc_tb))
    ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    entry = f"\n{'='*60}\n{ts}\n{crash_text}\n"
    try:
        with open(CRASH_FILE, "a", encoding="utf-8") as f:
            f.write(entry)
    except Exception:
        pass
    log_error(f"CRASH:\n{crash_text}")
    try:
        messagebox.showerror(
            "Issu's Firewall – Crash Detected",
            f"An unexpected error occurred:\n\n{exc_value}\n\nDetails saved to:\n{CRASH_FILE}",
        )
    except Exception:
        pass
    sys.__excepthook__(exc_type, exc_value, exc_tb)

sys.excepthook = crash_handler

# *************** DEL 04b – WINDOW ICON (WIN32) ***************
def _set_window_icon(root) -> None:
    """
    Set the window/taskbar icon via both tkinter and Win32 WM_SETICON.
    Must be called via root.after(0, ...) so tkinter doesn't overwrite it.
    Reads Icons/Firewall_adding.ico next to the script / EXE.
    """
    script_dir = get_base_dir()
    prog_name  = os.path.splitext(os.path.basename(
        sys.executable if getattr(sys, "frozen", False) else __file__
    ))[0]
    ico_path = os.path.join(script_dir, "Icons", f"{prog_name}.ico")
    if not os.path.isfile(ico_path):
        log.warning("Icon file not found: %s", ico_path)
        return

    # Kanal 1: tkinters eget API
    try:
        root.iconbitmap(ico_path)
    except Exception as e:
        log.warning("iconbitmap failed: %s", e)

    # Kanal 2: WM_SETICON via Win32 (taskbar + Alt-Tab)
    if platform.system() != "Windows":
        return
    try:
        user32          = ctypes.windll.user32
        LR_LOADFROMFILE = 0x0010
        LR_DEFAULTSIZE  = 0x0040
        IMAGE_ICON      = 1
        WM_SETICON      = 0x0080

        hwnd = user32.FindWindowW(None, root.title())
        if not hwnd:
            log.warning("FindWindowW returned NULL — icon not set via Win32")
            return
        hbig = user32.LoadImageW(None, ico_path, IMAGE_ICON,  0,  0,
                                 LR_LOADFROMFILE | LR_DEFAULTSIZE)
        hsml = user32.LoadImageW(None, ico_path, IMAGE_ICON, 16, 16,
                                 LR_LOADFROMFILE)
        if hbig:
            user32.SendMessageW(hwnd, WM_SETICON, 1, hbig)
        if hsml:
            user32.SendMessageW(hwnd, WM_SETICON, 0, hsml)
        log.info("Win32 WM_SETICON applied: %s", ico_path)
    except Exception as e:
        log.warning("Win32 icon setup failed: %s", e)


# *************** DEL 05 – ADMIN CHECK ***************
def is_admin() -> bool:
    try:
        return ctypes.windll.shell32.IsUserAnAdmin() != 0
    except Exception:
        return False

# *************** DEL 06 – SETTINGS LOAD / SAVE ***************
DEFAULT_SETTINGS = {
    "geometry":         "1020x720",
    "last_direction":   "both",
    "last_protocol":    "any",
    "last_block_type":  "ip",          # "ip" or "domain"
    "last_redirect_ip": "127.0.0.1",
    "sash_pos":         370,
}

def load_settings() -> dict:
    try:
        with open(SETTINGS_FILE, "r", encoding="utf-8") as f:
            return {**DEFAULT_SETTINGS, **json.load(f)}
    except Exception:
        return dict(DEFAULT_SETTINGS)

def save_settings(settings: dict):
    try:
        with open(SETTINGS_FILE, "w", encoding="utf-8") as f:
            json.dump(settings, f, indent=2)
    except Exception as e:
        log_error(f"save_settings: {e}")

# *************** DEL 07 – BLOCKLIST LOAD / SAVE ***************
# Each entry: {"type": "ip"|"domain", "value": "...", "redirect": "127.0.0.1", "note": "...", "added": "..."}
def load_blocklist(path: str = None) -> list:
    """Load blocklist from path, or from the default BLOCKLIST_FILE if path is None."""
    target = path if path else BLOCKLIST_FILE
    try:
        with open(target, "r", encoding="utf-8") as f:
            data = json.load(f)
        if isinstance(data, list):
            return data
    except Exception:
        pass
    return []

def save_blocklist(entries: list):
    try:
        with open(BLOCKLIST_FILE, "w", encoding="utf-8") as f:
            json.dump(entries, f, indent=2)
        log_info(f"Blocklist saved ({len(entries)} entries)")
    except Exception as e:
        log_error(f"save_blocklist: {e}")

# *************** DEL 08 – VALIDATION ***************
_IP_RE   = re.compile(r"^(\d{1,3}\.){3}\d{1,3}$")
_CIDR_RE = re.compile(r"^(\d{1,3}\.){3}\d{1,3}/\d{1,2}$")
_DOM_RE  = re.compile(
    r"^(\*\.)?[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?"
    r"(\.[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?)*$"
)

def validate_ip(value: str) -> bool:
    value = value.strip()
    if _CIDR_RE.match(value):
        ip_part, prefix = value.rsplit("/", 1)
        if int(prefix) > 32:
            return False
        return all(0 <= int(p) <= 255 for p in ip_part.split("."))
    if _IP_RE.match(value):
        return all(0 <= int(p) <= 255 for p in value.split("."))
    return False

def validate_domain(value: str) -> bool:
    value = value.strip().split("/")[0]
    return bool(_DOM_RE.match(value)) and len(value) <= 253

def clean_domain(value: str) -> str:
    """Strip protocol/path so pasted URLs work."""
    v = value.strip()
    for prefix in ("https://", "http://", "//"):
        if v.lower().startswith(prefix):
            v = v[len(prefix):]
    return v.split("/")[0].strip()

# *************** DEL 08b – PASTE-MANY PARSER ***************
# One pasted block of text -> a list of rows. Pure functions: no Tk, no firewall,
# no hosts file, so they run without admin rights and can be tested alone.
#
# Accepted, one OR several per line (separated by space, tab, comma or semicolon):
#   1.2.3.4    10.0.0.0/8    1.2.3.4:443    example.com    *.tracker.net
#   https://ads.example.com/page?x=1    "quoted"    <in angle brackets>
#   hosts-file lines:  0.0.0.0 ads.example.com   /   127.0.0.1 a.com b.com
# '#' starts a comment; it becomes the note of that line's entries.
# Words without a dot (normal sentences around the list) are silently ignored.

_SPLIT_RE = re.compile(r"[\s,;]+")
_NUMERIC_LABELS_RE = re.compile(r"^[0-9.]+$")

def _paste_host(token: str) -> str:
    """Reduce one pasted token to the bare host: no quotes, scheme, user@, port,
    path or query. CIDR (10.0.0.0/8) is returned untouched."""
    t = token.strip().strip("\"'`<>()[]{}")
    t = t.rstrip(".,;:!?")
    if _CIDR_RE.match(t):
        return t
    low = t.lower()
    for prefix in ("https://", "http://", "ftp://", "//"):
        if low.startswith(prefix):
            t = t[len(prefix):]
            break
    t = re.split(r"[/?#\\]", t, maxsplit=1)[0]
    if "@" in t:
        t = t.rsplit("@", 1)[1]
    m = re.match(r"^(.*):(\d{1,5})$", t)
    if m and ":" not in m.group(1):
        t = m.group(1)                       # strip :port
    return t.strip().rstrip(".")

def _looks_like_domain(value: str) -> bool:
    """A real host name: valid labels, at least one dot, a letter-based last label
    (so 999.1.1.1 and 1.2.3 are NOT taken for domains)."""
    if "." not in value or _NUMERIC_LABELS_RE.match(value):
        return False
    if not validate_domain(value):
        return False
    last = value.rsplit(".", 1)[1]
    return len(last) >= 2 and any(ch.isalpha() for ch in last)

def _is_hosts_redirect(tok: str) -> bool:
    """First token of a hosts-file line: the usual block addresses only."""
    return (validate_ip(tok) and "/" not in tok
            and (tok == "0.0.0.0" or tok.startswith("127.")))

def parse_paste(text: str, default_redirect: str = "127.0.0.1",
                default_note: str = "", existing=None) -> list:
    """Sort pasted text into rows.

    existing = set of (type, value_lower) already in the blocklist.
    Each row: {"line", "raw", "status", "type", "value", "redirect", "note", "why"}
      status "new"  - will be added
             "dup"  - already in the list / pasted twice
             "bad"  - looked like an address but is not valid (see "why")
    Ordinary words (no dot) produce no row at all."""
    seen = set(existing or ())
    rows = []
    for n, line in enumerate(str(text).splitlines(), 1):
        # '#' starts a comment only at the start of a line or after a space,
        # so a URL fragment (page#top) is not mistaken for one.
        parts   = re.split(r"(?:^|\s)#", line, maxsplit=1)
        body    = parts[0]
        comment = parts[1] if len(parts) > 1 else ""
        note    = comment.strip() or default_note
        tokens = [t for t in _SPLIT_RE.split(body) if t]
        if not tokens:
            continue
        redirect = default_redirect
        if (len(tokens) >= 2 and _is_hosts_redirect(tokens[0])
                and not any(validate_ip(_paste_host(t)) for t in tokens[1:])):
            redirect = tokens[0]              # hosts-file line: 0.0.0.0 a.com b.com
            tokens   = tokens[1:]
        for tok in tokens:
            host = _paste_host(tok)
            if "." not in host:
                continue                      # an ordinary word: ignore silently
            row = {"line": n, "raw": tok, "status": "bad", "type": "", "value": host,
                   "redirect": "", "note": note, "why": ""}
            if validate_ip(host):
                row.update(type="ip", value=host)
            elif _looks_like_domain(host.lower()):
                row.update(type="domain", value=host.lower(), redirect=redirect)
            else:
                row["why"] = "not a valid IP, CIDR or domain"
                rows.append(row)
                continue
            key = (row["type"], row["value"].lower())
            if key in seen:
                row["status"] = "dup"
            else:
                row["status"] = "new"
                seen.add(key)
            rows.append(row)
    return rows

# *************** DEL 09 – FIREWALL RULE NAMES ***************
RULE_PREFIX = "IssusBlock"

def _fw_rule_name(ip: str, direction: str) -> str:
    safe = ip.replace("/", "_").replace(".", "-")
    return f"{RULE_PREFIX}_{direction.upper()}_{safe}"

# Suppress the console window these CLI tools would otherwise flash on Windows
# when the app is launched windowless (pythonw / frozen EXE). 0 elsewhere.
_NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0) if sys.platform == "win32" else 0

# *************** DEL 10 – NETSH FIREWALL ACTIONS ***************
def _run_netsh(args: list) -> tuple:
    cmd = ["netsh", "advfirewall", "firewall"] + args
    try:
        r = subprocess.run(cmd, capture_output=True, text=True, timeout=15,
                           creationflags=_NO_WINDOW)
        return r.returncode == 0, (r.stdout + r.stderr).strip()
    except Exception as e:
        return False, str(e)

def add_fw_rule(ip: str, direction: str = "both", protocol: str = "any") -> tuple:
    directions = ["in", "out"] if direction == "both" else [direction]
    results = []
    for d in directions:
        name = _fw_rule_name(ip, d)
        _run_netsh(["delete", "rule", f"name={name}"])   # idempotent
        ok, out = _run_netsh([
            "add", "rule", f"name={name}",
            f"dir={d}", "action=block",
            f"remoteip={ip}", f"protocol={protocol}",
            "enable=yes", "profile=any",
        ])
        results.append((d, ok, out))
        log_info(f"add_fw_rule ip={ip} dir={d} proto={protocol} ok={ok}")
    success = all(r[1] for r in results)
    return success, "\n".join(f"[{r[0]}] {r[2]}" for r in results)

def remove_fw_rule(ip: str) -> tuple:
    results = []
    for d in ("IN", "OUT"):
        name = _fw_rule_name(ip, d)
        ok, out = _run_netsh(["delete", "rule", f"name={name}"])
        results.append((d, ok, out))
        log_info(f"remove_fw_rule ip={ip} dir={d} ok={ok}")
    return all(r[1] for r in results), "\n".join(f"[{r[0]}] {r[2]}" for r in results)

# *************** DEL 11 – HOSTS FILE ACTIONS ***************
def _read_hosts() -> str:
    try:
        with open(HOSTS_FILE, "r", encoding="utf-8", errors="replace") as f:
            return f.read()
    except Exception as e:
        log_error(f"_read_hosts: {e}")
        return ""

def _write_hosts(content: str) -> tuple:
    import stat
    # Backup before every write (best-effort)
    try:
        shutil.copy2(HOSTS_FILE, HOSTS_BACKUP)
    except Exception as be:
        log_error(f"_write_hosts backup failed: {be}")

    # Remove read-only attribute if set (common on Windows even for admins)
    original_mode = None
    try:
        original_mode = os.stat(HOSTS_FILE).st_mode
        os.chmod(HOSTS_FILE, original_mode | stat.S_IWRITE)
    except Exception as ce:
        log_error(f"_write_hosts chmod: {ce}")

    # Attempt 1: direct write
    try:
        with open(HOSTS_FILE, "w", encoding="utf-8") as f:
            f.write(content)
        return True, "OK"
    except PermissionError as pe:
        log_error(f"_write_hosts direct write failed: {pe} – trying cmd fallback")

    # Attempt 2: write to temp file then copy via cmd (bypasses ACL locks)
    try:
        tmp_path = HOSTS_FILE + ".issu_tmp"
        with open(tmp_path, "w", encoding="utf-8") as f:
            f.write(content)
        result = subprocess.run(
            ["cmd", "/c", f'copy /y "{tmp_path}" "{HOSTS_FILE}"'],
            capture_output=True, text=True, timeout=10,
            creationflags=_NO_WINDOW,
        )
        try:
            os.remove(tmp_path)
        except Exception:
            pass
        if result.returncode == 0:
            return True, "OK (via cmd copy)"
        return False, (result.stdout + result.stderr).strip()
    except Exception as e2:
        log_error(f"_write_hosts cmd fallback failed: {e2}")
        return False, str(e2)
    finally:
        # Restore original file mode
        if original_mode is not None:
            try:
                os.chmod(HOSTS_FILE, original_mode)
            except Exception:
                pass

def _hosts_block_lines(entries: list) -> str:
    """Build the Issu's section for the hosts file."""
    lines = [HOSTS_MARKER + " BEGIN\n"]
    for e in entries:
        if e.get("type") != "domain":
            continue
        domain   = e.get("value", "").strip()
        redirect = (e.get("redirect") or "127.0.0.1").strip()
        note     = e.get("note", "")
        comment  = f"  # {note}" if note else ""
        lines.append(f"{redirect:<16}{domain}{comment}\n")
        # Also block www. variant automatically (unless already www. or wildcard)
        if not domain.startswith("www.") and not domain.startswith("*"):
            lines.append(f"{redirect:<16}www.{domain}\n")
    lines.append(HOSTS_MARKER + " END\n")
    return "".join(lines)

def sync_hosts(entries: list) -> tuple:
    """Replace the Issu's section in the hosts file. Returns (success, message)."""
    domain_entries = [e for e in entries if e.get("type") == "domain"]
    if not domain_entries:
        return True, "No domain entries to write."
    original = _read_hosts()
    # Strip old Issu's section
    cleaned = []
    inside  = False
    for line in original.splitlines(keepends=True):
        if HOSTS_MARKER + " BEGIN" in line:
            inside = True
        if not inside:
            cleaned.append(line)
        if HOSTS_MARKER + " END" in line:
            inside = False
    new_content = "".join(cleaned).rstrip("\n") + "\n\n" + _hosts_block_lines(domain_entries)
    ok, msg = _write_hosts(new_content)
    if ok:
        log_info(f"Hosts file synced: {len(domain_entries)} domain(s)")
    return ok, msg

def remove_hosts_entries() -> tuple:
    """Remove the entire Issu's section from the hosts file."""
    original = _read_hosts()
    cleaned  = []
    inside   = False
    for line in original.splitlines(keepends=True):
        if HOSTS_MARKER + " BEGIN" in line:
            inside = True
        if not inside:
            cleaned.append(line)
        if HOSTS_MARKER + " END" in line:
            inside = False
    ok, msg = _write_hosts("".join(cleaned))
    log_info(f"Hosts entries removed: {msg}")
    return ok, msg

def flush_dns():
    """Run ipconfig /flushdns after hosts changes."""
    try:
        subprocess.run(["ipconfig", "/flushdns"], capture_output=True, timeout=10,
                       creationflags=_NO_WINDOW)
        log_info("DNS cache flushed")
    except Exception as e:
        log_error(f"flush_dns: {e}")

# *************** DEL 12 – NO-BLINK HELPER ***************
def no_blink(widget):
    try:
        widget.configure(insertofftime=0, insertontime=9999999)
    except Exception:
        pass

# *************** DEL 13 – AUTO-CLOSE POPUP ***************
def auto_popup(parent, title: str, message: str, ms: int = 1000):
    win = tk.Toplevel(parent)
    win.title(title)
    win.resizable(False, False)
    win.overrideredirect(True)
    parent.update_idletasks()
    px = parent.winfo_rootx() + parent.winfo_width()  // 2
    py = parent.winfo_rooty() + parent.winfo_height() // 2
    win.geometry(f"+{px - 170}+{py - 42}")
    fr = tk.Frame(win, bg="#1e8c45", padx=24, pady=14)
    fr.pack(fill="both", expand=True)
    tk.Label(fr, text=message, bg="#1e8c45", fg="#ffffff",
             font=("Consolas", 10, "bold")).pack()
    win.after(ms, win.destroy)

# *************** DEL 14 – COLOUR PALETTE ***************
C = {
    "bg":           "#0d1117",   # main background
    "panel":        "#161b22",   # panel background
    "border":       "#30363d",   # separator / border
    "accent":       "#238636",   # green  (add / apply)
    "accent2":      "#1f6feb",   # blue   (sync firewall)
    "accent3":      "#6e40c9",   # purple (sync hosts)
    "danger":       "#da3633",   # red    (remove / delete)
    "warn":         "#d29922",   # amber  (add & push)
    "text":         "#e6edf3",   # primary text
    "text_dim":     "#8b949e",   # dimmed / label text
    "input_bg":     "#0d1117",   # entry background
    "select_bg":    "#1f6feb",   # listbox selection
    "select_fg":    "#ffffff",
    "btn_grey":     "#21262d",   # neutral button  ← change to "red", "blue" etc.
    "btn_grey_fg":  "#e6edf3",
    "log_bg":       "#010409",   # log background
    "log_fg":       "#58a6ff",   # log text
    "tag_ok":       "#3fb950",
    "tag_fail":     "#f85149",
    "tag_info":     "#58a6ff",
    "tag_warn":     "#d29922",
    "type_ip":      "#58a6ff",   # IP type badge colour
    "type_dom":     "#a5d6ff",   # Domain type badge colour
}

# *************** DEL 15 – STYLED WIDGET FACTORIES ***************
def make_btn(parent, text, command, bg=None, fg=None, width=None, **kw):
    return tk.Button(
        parent, text=text, command=command,
        bg=bg or C["btn_grey"],
        fg=fg or C["btn_grey_fg"],
        activebackground=bg or C["btn_grey"],
        activeforeground=fg or C["btn_grey_fg"],
        relief="flat", cursor="hand2",
        font=("Consolas", 9, "bold"),
        pady=5, padx=8, width=width or 0,
        **kw,
    )

def make_entry(parent, textvariable=None, width=28, **kw):
    e = tk.Entry(
        parent, textvariable=textvariable, width=width,
        bg=C["input_bg"], fg=C["text"],
        insertbackground=C["text"],
        relief="flat",
        highlightthickness=1,
        highlightbackground=C["border"],
        highlightcolor=C["accent"],
        font=("Consolas", 10),
        insertofftime=0, insertontime=9999999,
        **kw,
    )
    no_blink(e)
    assert e.cget("insertofftime") == 0
    return e

def make_text(parent, wrap="word", **kw):
    t = tk.Text(
        parent,
        bg=C["log_bg"], fg=C["log_fg"],
        insertbackground=C["text"],
        relief="flat",
        highlightthickness=1,
        highlightbackground=C["border"],
        highlightcolor=C["accent"],
        font=("Consolas", 9),
        wrap=wrap,
        insertofftime=0, insertontime=9999999,
        **kw,
    )
    no_blink(t)
    assert t.cget("insertofftime") == 0
    return t

# *************** DEL 16 – EditorFrame (embeddable tk.Frame) ***************
# This is the full UI as a plain Frame so it can be:
#   - Embedded in a hub/notebook:  frame = EditorFrame(parent_notebook)
#   - Wrapped by IssusFirewall(tk.Tk) for standalone use
#   - Any other parent widget

class EditorFrame(tk.Frame):

    def __init__(self, parent, initial_blocklist: str = None):
        super().__init__(parent, bg=C["bg"])
        self.settings  = load_settings()
        self.blocklist = load_blocklist(initial_blocklist)
        self._apply_style()
        self._build_layout()
        self._refresh_list()
        self._on_type_change()
        self._check_admin()

    # ── DEL 16a  STYLE (no window title / geometry here) ──────────
    def _apply_style(self):
        style = ttk.Style(self)
        style.theme_use("clam")
        style.configure("Dark.TCombobox",
            fieldbackground=C["input_bg"], background=C["btn_grey"],
            foreground=C["text"], selectbackground=C["select_bg"],
            arrowcolor=C["text_dim"])
        style.map("Dark.TCombobox",
            fieldbackground=[("readonly", C["input_bg"])],
            foreground=[("readonly", C["text"])])

    # ── DEL 16b  MAIN LAYOUT ──────────────────────────────────────
    def _build_layout(self):
        self.pack(fill="both", expand=True)
        self.paned = tk.PanedWindow(self, orient="horizontal",
                                    bg=C["border"], sashwidth=4, sashrelief="flat")
        self.paned.pack(fill="both", expand=True)
        left  = tk.Frame(self.paned, bg=C["bg"])
        right = tk.Frame(self.paned, bg=C["bg"])
        sash  = self.settings.get("sash_pos", 370)
        self.paned.add(left,  minsize=300, width=sash)
        self.paned.add(right, minsize=280)
        self._build_left(left)
        self._build_right(right)

    # ── DEL 16c  LEFT PANEL ───────────────────────────────────────
    def _build_left(self, parent):
        hdr = tk.Frame(parent, bg=C["panel"], pady=6)
        hdr.pack(fill="x")
        tk.Label(hdr, text="  BLOCKLIST", bg=C["panel"], fg=C["text"],
                 font=("Consolas", 11, "bold")).pack(side="left")
        self._lbl_count = tk.Label(hdr, text="0 entries",
                                    bg=C["panel"], fg=C["text_dim"],
                                    font=("Consolas", 9))
        self._lbl_count.pack(side="right", padx=10)
        tk.Frame(parent, bg=C["border"], height=1).pack(fill="x")

        sf = tk.Frame(parent, bg=C["bg"], pady=4)
        sf.pack(fill="x", padx=8)
        tk.Label(sf, text="Filter:", bg=C["bg"], fg=C["text_dim"],
                 font=("Consolas", 9)).pack(side="left")
        self._var_search = tk.StringVar()
        self._var_search.trace_add("write", lambda *_: self._refresh_list())
        se = make_entry(sf, textvariable=self._var_search, width=22)
        se.pack(side="left", padx=(4, 10))
        self._var_filter_type = tk.StringVar(value="all")
        for val, label in [("all","All"), ("ip","IP"), ("domain","Domain")]:
            tk.Radiobutton(
                sf, text=label, variable=self._var_filter_type, value=val,
                command=self._refresh_list,
                bg=C["bg"], fg=C["text_dim"], selectcolor=C["panel"],
                activebackground=C["bg"], activeforeground=C["text"],
                font=("Consolas", 9),
            ).pack(side="left", padx=2)

        lb_fr = tk.Frame(parent, bg=C["bg"])
        lb_fr.pack(fill="both", expand=True, padx=8, pady=(2, 4))
        vs = tk.Scrollbar(lb_fr, orient="vertical",   bg=C["panel"], troughcolor=C["bg"])
        hs = tk.Scrollbar(lb_fr, orient="horizontal", bg=C["panel"], troughcolor=C["bg"])
        self._listbox = tk.Listbox(
            lb_fr,
            yscrollcommand=vs.set, xscrollcommand=hs.set,
            bg=C["panel"], fg=C["text"],
            selectbackground=C["select_bg"], selectforeground=C["select_fg"],
            activestyle="none",
            font=("Consolas", 10),
            relief="flat",
            highlightthickness=1, highlightbackground=C["border"],
        )
        vs.config(command=self._listbox.yview)
        hs.config(command=self._listbox.xview)
        self._listbox.grid(row=0, column=0, sticky="nsew")
        vs.grid(row=0, column=1, sticky="ns")
        hs.grid(row=1, column=0, sticky="ew")
        lb_fr.rowconfigure(0, weight=1)
        lb_fr.columnconfigure(0, weight=1)
        self._listbox.bind("<MouseWheel>",
            lambda e: self._listbox.yview_scroll(int(-1*(e.delta/120)), "units"))
        self._listbox.bind("<<ListboxSelect>>", self._on_select)
        self._listbox.bind("<Delete>",          lambda e: self._remove_selected())
        self._listbox.bind("<Double-Button-1>", lambda e: self._edit_selected())

        tk.Frame(parent, bg=C["border"], height=1).pack(fill="x", padx=8)
        form = tk.Frame(parent, bg=C["bg"], pady=6)
        form.pack(fill="x", padx=8)

        tk.Label(form, text="Block type:", bg=C["bg"], fg=C["text_dim"],
                 font=("Consolas", 9)).grid(row=0, column=0, sticky="w", pady=2)
        type_fr = tk.Frame(form, bg=C["bg"])
        type_fr.grid(row=0, column=1, columnspan=2, sticky="w", pady=2)
        self._var_block_type = tk.StringVar(
            value=self.settings.get("last_block_type", "ip"))
        for val, label, col in [
            ("ip",     "🛡 IP  →  Firewall",       C["type_ip"]),
            ("domain", "🌐 Domain  →  Hosts file", C["type_dom"]),
        ]:
            tk.Radiobutton(
                type_fr, text=label, variable=self._var_block_type, value=val,
                command=self._on_type_change,
                bg=C["bg"], fg=col, selectcolor=C["panel"],
                activebackground=C["bg"], activeforeground=col,
                font=("Consolas", 9, "bold"),
            ).pack(side="left", padx=(0, 14))

        self._lbl_value = tk.Label(form, text="IP / CIDR:", bg=C["bg"],
                                    fg=C["text_dim"], font=("Consolas", 9))
        self._lbl_value.grid(row=1, column=0, sticky="w", pady=2)
        self._var_value = tk.StringVar()
        self._entry_value = make_entry(form, textvariable=self._var_value, width=26)
        self._entry_value.grid(row=1, column=1, columnspan=2, sticky="w",
                                padx=(4, 0), pady=2)
        self._entry_value.bind("<Return>",
            lambda e: self._entry_redirect.focus_set()
            if self._var_block_type.get() == "domain"
            else self._entry_note.focus_set())
        # Pasting a LIST into the value field (or Ctrl+V on the list) opens Paste many.
        self._entry_value.bind("<<Paste>>", self._on_value_paste)
        self._listbox.bind("<Control-v>", lambda e: self._on_list_paste())

        self._lbl_redirect = tk.Label(form, text="Redirect IP:", bg=C["bg"],
                                       fg=C["text_dim"], font=("Consolas", 9))
        self._lbl_redirect.grid(row=2, column=0, sticky="w", pady=2)
        self._var_redirect = tk.StringVar(
            value=self.settings.get("last_redirect_ip", "127.0.0.1"))
        self._entry_redirect = make_entry(form, textvariable=self._var_redirect, width=18)
        self._entry_redirect.grid(row=2, column=1, sticky="w", padx=(4, 0), pady=2)
        self._entry_redirect.bind("<Return>", lambda e: self._entry_note.focus_set())
        tk.Label(form, text="(default: 127.0.0.1)", bg=C["bg"],
                 fg=C["text_dim"], font=("Consolas", 8)).grid(
                 row=2, column=2, sticky="w", padx=4)

        tk.Label(form, text="Note:", bg=C["bg"], fg=C["text_dim"],
                 font=("Consolas", 9)).grid(row=3, column=0, sticky="w", pady=2)
        self._var_note = tk.StringVar()
        self._entry_note = make_entry(form, textvariable=self._var_note, width=26)
        self._entry_note.grid(row=3, column=1, columnspan=2, sticky="w",
                               padx=(4, 0), pady=2)
        self._entry_note.bind("<Return>", lambda e: self._add_entry())

        self._opt_frame = tk.Frame(parent, bg=C["bg"])
        self._opt_frame.pack(fill="x", padx=8, pady=(0, 2))
        tk.Label(self._opt_frame, text="Direction:", bg=C["bg"], fg=C["text_dim"],
                 font=("Consolas", 9)).grid(row=0, column=0, sticky="w")
        self._var_dir = tk.StringVar(value=self.settings.get("last_direction", "both"))
        ttk.Combobox(self._opt_frame, textvariable=self._var_dir,
                     values=["both", "in", "out"],
                     state="readonly", width=7,
                     style="Dark.TCombobox").grid(row=0, column=1, padx=(4, 16), pady=2)
        tk.Label(self._opt_frame, text="Protocol:", bg=C["bg"], fg=C["text_dim"],
                 font=("Consolas", 9)).grid(row=0, column=2, sticky="w")
        self._var_proto = tk.StringVar(value=self.settings.get("last_protocol", "any"))
        ttk.Combobox(self._opt_frame, textvariable=self._var_proto,
                     values=["any", "tcp", "udp"],
                     state="readonly", width=6,
                     style="Dark.TCombobox").grid(row=0, column=3, padx=(4, 0), pady=2)

        tk.Frame(parent, bg=C["border"], height=1).pack(fill="x", padx=8)
        btn_fr = tk.Frame(parent, bg=C["bg"], pady=4)
        btn_fr.pack(fill="x", padx=8)

        make_btn(btn_fr, "＋ Add to list",
                 self._add_entry,
                 bg=C["accent"], fg="#ffffff",           # ← colour: green
                 width=14).grid(row=0, column=0, padx=(0, 4), pady=2)

        self._btn_push = make_btn(btn_fr, "⬆ Add & Push",
                 self._add_and_push,
                 bg=C["warn"], fg="#000000",              # ← colour: amber
                 width=14)
        self._btn_push.grid(row=0, column=1, padx=4, pady=2)

        make_btn(btn_fr, "✖ Remove selected",
                 self._remove_selected,
                 bg=C["danger"], fg="#ffffff",            # ← colour: red
                 width=16).grid(row=1, column=0, padx=(0, 4), pady=2)

        make_btn(btn_fr, "✎ Edit selected",
                 self._edit_selected,
                 bg=C["btn_grey"], fg=C["btn_grey_fg"],  # ← colour: grey
                 width=14).grid(row=1, column=1, padx=4, pady=2)

        make_btn(btn_fr, "📋 Paste many…  (a whole list at once)",
                 self._paste_many,
                 bg=C["accent2"], fg="#ffffff"           # ← colour: blue
                 ).grid(row=2, column=0, columnspan=2, padx=(0, 4), pady=2, sticky="ew")

        tk.Frame(parent, bg=C["border"], height=1).pack(fill="x", padx=8, pady=(4, 0))
        sync_fr = tk.Frame(parent, bg=C["bg"], pady=6)
        sync_fr.pack(fill="x", padx=8)
        make_btn(sync_fr, "⚡ Sync IPs → Firewall",
                 self._sync_fw_all,
                 bg=C["accent2"], fg="#ffffff"           # ← colour: blue
                 ).pack(side="left")
        make_btn(sync_fr, "🌐 Sync Domains → Hosts",
                 self._sync_hosts_all,
                 bg=C["accent3"], fg="#ffffff"           # ← colour: purple
                 ).pack(side="left", padx=(8, 0))
        make_btn(sync_fr, "🗑 Clear All",
                 self._remove_all_rules_and_hosts,
                 bg=C["danger"], fg="#ffffff"            # ← colour: red
                 ).pack(side="right")

        self._lbl_admin = tk.Label(parent, text="", bg=C["bg"],
                                    font=("Consolas", 9))
        self._lbl_admin.pack(anchor="w", padx=8, pady=(0, 4))

    # ── DEL 16d  RIGHT PANEL ──────────────────────────────────────
    def _build_right(self, parent):
        hdr = tk.Frame(parent, bg=C["panel"], pady=6)
        hdr.pack(fill="x")
        tk.Label(hdr, text="  ACTIVITY LOG", bg=C["panel"], fg=C["text"],
                 font=("Consolas", 11, "bold")).pack(side="left")
        make_btn(hdr, "Clear", self._clear_log,
                 bg=C["btn_grey"], fg=C["btn_grey_fg"]  # ← colour: grey
                 ).pack(side="right", padx=6)
        tk.Frame(parent, bg=C["border"], height=1).pack(fill="x")

        log_fr = tk.Frame(parent, bg=C["bg"])
        log_fr.pack(fill="both", expand=True, padx=6, pady=6)
        lv = tk.Scrollbar(log_fr, orient="vertical",   bg=C["panel"], troughcolor=C["bg"])
        lh = tk.Scrollbar(log_fr, orient="horizontal", bg=C["panel"], troughcolor=C["bg"])
        self._log_text = make_text(log_fr,
                                   yscrollcommand=lv.set, xscrollcommand=lh.set,
                                   state="disabled", height=10)
        lv.config(command=self._log_text.yview)
        lh.config(command=self._log_text.xview)
        self._log_text.grid(row=0, column=0, sticky="nsew")
        lv.grid(row=0, column=1, sticky="ns")
        lh.grid(row=1, column=0, sticky="ew")
        log_fr.rowconfigure(0, weight=1)
        log_fr.columnconfigure(0, weight=1)
        self._log_text.tag_config("OK",   foreground=C["tag_ok"])
        self._log_text.tag_config("FAIL", foreground=C["tag_fail"])
        self._log_text.tag_config("INFO", foreground=C["tag_info"])
        self._log_text.tag_config("WARN", foreground=C["tag_warn"])
        self._log_text.bind("<MouseWheel>",
            lambda e: self._log_text.yview_scroll(int(-1*(e.delta/120)), "units"))

        tk.Frame(parent, bg=C["border"], height=1).pack(fill="x", padx=6)
        prev_hdr = tk.Frame(parent, bg=C["panel"], pady=4)
        prev_hdr.pack(fill="x")
        tk.Label(prev_hdr, text="  HOSTS FILE  (Issu's section)",
                 bg=C["panel"], fg=C["text_dim"],
                 font=("Consolas", 9)).pack(side="left")
        make_btn(prev_hdr, "Refresh", self._refresh_hosts_preview,
                 bg=C["btn_grey"], fg=C["btn_grey_fg"]  # ← colour: grey
                 ).pack(side="right", padx=6)

        prev_fr = tk.Frame(parent, bg=C["bg"])
        prev_fr.pack(fill="x", padx=6, pady=(2, 6))
        pv = tk.Scrollbar(prev_fr, orient="vertical", bg=C["panel"], troughcolor=C["bg"])
        self._hosts_preview = make_text(prev_fr,
                                        yscrollcommand=pv.set,
                                        state="disabled", height=7, wrap="none")
        self._hosts_preview.tag_config("marker",   foreground=C["warn"])
        self._hosts_preview.tag_config("hostline", foreground=C["tag_ok"])
        pv.config(command=self._hosts_preview.yview)
        self._hosts_preview.pack(side="left", fill="both", expand=True)
        pv.pack(side="right", fill="y")
        self._hosts_preview.bind("<MouseWheel>",
            lambda e: self._hosts_preview.yview_scroll(int(-1*(e.delta/120)), "units"))

        tk.Frame(parent, bg=C["border"], height=1).pack(fill="x", padx=6)
        det = tk.Frame(parent, bg=C["bg"], pady=4)
        det.pack(fill="x", padx=6)
        tk.Label(det, text="Selected:", bg=C["bg"], fg=C["text_dim"],
                 font=("Consolas", 9)).pack(side="left")
        self._lbl_detail = tk.Label(det, text="–", bg=C["bg"], fg=C["text"],
                                     font=("Consolas", 9), anchor="w", wraplength=380)
        self._lbl_detail.pack(side="left", padx=6)

    # ── DEL 16e  ADMIN CHECK ──────────────────────────────────────
    def _check_admin(self):
        if is_admin():
            self._lbl_admin.config(text="● Running as Administrator", fg=C["tag_ok"])
            self._log("Started with Administrator privileges.", "INFO")
        else:
            self._lbl_admin.config(
                text="⚠ NOT Administrator – Firewall/Hosts changes will FAIL",
                fg=C["tag_fail"])
            self._log(
                "WARNING: Not running as Administrator. "
                "Firewall and hosts changes require admin rights.", "FAIL")
        self._refresh_hosts_preview()

    # ── DEL 16f  LOG HELPERS ──────────────────────────────────────
    def _log(self, msg: str, tag: str = "INFO"):
        ts = datetime.now().strftime("%H:%M:%S")
        self._log_text.config(state="normal")
        self._log_text.insert("end", f"[{ts}] {msg}\n", tag)
        self._log_text.see("end")
        self._log_text.config(state="disabled")
        log_info(msg)

    def _clear_log(self):
        self._log_text.config(state="normal")
        self._log_text.delete("1.0", "end")
        self._log_text.config(state="disabled")

    def _safe_log(self, msg: str, tag: str = "INFO"):
        self.after(0, lambda: self._log(msg, tag))

    # ── DEL 16g  HOSTS PREVIEW ────────────────────────────────────
    def _refresh_hosts_preview(self):
        self._hosts_preview.config(state="normal")
        self._hosts_preview.delete("1.0", "end")
        content = _read_hosts()
        inside  = False
        found   = False
        for line in content.splitlines():
            if HOSTS_MARKER + " BEGIN" in line:
                inside = True
                found  = True
            if inside:
                tag = "marker" if HOSTS_MARKER in line else "hostline"
                self._hosts_preview.insert("end", line + "\n", tag)
            if HOSTS_MARKER + " END" in line:
                inside = False
        if not found:
            self._hosts_preview.insert("end",
                "(No Issu's entries in hosts file yet.)\n", "INFO")
        self._hosts_preview.config(state="disabled")

    # ── DEL 16h  BLOCK-TYPE CHANGE ────────────────────────────────
    def _on_type_change(self):
        t = self._var_block_type.get()
        if t == "ip":
            self._lbl_value.config(text="IP / CIDR:")
            self._entry_redirect.config(state="disabled",
                                         disabledbackground=C["panel"],
                                         disabledforeground=C["text_dim"])
            self._lbl_redirect.config(fg=C["text_dim"])
            self._opt_frame.pack(fill="x", padx=8, pady=(0, 2))
            self._btn_push.config(text="⬆ Add & Push FW")
        else:
            self._lbl_value.config(text="Domain:")
            if not self._var_redirect.get().strip():
                self._var_redirect.set("127.0.0.1")
            self._entry_redirect.config(state="normal",
                                         disabledbackground=C["input_bg"],
                                         disabledforeground=C["text"])
            self._lbl_redirect.config(fg=C["text"])
            self._opt_frame.pack_forget()
            self._btn_push.config(text="⬆ Add & Push Hosts")

    # ── DEL 16i  LIST REFRESH ─────────────────────────────────────
    def _get_filtered_entries(self) -> list:
        search    = self._var_search.get().lower().strip() if hasattr(self, "_var_search") else ""
        type_filt = self._var_filter_type.get() if hasattr(self, "_var_filter_type") else "all"
        result    = []
        for e in self.blocklist:
            if type_filt != "all" and e.get("type", "ip") != type_filt:
                continue
            val  = e.get("value", e.get("ip", ""))
            note = e.get("note", "")
            if search and search not in val.lower() and search not in note.lower():
                continue
            result.append(e)
        return result

    def _refresh_list(self):
        self._listbox.delete(0, "end")
        filtered = self._get_filtered_entries()
        for entry in filtered:
            t     = entry.get("type", "ip")
            val   = entry.get("value", entry.get("ip", ""))
            note  = entry.get("note", "")
            redir = entry.get("redirect", "")
            if t == "domain":
                redir_part = f" → {redir}" if redir else " → 127.0.0.1"
                display = f"  [DOM]  {val:<34}{redir_part}  {note}"
            else:
                display = f"  [IP]   {val:<22}  {note}"
            self._listbox.insert("end", display)
        total = len(self.blocklist)
        shown = len(filtered)
        if hasattr(self, "_lbl_count"):
            q = self._var_search.get().strip() if hasattr(self, "_var_search") else ""
            self._lbl_count.config(
                text=f"{shown}/{total} entries" if q else f"{total} entries")

    def _on_select(self, _event=None):
        sel = self._listbox.curselection()
        if not sel:
            return
        filtered = self._get_filtered_entries()
        idx = sel[0]
        if idx >= len(filtered):
            return
        e   = filtered[idx]
        t   = e.get("type", "ip")
        val = e.get("value", e.get("ip", ""))
        self._lbl_detail.config(
            text=f"[{t.upper()}]  {val}   redirect: {e.get('redirect','–')}"
                 f"   note: {e.get('note','–')}   added: {e.get('added','–')}")

    # ── DEL 16j  BUILD ENTRY DICT ─────────────────────────────────
    def _build_entry_from_form(self) -> dict | None:
        t    = self._var_block_type.get()
        raw  = self._var_value.get().strip()
        note = self._var_note.get().strip()
        if not raw:
            messagebox.showwarning("Missing value",
                "Please enter an IP/CIDR or domain name.")
            return None
        if t == "ip":
            if not validate_ip(raw):
                messagebox.showerror("Invalid IP",
                    f"'{raw}' is not a valid IPv4 address or CIDR.\n"
                    "Examples:  192.168.1.1   10.0.0.0/8")
                return None
            return {"type": "ip", "value": raw, "redirect": "",
                    "note": note,
                    "added": datetime.now().strftime("%Y-%m-%d %H:%M")}
        else:
            domain = clean_domain(raw)
            if not validate_domain(domain):
                messagebox.showerror("Invalid domain",
                    f"'{domain}' doesn't look like a valid domain.\n"
                    "Examples:  useless.shit.com   ads.example.org")
                return None
            redirect = self._var_redirect.get().strip() or "127.0.0.1"
            if not validate_ip(redirect):
                messagebox.showerror("Invalid redirect IP",
                    f"'{redirect}' is not a valid IP address.")
                return None
            return {"type": "domain", "value": domain, "redirect": redirect,
                    "note": note,
                    "added": datetime.now().strftime("%Y-%m-%d %H:%M")}

    def _clear_form(self):
        self._var_value.set("")
        self._var_note.set("")
        self._entry_value.focus_set()

    def _is_duplicate(self, entry: dict) -> bool:
        for e in self.blocklist:
            if (e.get("type") == entry.get("type") and
                    e.get("value","").lower() == entry.get("value","").lower()):
                return True
        return False

    # ── DEL 16k  ADD ENTRY ────────────────────────────────────────
    def _add_entry(self):
        entry = self._build_entry_from_form()
        if not entry:
            return
        if self._is_duplicate(entry):
            messagebox.showinfo("Duplicate", f"{entry['value']} is already in the list.")
            return
        self.blocklist.append(entry)
        save_blocklist(self.blocklist)
        self._clear_form()
        self._refresh_list()
        self._log(f"Added [{entry['type'].upper()}]: {entry['value']}  ({entry['note']})", "OK")
        auto_popup(self, "Added", f"✓ {entry['value']} added")

    # ── DEL 16l  ADD & PUSH ───────────────────────────────────────
    def _add_and_push(self):
        entry = self._build_entry_from_form()
        if not entry:
            return
        if not self._is_duplicate(entry):
            self.blocklist.append(entry)
            save_blocklist(self.blocklist)
            self._refresh_list()
            self._log(f"Added [{entry['type'].upper()}]: {entry['value']}", "OK")

        if entry["type"] == "ip":
            direction = self._var_dir.get()
            protocol  = self._var_proto.get()
            self._log(f"Pushing FW rule: {entry['value']} dir={direction} proto={protocol}", "INFO")
            ok, msg = add_fw_rule(entry["value"], direction, protocol)
            self._log(f"{'Rule applied' if ok else 'Rule FAILED'}: {entry['value']}\n  {msg}",
                      "OK" if ok else "FAIL")
            if ok:
                auto_popup(self, "Firewall Rule Applied",
                           f"✓ {entry['value']} blocked in Windows Firewall")
            else:
                messagebox.showerror("Firewall Error",
                    f"Failed to add rule for {entry['value']}.\n\n{msg}\n\n"
                    "Run as Administrator.")
        else:
            self._log(f"Writing to hosts: {entry['value']} → {entry['redirect']}", "INFO")
            ok, msg = sync_hosts(self.blocklist)
            self._log(f"Hosts file {'updated' if ok else 'FAILED'}: {msg}",
                      "OK" if ok else "FAIL")
            if ok:
                flush_dns()
                self._refresh_hosts_preview()
                auto_popup(self, "Hosts File Updated",
                           f"✓ {entry['value']} → {entry['redirect']}")
            else:
                messagebox.showerror("Hosts File Error",
                    f"Failed to update hosts file.\n\n{msg}\n\nRun as Administrator.")
        self._clear_form()

    # ── DEL 16m  REMOVE SELECTED ──────────────────────────────────
    def _remove_selected(self):
        sel = self._listbox.curselection()
        if not sel:
            return
        filtered = self._get_filtered_entries()
        idx = sel[0]
        if idx >= len(filtered):
            return
        entry = filtered[idx]
        t     = entry.get("type", "ip")
        val   = entry.get("value", entry.get("ip", ""))
        if not messagebox.askyesno("Remove entry",
                f"Remove  [{t.upper()}]  {val}  from blocklist?\n\n"
                "(Also removes the Firewall rule / hosts entry.)"):
            return
        self.blocklist = [
            e for e in self.blocklist
            if not (e.get("type") == t and
                    e.get("value","").lower() == val.lower())
        ]
        save_blocklist(self.blocklist)
        self._refresh_list()
        self._log(f"Removed [{t.upper()}]: {val}", "INFO")
        if t == "ip":
            ok, msg = remove_fw_rule(val)
            self._log(f"FW rule removal ({val}): {msg}", "OK" if ok else "INFO")
        else:
            ok, msg = sync_hosts(self.blocklist)
            if ok:
                flush_dns()
                self._refresh_hosts_preview()
            self._log(f"Hosts re-synced: {msg}", "OK" if ok else "FAIL")

    # ── DEL 16n  EDIT SELECTED ────────────────────────────────────
    def _edit_selected(self):
        sel = self._listbox.curselection()
        if not sel:
            return
        filtered = self._get_filtered_entries()
        idx = sel[0]
        if idx >= len(filtered):
            return
        entry    = filtered[idx]
        t        = entry.get("type", "ip")
        real_idx = next(
            (i for i, e in enumerate(self.blocklist)
             if e.get("type") == t and
                e.get("value","").lower() == entry.get("value","").lower()),
            None)
        if real_idx is None:
            return

        win = tk.Toplevel(self)
        win.title(f"Edit [{t.upper()}] Entry")
        win.configure(bg=C["bg"])
        win.resizable(False, False)
        win.grab_set()
        win.focus_force()
        win.bind("<Escape>", lambda e: win.destroy())

        lbl = "IP / CIDR:" if t == "ip" else "Domain:"
        tk.Label(win, text=lbl, bg=C["bg"], fg=C["text"],
                 font=("Consolas", 9)).grid(row=0, column=0, padx=12, pady=6, sticky="w")
        var_val = tk.StringVar(value=entry.get("value", entry.get("ip","")))
        e_val   = make_entry(win, textvariable=var_val, width=26)
        e_val.grid(row=0, column=1, padx=(0,12), pady=6)

        tk.Label(win, text="Redirect IP:", bg=C["bg"], fg=C["text"],
                 font=("Consolas", 9)).grid(row=1, column=0, padx=12, pady=6, sticky="w")
        var_redir = tk.StringVar(value=entry.get("redirect","127.0.0.1"))
        e_redir   = make_entry(win, textvariable=var_redir, width=18)
        e_redir.grid(row=1, column=1, sticky="w", padx=(0,12), pady=6)
        if t == "ip":
            e_redir.config(state="disabled", disabledbackground=C["panel"])

        tk.Label(win, text="Note:", bg=C["bg"], fg=C["text"],
                 font=("Consolas", 9)).grid(row=2, column=0, padx=12, pady=6, sticky="w")
        var_note = tk.StringVar(value=entry.get("note",""))
        e_note   = make_entry(win, textvariable=var_note, width=26)
        e_note.grid(row=2, column=1, padx=(0,12), pady=6)

        def save_edit():
            new_val   = var_val.get().strip()
            new_note  = var_note.get().strip()
            new_redir = var_redir.get().strip() or "127.0.0.1"
            if t == "ip":
                if not validate_ip(new_val):
                    messagebox.showerror("Invalid IP", f"'{new_val}' is not valid.", parent=win)
                    return
            else:
                new_val = clean_domain(new_val)
                if not validate_domain(new_val):
                    messagebox.showerror("Invalid domain", f"'{new_val}' is not valid.", parent=win)
                    return
                if not validate_ip(new_redir):
                    messagebox.showerror("Invalid redirect IP", f"'{new_redir}' is not valid.", parent=win)
                    return
            self.blocklist[real_idx]["value"]    = new_val
            self.blocklist[real_idx]["note"]     = new_note
            self.blocklist[real_idx]["redirect"] = new_redir
            save_blocklist(self.blocklist)
            self._refresh_list()
            self._log(f"Edited [{t.upper()}]: {entry.get('value','')} → {new_val}", "INFO")
            win.destroy()
            auto_popup(self, "Saved", "✓ Entry updated")

        e_val.bind("<Return>",  lambda e: e_note.focus_set())
        e_note.bind("<Return>", lambda e: save_edit())

        bf = tk.Frame(win, bg=C["bg"])
        bf.grid(row=3, column=0, columnspan=2, pady=10)
        make_btn(bf, "Save", save_edit,
                 bg=C["accent"], fg="#ffffff").pack(side="left", padx=6)    # ← green
        make_btn(bf, "Cancel", win.destroy,
                 bg=C["btn_grey"], fg=C["btn_grey_fg"]).pack(side="left")   # ← grey
        e_val.focus_set()

    # ── DEL 16o  SYNC ALL IPs ─────────────────────────────────────
    def _sync_fw_all(self):
        ip_entries = [e for e in self.blocklist if e.get("type","ip") == "ip"]
        if not ip_entries:
            messagebox.showinfo("Nothing to sync", "No IP entries in the blocklist.")
            return
        direction = self._var_dir.get()
        protocol  = self._var_proto.get()
        n = len(ip_entries)
        if not messagebox.askyesno("Sync All IPs",
                f"Push {n} IP rule(s) to Windows Firewall?\n"
                f"Direction: {direction}   Protocol: {protocol}"):
            return
        self._log(f"Syncing {n} IP entries → Firewall (dir={direction}, proto={protocol})", "INFO")
        def _worker():
            ok_count = 0
            for i, entry in enumerate(ip_entries):
                ip = entry.get("value","")
                if not ip:
                    continue
                ok, msg = add_fw_rule(ip, direction, protocol)
                if ok:
                    ok_count += 1
                self._safe_log(f"[{i+1}/{n}] {ip} → {'OK' if ok else 'FAIL'}  {msg}",
                               "OK" if ok else "FAIL")
            self._safe_log(f"── IP sync complete: {ok_count}/{n} rules applied ──", "INFO")
        threading.Thread(target=_worker, daemon=True).start()

    # ── DEL 16p  SYNC ALL DOMAINS ─────────────────────────────────
    def _sync_hosts_all(self):
        dom_entries = [e for e in self.blocklist if e.get("type") == "domain"]
        if not dom_entries:
            messagebox.showinfo("Nothing to sync", "No domain entries in the blocklist.")
            return
        n = len(dom_entries)
        if not messagebox.askyesno("Sync All Domains",
                f"Write {n} domain(s) to the hosts file?\n"
                "(Current Issu's section will be replaced.)"):
            return
        self._log(f"Syncing {n} domain entries → hosts file", "INFO")
        def _worker():
            ok, msg = sync_hosts(self.blocklist)
            self._safe_log(f"Hosts file {'synced' if ok else 'FAILED'}: {msg}",
                           "OK" if ok else "FAIL")
            if ok:
                flush_dns()
                self._safe_log("DNS cache flushed.", "OK")
                self.after(0, self._refresh_hosts_preview)
        threading.Thread(target=_worker, daemon=True).start()

    def _sync_everything(self):
        self._sync_fw_all()
        self._sync_hosts_all()

    # ── DEL 16q  REMOVE ALL ───────────────────────────────────────
    def _remove_all_fw_rules(self):
        if not messagebox.askyesno("Remove All FW Rules",
                "Delete ALL IssusBlock rules from Windows Firewall?\n"
                "(JSON blocklist NOT changed.)"):
            return
        def _worker():
            for e in [x for x in self.blocklist if x.get("type","ip") == "ip"]:
                ip = e.get("value","")
                if ip:
                    ok, msg = remove_fw_rule(ip)
                    self._safe_log(f"Removed FW rule {ip}: {msg}", "OK" if ok else "FAIL")
            self._safe_log("── All firewall rules removed ──", "INFO")
        threading.Thread(target=_worker, daemon=True).start()

    def _remove_all_hosts(self):
        if not messagebox.askyesno("Remove Hosts Entries",
                "Remove ALL Issu's entries from the hosts file?\n"
                "(JSON blocklist NOT changed.)"):
            return
        ok, msg = remove_hosts_entries()
        self._log(f"Hosts entries removed: {msg}", "OK" if ok else "FAIL")
        if ok:
            flush_dns()
            self._refresh_hosts_preview()

    def _remove_all_rules_and_hosts(self):
        if not messagebox.askyesno("Clear Everything",
                "Remove ALL Issu's Firewall rules AND hosts entries?\n"
                "(JSON blocklist NOT changed.)"):
            return
        self._remove_all_fw_rules()
        ok, msg = remove_hosts_entries()
        self._log(f"Hosts cleared: {msg}", "OK" if ok else "FAIL")
        if ok:
            flush_dns()
            self._refresh_hosts_preview()

    # ── DEL 16r  IMPORT / EXPORT ──────────────────────────────────
    def _import_json(self):
        path = filedialog.askopenfilename(
            title="Import JSON blocklist",
            filetypes=[("JSON files", "*.json"), ("All files", "*.*")],
        )
        if not path:
            return
        try:
            with open(path, "r", encoding="utf-8") as f:
                data = json.load(f)
            if not isinstance(data, list):
                messagebox.showerror("Import Error",
                    "Expected a JSON array.\n"
                    'Each item: {"type":"ip"|"domain", "value":"...", ...}')
                return
            added    = 0
            skipped  = 0
            existing = {(e.get("type","ip"), e.get("value","").lower())
                        for e in self.blocklist}
            for item in data:
                if isinstance(item, str):
                    t = "ip" if validate_ip(item) else "domain"
                    item = {"type": t, "value": item,
                            "redirect": "127.0.0.1", "note": ""}
                t   = item.get("type", "ip")
                val = item.get("value", item.get("ip","")).strip()
                if not val:
                    skipped += 1; continue
                key = (t, val.lower())
                if key in existing:
                    skipped += 1; continue
                item.setdefault("redirect", "127.0.0.1")
                item.setdefault("note", "")
                item.setdefault("added", datetime.now().strftime("%Y-%m-%d %H:%M"))
                item["value"] = val
                self.blocklist.append(item)
                existing.add(key)
                added += 1
            save_blocklist(self.blocklist)
            self._refresh_list()
            self._log(f"Imported {added} entries. Skipped {skipped}.", "OK")
            auto_popup(self, "Import Complete", f"✓ {added} entries imported")
        except Exception as e:
            messagebox.showerror("Import Error", str(e))
            log_error(f"import_json: {e}")

    def _export_json(self):
        path = filedialog.asksaveasfilename(
            title="Export JSON blocklist",
            defaultextension=".json",
            filetypes=[("JSON files", "*.json"), ("All files", "*.*")],
            initialfile="blocklist_export.json",
        )
        if not path:
            return
        try:
            with open(path, "w", encoding="utf-8") as f:
                json.dump(self.blocklist, f, indent=2)
            self._log(f"Exported {len(self.blocklist)} entries → {path}", "OK")
            auto_popup(self, "Export Complete",
                       f"✓ {len(self.blocklist)} entries exported")
        except Exception as e:
            messagebox.showerror("Export Error", str(e))

    # ── DEL 16s  ABOUT ────────────────────────────────────────────
    def _show_about(self):
        """Stylish About dialog with documentation link and donation info."""
        import webbrowser

        top = tk.Toplevel(self)
        top.title("About – Firewall Manager")
        top.configure(bg=C["panel"])
        top.resizable(False, False)
        top.transient(self.winfo_toplevel())
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())

        # ── Header ──────────────────────────────────────────────────
        hdr = tk.Frame(top, bg=C["panel"])
        hdr.pack(fill="x")
        tk.Label(hdr, text="🛡", bg=C["panel"], fg=C["accent2"],
                 font=("Segoe UI", 36)).pack(pady=(18, 0))
        tk.Label(hdr, text="Firewall Manager",
                 bg=C["panel"], fg=C["accent2"],
                 font=("Segoe UI", 18, "bold")).pack()
        tk.Label(hdr, text="IP & Domain Blocker for Windows",
                 bg=C["panel"], fg=C["text_dim"],
                 font=("Segoe UI", 9, "italic")).pack(pady=(2, 10))
        tk.Frame(top, bg=C["border"], height=1).pack(fill="x", padx=20)

        # ── Author ───────────────────────────────────────────────────
        tk.Label(top, text='Created by  Lars "Issu" Olsson',
                 bg=C["panel"], fg=C["text"],
                 font=("Segoe UI", 10, "bold")).pack(pady=(14, 0))

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

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

        # ── Donation section ─────────────────────────────────────────
        tk.Label(top, text="☕  If you enjoy this tool, a small gift is always welcome!",
                 bg=C["panel"], fg=C["text_dim"],
                 font=("Segoe UI", 8, "italic"),
                 wraplength=300, justify="center").pack(pady=(10, 6))

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

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

        def _donate_btn(parent, label, color, url):
            btn = tk.Label(parent, text=label,
                           bg=color, fg="#ffffff",
                           font=("Segoe UI", 9, "bold"),
                           padx=10, pady=5, cursor="hand2",
                           relief="flat")
            btn.pack(side="left", expand=True, fill="x", padx=4)
            btn.bind("<Button-1>", lambda e: open_url(url))
            darker = {
                "#1e4d8c": "#163a6b",
                "#003087": "#002266",
                "#37517e": "#2a3d60",
            }
            btn.bind("<Enter>", lambda e, b=btn, d=darker.get(color, color): b.configure(bg=d))
            btn.bind("<Leave>", lambda e, b=btn, c=color: b.configure(bg=c))

        _donate_btn(donate_frame, "💳  Revolut", "#1e4d8c", REVOLUT_URL)
        _donate_btn(donate_frame, "🅿  PayPal",  "#003087", PAYPAL_URL)
        _donate_btn(donate_frame, "🌐  Wise",    "#37517e", WISE_URL)

        tk.Frame(top, bg=C["border"], height=1).pack(fill="x", padx=20, pady=(6, 0))

        # ── Paths info ───────────────────────────────────────────────
        paths_text = (
            f"Blocklist:  {BLOCKLIST_FILE}\n"
            f"Hosts bak:  {HOSTS_BACKUP}\n"
            f"Logs:       {LOG_DIR}"
        )
        tk.Label(top, text=paths_text,
                 bg=C["panel"], fg=C["text_dim"],
                 font=("Consolas", 7),
                 justify="left").pack(padx=20, pady=(8, 2), anchor="w")

        tk.Frame(top, bg=C["border"], height=1).pack(fill="x", padx=20, pady=(6, 0))

        # ── Close button ─────────────────────────────────────────────
        make_btn(top, "Close", top.destroy,
                 bg=C["btn_grey"], fg=C["btn_grey_fg"]).pack(pady=12)

    # ── DEL 16u  HELP DIALOG ──────────────────────────────────────
    def _show_help(self):
        """Scrollable Help dialog explaining every feature of the application."""
        top = tk.Toplevel(self)
        top.title("Help – Firewall Manager")
        top.configure(bg=C["panel"])
        top.resizable(True, True)
        top.transient(self.winfo_toplevel())
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())
        top.geometry("640x620")
        top.minsize(480, 400)

        # ── Header ──────────────────────────────────────────────────
        hdr = tk.Frame(top, bg=C["panel"])
        hdr.pack(fill="x", padx=20, pady=(16, 4))
        tk.Label(hdr, text="❓  How to use Firewall Manager",
                 bg=C["panel"], fg=C["accent2"],
                 font=("Segoe UI", 13, "bold")).pack(anchor="w")
        tk.Frame(top, bg=C["border"], height=1).pack(fill="x", padx=20, pady=(0, 6))

        # ── Scrollable text area ─────────────────────────────────────
        frame = tk.Frame(top, bg=C["panel"])
        frame.pack(fill="both", expand=True, padx=12, pady=(0, 4))

        sb = tk.Scrollbar(frame, orient="vertical", bg=C["bg"],
                          troughcolor=C["bg"], relief="flat")
        sb.pack(side="right", fill="y")

        txt = tk.Text(frame, wrap="word",
                      bg=C["bg"], fg=C["text"],
                      font=("Segoe UI", 9),
                      relief="flat",
                      padx=14, pady=10,
                      spacing1=2, spacing3=4,
                      insertofftime=0, insertontime=9999999,
                      state="normal",
                      yscrollcommand=sb.set,
                      highlightthickness=0)
        txt.pack(side="left", fill="both", expand=True)
        sb.config(command=txt.yview)

        # ── Tag styles ───────────────────────────────────────────────
        txt.tag_config("h1",   font=("Segoe UI", 11, "bold"),  foreground=C["accent2"])
        txt.tag_config("h2",   font=("Segoe UI", 9,  "bold"),  foreground=C["warn"])
        txt.tag_config("body", font=("Segoe UI", 9),           foreground=C["text"])
        txt.tag_config("dim",  font=("Segoe UI", 8,  "italic"),foreground=C["text_dim"])
        txt.tag_config("key",  font=("Consolas", 9,  "bold"),  foreground=C["accent"])
        txt.tag_config("sep",  font=("Segoe UI", 4),           foreground=C["border"])

        def h1(t):  txt.insert("end", t + "\n",   "h1")
        def h2(t):  txt.insert("end", t + "\n",   "h2")
        def body(t):txt.insert("end", t + "\n",   "body")
        def dim(t): txt.insert("end", t + "\n",   "dim")
        def sep():  txt.insert("end", "─" * 72 + "\n", "sep")
        def nl():   txt.insert("end", "\n")

        # ════════════════════════════════════════════════════════════
        h1("Overview")
        sep()
        body(
            "Firewall Manager lets you block IP addresses and domain names "
            "directly from Windows, without touching any third-party software.\n"
        )
        body("Two blocking methods are available:")
        body("  🛡  IP / CIDR block  →  adds a rule to the Windows Firewall via netsh.")
        body("  🌐  Domain block     →  redirects the domain in the Windows hosts file.")
        nl()
        dim("Administrator privileges are required for both methods.")
        nl()

        # ────────────────────────────────────────────────────────────
        h1("Adding a Block")
        sep()
        h2("1.  Choose the block type")
        body(
            "Use the 'Block type' radio buttons to select whether you are blocking "
            "an IP address (or CIDR range such as 192.168.1.0/24) or a domain name "
            "(such as example.com)."
        )
        nl()
        h2("2.  Enter the value")
        body(
            "Type or paste the IP, CIDR, or domain into the input field. "
            "You can paste a full URL – the app will strip the protocol and path "
            "automatically (e.g. https://example.com/page → example.com)."
        )
        nl()
        h2("3.  IP options (Direction & Protocol)")
        body(
            "These only apply when blocking an IP or CIDR range.\n"
            "  • Direction  –  'In' blocks incoming traffic, 'Out' blocks outgoing "
            "traffic, 'Both' (default) blocks in both directions.\n"
            "  • Protocol   –  restrict the rule to TCP, UDP, or leave it as 'Any'."
        )
        nl()
        h2("4.  Domain options (Redirect IP)")
        body(
            "When blocking a domain the hosts file maps the domain to an IP address "
            "of your choice. The default is 127.0.0.1 (localhost), which effectively "
            "makes the domain unreachable. You can change this to any valid IP."
        )
        dim(
            "Tip: the app automatically also blocks the 'www.' variant of every "
            "domain you add (e.g. blocking example.com also blocks www.example.com)."
        )
        nl()
        h2("5.  Optional note")
        body(
            "Fill in the 'Note' field with a short description so you remember "
            "why a particular entry was added."
        )
        nl()
        h2("6.  Add buttons")
        body(
            "  • Add to list        –  saves the entry to the blocklist only. "
            "No firewall or hosts change is made yet.\n"
            "  • Add & Push Now     –  saves the entry AND immediately applies it "
            "(adds the firewall rule or writes to the hosts file)."
        )
        nl()
        h2("7.  Paste many  (a whole list at once)")
        body(
            "Click '📋 Paste many…' (or File > Paste many…), or simply paste a list "
            "of two or more lines into the value field - the window opens by itself. "
            "Paste anything: IPs, CIDR ranges, domains, full URLs, even hosts-file "
            "lines such as '0.0.0.0 ads.example.com', one or several per line "
            "(separated by space, comma or semicolon). Ordinary words are ignored.\n"
            "  • The program sorts every item itself: IP / CIDR → Firewall, "
            "domain → hosts file. URLs are cut down to the domain.\n"
            "  • The lower box shows what will happen, live: [IP], [DOM], [DUP] "
            "(already in the list) and [BAD] (looks like an address but is not valid).\n"
            "  • Text after '#' on a line becomes that entry's note; 'Note for all' "
            "fills in the rest.\n"
            "  • Add all to list = save only.  Add all & Push = save AND apply "
            "everything (one hosts-file write, one rule per IP). Direction and "
            "Protocol are taken from the main window."
        )
        nl()

        # ────────────────────────────────────────────────────────────
        h1("Managing the Blocklist")
        sep()
        body(
            "The left panel shows all blocked entries. Each row displays the type "
            "(IP or Domain), the value, the redirect IP (domains only), and an "
            "optional note."
        )
        nl()
        h2("Filtering the list")
        body(
            "Above the list is a Filter bar.\n"
            "  • Type in the text box to search by value or note in real time.\n"
            "  • Use the All / IP / Domain radio buttons to show only entries "
            "of a specific type.\n"
            "  • The entry count in the header updates to reflect the current filter."
        )
        nl()
        h2("Selecting entries")
        body(
            "Click any entry to select it (single selection). "
            "The detail bar at the bottom of the right panel shows the full "
            "type, value, redirect, note, and date for the selected entry."
        )
        nl()
        h2("Keyboard shortcuts")
        body(
            "  • Delete key    –  removes the selected entry "
            "(same as '✖ Remove selected').\n"
            "  • Double-click  –  opens the Edit dialog for the selected entry."
        )
        nl()
        h2("✎ Edit selected")
        body(
            "Opens a small dialog where you can change the value, redirect IP, "
            "and note of an entry without removing and re-adding it. "
            "The blocklist is saved automatically after editing."
        )
        nl()
        h2("Remove selected")
        body(
            "Removes the selected entry from the blocklist AND deletes its "
            "corresponding firewall rule or hosts file entry immediately."
        )
        nl()
        h2("Quick sync buttons  (left panel)")
        body(
            "Three buttons at the bottom of the left panel give fast access "
            "to the most common sync operations:\n"
            "  • ⚡ Sync IPs → Firewall  –  re-applies all IP rules to Windows Firewall.\n"
            "  • 🌐 Sync Domains → Hosts –  rewrites the hosts file with all domain entries.\n"
            "  • 🗑 Clear All            –  removes all Issu's firewall rules AND "
            "hosts entries at once (the JSON blocklist file is NOT changed)."
        )
        nl()

        # ────────────────────────────────────────────────────────────
        h1("Right Panel")
        sep()
        h2("Activity Log")
        body(
            "The upper area of the right panel is a live activity log. "
            "Every add, remove, sync, and error event is written here with a "
            "timestamp and colour-coded tag:\n"
            "  • Green  (OK)   –  operation succeeded.\n"
            "  • Red    (FAIL) –  operation failed (check admin rights).\n"
            "  • Blue   (INFO) –  informational message.\n"
            "  • Amber  (WARN) –  warning.\n"
            "Click 'Clear' to wipe the on-screen log (the log file is not affected)."
        )
        nl()
        h2("Hosts File Preview")
        body(
            "The lower area shows the current Issu's section of the Windows "
            "hosts file (C:\\Windows\\System32\\drivers\\etc\\hosts). "
            "It is refreshed automatically after every hosts write. "
            "Click 'Refresh' to reload it manually at any time."
        )
        nl()

        # ────────────────────────────────────────────────────────────
        h1("Sync Functions  (Firewall / Hosts menu)")
        sep()
        body(
            "Use these when the blocklist is out of sync with the actual system "
            "state – for example after a reboot or after manually editing rules."
        )
        nl()
        body(
            "  • Sync all IPs → Windows Firewall  –  re-applies every IP/CIDR "
            "rule in the blocklist to the Windows Firewall.\n"
            "  • Sync all Domains → Hosts file    –  rewrites the Issu's section "
            "of the hosts file with all domain entries from the blocklist.\n"
            "  • Sync EVERYTHING                  –  runs both syncs above at once.\n"
            "  • Remove ALL Issu's Firewall rules  –  deletes every IssusBlock* "
            "rule from the Windows Firewall (does not touch the blocklist file).\n"
            "  • Remove ALL Issu's Hosts entries   –  strips the Issu's section "
            "from the hosts file entirely (does not touch the blocklist file)."
        )
        nl()

        # ────────────────────────────────────────────────────────────
        h1("Import & Export  (File menu)")
        sep()
        body(
            "  • Import JSON blocklist  –  merges entries from an external JSON "
            "file into the current blocklist. Duplicates are skipped automatically.\n"
            "  • Export JSON blocklist  –  saves the current blocklist to a JSON "
            "file of your choice. Useful for backups or sharing between machines."
        )
        dim(
            "Format: a JSON array of objects with the fields "
            '"type", "value", "redirect", "note", "added".'
        )
        nl()

        # ────────────────────────────────────────────────────────────
        h1("Log & Diagnostics  (Help menu)")
        sep()
        body(
            "  • Open log file          –  shows the running activity log "
            "(every add, remove, and sync operation).\n"
            "  • Open crash log         –  shows the crash log if an unexpected "
            "error has occurred.\n"
            "  • Open hosts backup      –  opens the automatic backup of the hosts "
            "file that is created before every write.\n"
            "  • Open hosts file        –  opens the live Windows hosts file.\n"
            "  • Open Helpfiles folder  –  opens the folder that contains all "
            "settings, logs, and backup files."
        )
        nl()

        # ────────────────────────────────────────────────────────────
        h1("File Locations")
        sep()
        body(f"  Blocklist  :  {BLOCKLIST_FILE}")
        body(f"  Settings   :  {SETTINGS_FILE}")
        body(f"  Log        :  {LOG_FILE}")
        body(f"  Crash log  :  {CRASH_FILE}")
        body(f"  Hosts bak  :  {HOSTS_BACKUP}")
        body(f"  Base dir   :  {BASE_DIR}")
        nl()
        dim(
            "All paths are resolved relative to the location of the script / .exe, "
            "so the app remains fully portable."
        )
        nl()

        txt.config(state="disabled")

        # ── Close button ─────────────────────────────────────────────
        tk.Frame(top, bg=C["border"], height=1).pack(fill="x", padx=20)
        make_btn(top, "Close", top.destroy,
                 bg=C["btn_grey"], fg=C["btn_grey_fg"]).pack(pady=10)

    # ── DEL 16u  PASTE MANY ───────────────────────────────────────
    def _clipboard_text(self) -> str:
        try:
            return self.clipboard_get()
        except tk.TclError:
            return ""

    def _on_value_paste(self, _event=None):
        """Ctrl+V in the value field: one value pastes normally, a LIST opens Paste many."""
        clip = self._clipboard_text()
        lines = [l for l in clip.splitlines() if l.strip()]
        if len(lines) >= 2 or len(parse_paste(clip)) >= 2:
            self._paste_many(clip)
            return "break"
        return None

    def _on_list_paste(self):
        clip = self._clipboard_text()
        if clip.strip():
            self._paste_many(clip)

    def _existing_keys(self) -> set:
        return {(e.get("type", "ip"), e.get("value", e.get("ip", "")).lower())
                for e in self.blocklist}

    def _paste_many(self, initial_text=""):
        """Modal dialog: paste a list, see it sorted live, add (and optionally push) it all."""
        if not isinstance(initial_text, str):
            initial_text = ""
        redirect = self._var_redirect.get().strip()
        if not validate_ip(redirect) or "/" in redirect:
            redirect = "127.0.0.1"
        existing = self._existing_keys()

        win = tk.Toplevel(self)
        win.title("Paste many")
        win.configure(bg=C["bg"])
        win.transient(self.winfo_toplevel())
        win.geometry("780x600")
        win.minsize(600, 460)
        win.grab_set()
        win.focus_force()
        win.bind("<Escape>", lambda e: win.destroy())
        win.columnconfigure(0, weight=1)
        win.rowconfigure(2, weight=3)
        win.rowconfigure(4, weight=2)

        tk.Label(win, bg=C["bg"], fg=C["text_dim"], font=("Consolas", 9),
                 justify="left", anchor="w", wraplength=740, height=4,
                 text="Paste your list below - IPs, CIDR ranges, domains, full URLs or "
                      "hosts-file lines (0.0.0.0 domain). One or several per line, "
                      "separated by space, comma or semicolon. Everything is sorted "
                      "automatically: IP/CIDR -> Firewall, domain -> hosts file. "
                      "'#' starts a note. Duplicates and rubbish are skipped."
                 ).grid(row=0, column=0, sticky="ew", padx=12, pady=(10, 4))
        tk.Label(win, text="PASTE HERE", bg=C["bg"], fg=C["warn"],
                 font=("Consolas", 9, "bold")).grid(row=1, column=0, sticky="w", padx=12)

        in_fr = tk.Frame(win, bg=C["bg"])
        in_fr.grid(row=2, column=0, sticky="nsew", padx=12, pady=(2, 6))
        in_fr.rowconfigure(0, weight=1)
        in_fr.columnconfigure(0, weight=1)
        sb_in = tk.Scrollbar(in_fr, orient="vertical", bg=C["panel"], troughcolor=C["bg"])
        txt_in = make_text(in_fr, wrap="none", yscrollcommand=sb_in.set)
        txt_in.config(fg=C["text"], bg=C["input_bg"])
        sb_in.config(command=txt_in.yview)
        txt_in.grid(row=0, column=0, sticky="nsew")
        sb_in.grid(row=0, column=1, sticky="ns")

        tk.Label(win, text="WHAT WILL HAPPEN", bg=C["bg"], fg=C["warn"],
                 font=("Consolas", 9, "bold")).grid(row=3, column=0, sticky="w", padx=12)
        pv_fr = tk.Frame(win, bg=C["bg"])
        pv_fr.grid(row=4, column=0, sticky="nsew", padx=12, pady=(2, 6))
        pv_fr.rowconfigure(0, weight=1)
        pv_fr.columnconfigure(0, weight=1)
        sb_pv = tk.Scrollbar(pv_fr, orient="vertical", bg=C["panel"], troughcolor=C["bg"])
        txt_pv = make_text(pv_fr, wrap="none", yscrollcommand=sb_pv.set, state="disabled")
        sb_pv.config(command=txt_pv.yview)
        txt_pv.grid(row=0, column=0, sticky="nsew")
        sb_pv.grid(row=0, column=1, sticky="ns")
        txt_pv.tag_config("ip",  foreground=C["type_ip"])
        txt_pv.tag_config("dom", foreground=C["type_dom"])
        txt_pv.tag_config("dup", foreground=C["text_dim"])
        txt_pv.tag_config("bad", foreground=C["tag_fail"])

        opt = tk.Frame(win, bg=C["bg"])
        opt.grid(row=5, column=0, sticky="ew", padx=12, pady=(0, 4))
        tk.Label(opt, text="Note for all:", bg=C["bg"], fg=C["text_dim"],
                 font=("Consolas", 9)).grid(row=0, column=0, sticky="w")
        var_note = tk.StringVar()
        make_entry(opt, textvariable=var_note, width=40).grid(row=0, column=1, padx=(6, 0))
        tk.Label(opt, text=f"Domains are redirected to {redirect}  "
                           f"(hosts-file lines keep their own address)",
                 bg=C["bg"], fg=C["text_dim"], font=("Consolas", 8)
                 ).grid(row=1, column=0, columnspan=2, sticky="w", pady=(2, 0))

        lbl_sum = tk.Label(win, text="", bg=C["bg"], fg=C["text"], anchor="w",
                           font=("Consolas", 10, "bold"), width=80)
        lbl_sum.grid(row=6, column=0, sticky="w", padx=12, pady=(2, 4))

        btn_fr = tk.Frame(win, bg=C["bg"])
        btn_fr.grid(row=7, column=0, pady=(0, 10))
        state = {"rows": []}
        MAX_PREVIEW = 1500

        def refresh(*_):
            rows = parse_paste(txt_in.get("1.0", "end-1c"), redirect,
                               var_note.get().strip(), existing)
            state["rows"] = rows
            txt_pv.config(state="normal")
            txt_pv.delete("1.0", "end")
            for r in rows[:MAX_PREVIEW]:
                note = f"   # {r['note']}" if r["note"] else ""
                if r["status"] == "bad":
                    txt_pv.insert("end", f"  [BAD]  line {r['line']}: {r['raw']}  "
                                         f"- {r['why']}\n", "bad")
                elif r["status"] == "dup":
                    txt_pv.insert("end", f"  [DUP]  {r['value']}  - already in the "
                                         f"list\n", "dup")
                elif r["type"] == "ip":
                    txt_pv.insert("end", f"  [IP]   {r['value']:<24}{note}\n", "ip")
                else:
                    txt_pv.insert("end", f"  [DOM]  {r['value']:<34}-> "
                                         f"{r['redirect']}{note}\n", "dom")
            if len(rows) > MAX_PREVIEW:
                txt_pv.insert("end", f"  ... and {len(rows) - MAX_PREVIEW} more\n", "dup")
            txt_pv.config(state="disabled")
            n_ip  = sum(1 for r in rows if r["status"] == "new" and r["type"] == "ip")
            n_dom = sum(1 for r in rows if r["status"] == "new" and r["type"] == "domain")
            n_dup = sum(1 for r in rows if r["status"] == "dup")
            n_bad = sum(1 for r in rows if r["status"] == "bad")
            lbl_sum.config(
                text=f"{n_ip} IP  ·  {n_dom} domain  ·  {n_dup} duplicate  ·  {n_bad} not recognised",
                fg=C["tag_ok"] if (n_ip + n_dom) else C["text_dim"])
            st = "normal" if (n_ip + n_dom) else "disabled"
            btn_add.config(state=st)
            btn_push.config(state=st)

        def on_modified(_e=None):
            if not txt_in.edit_modified():
                return
            txt_in.edit_modified(False)
            refresh()

        def do_add(push):
            new = [r for r in state["rows"] if r["status"] == "new"]
            if not new:
                return
            if push and not is_admin():
                if not messagebox.askyesno(
                        "Not Administrator",
                        "Firewall and hosts changes need Administrator rights, "
                        "so pushing would fail.\n\nAdd everything to the list only?",
                        parent=win):
                    return
                push = False
            win.destroy()
            self._add_many(new, push)

        btn_add = make_btn(btn_fr, "+ Add all to list", lambda: do_add(False),
                           bg=C["accent"], fg="#ffffff", width=20)
        btn_add.pack(side="left", padx=6)
        btn_push = make_btn(btn_fr, "⬆ Add all & Push", lambda: do_add(True),
                            bg=C["warn"], fg="#000000", width=20)
        btn_push.pack(side="left", padx=6)
        make_btn(btn_fr, "Cancel", win.destroy,
                 bg=C["btn_grey"], fg=C["btn_grey_fg"], width=10).pack(side="left", padx=6)

        txt_in.bind("<<Modified>>", on_modified)
        txt_in.bind("<Control-a>", lambda e: (txt_in.tag_add("sel", "1.0", "end-1c"), "break")[1])
        var_note.trace_add("write", refresh)
        if initial_text:
            txt_in.insert("1.0", initial_text)
        refresh()
        txt_in.focus_set()

    def _add_many(self, rows: list, push: bool):
        """Add the 'new' rows from Paste many; if push, apply them to Windows too."""
        now = datetime.now().strftime("%Y-%m-%d %H:%M")
        added = []
        for r in rows:
            entry = {"type": r["type"], "value": r["value"],
                     "redirect": r["redirect"] if r["type"] == "domain" else "",
                     "note": r["note"], "added": now}
            if self._is_duplicate(entry):
                continue
            self.blocklist.append(entry)
            added.append(entry)
        save_blocklist(self.blocklist)
        self._refresh_list()
        ips = [e["value"] for e in added if e["type"] == "ip"]
        n_dom = len(added) - len(ips)
        self._log(f"Paste many: added {len(ips)} IP and {n_dom} domain entries.", "OK")
        if not added:
            return
        if not push:
            auto_popup(self, "Added", f"✓ {len(added)} entries added")
            return

        direction = self._var_dir.get()
        protocol  = self._var_proto.get()
        snapshot  = list(self.blocklist)
        self._log(f"Pushing {len(ips)} firewall rule(s) and {n_dom} domain(s)...", "INFO")

        def _worker():
            fw_ok = 0
            for i, ip in enumerate(ips, 1):
                ok, msg = add_fw_rule(ip, direction, protocol)
                fw_ok += 1 if ok else 0
                self._safe_log(f"[{i}/{len(ips)}] {ip} → {'OK' if ok else 'FAIL  ' + msg}",
                               "OK" if ok else "FAIL")
            hosts_ok = True
            if n_dom:
                hosts_ok, msg = sync_hosts(snapshot)
                self._safe_log(f"Hosts file {'updated' if hosts_ok else 'FAILED'}: {msg}",
                               "OK" if hosts_ok else "FAIL")
                if hosts_ok:
                    flush_dns()
                self.after(0, self._refresh_hosts_preview)
            failed = (len(ips) - fw_ok) + (0 if hosts_ok else n_dom)
            self._safe_log(f"── Paste many push done: {fw_ok}/{len(ips)} rules, "
                           f"{n_dom if hosts_ok else 0}/{n_dom} domains ──", "INFO")
            if failed:
                self.after(0, lambda: messagebox.showwarning(
                    "Some pushes failed",
                    f"{failed} entr{'y' if failed == 1 else 'ies'} could not be applied.\n"
                    "See the activity log (right panel). Run as Administrator."))
            else:
                self.after(0, lambda: auto_popup(
                    self, "Pushed", f"✓ {len(ips) + n_dom} entries applied"))
        threading.Thread(target=_worker, daemon=True).start()

    # ── DEL 16t  SAVE STATE (called by hub or IssusFirewall) ──────
    def save_state(self, geometry: str = None):
        """Persist settings. Pass window geometry string if available."""
        if geometry:
            self.settings["geometry"] = geometry
        self.settings["last_direction"]   = self._var_dir.get()
        self.settings["last_protocol"]    = self._var_proto.get()
        self.settings["last_block_type"]  = self._var_block_type.get()
        self.settings["last_redirect_ip"] = self._var_redirect.get()
        try:
            self.settings["sash_pos"] = self.paned.sash_coord(0)[0]
        except Exception:
            pass
        save_settings(self.settings)
        log_info("Settings saved.")


# *************** DEL 17 – IssusFirewall (standalone Tk window) ***************
class IssusFirewall(tk.Tk):
    """
    Thin wrapper around EditorFrame for standalone use.
    Adds window title, menu bar, and geometry management.
    """

    def __init__(self, initial_blocklist: str = None):
        super().__init__()
        self.title("Firewall Manager  –  IP & Domain Blocker")
        self.configure(bg=C["bg"])
        self.protocol("WM_DELETE_WINDOW", self._on_close)
        self._frame = EditorFrame(self, initial_blocklist=initial_blocklist)
        self._frame.pack(fill="both", expand=True)
        self._build_menu()
        try:
            self.geometry(self._frame.settings.get("geometry", "1020x720"))
        except Exception:
            self.geometry("1020x720")

    def _build_menu(self):
        f = self._frame   # shorthand
        bar = tk.Menu(self, bg=C["panel"], fg=C["text"],
                      activebackground=C["select_bg"],
                      activeforeground=C["select_fg"],
                      relief="flat", tearoff=False)
        self.config(menu=bar)

        fm = tk.Menu(bar, tearoff=False, bg=C["panel"], fg=C["text"],
                     activebackground=C["select_bg"])
        fm.add_command(label="Paste many…  (a whole list at once)", command=f._paste_many)
        fm.add_separator()
        fm.add_command(label="Import JSON blocklist…", command=f._import_json)
        fm.add_command(label="Export JSON blocklist…", command=f._export_json)
        fm.add_separator()
        fm.add_command(label="Exit", command=self._on_close)
        bar.add_cascade(label="File", menu=fm)

        fwm = tk.Menu(bar, tearoff=False, bg=C["panel"], fg=C["text"],
                      activebackground=C["select_bg"])
        fwm.add_command(label="Sync all IPs → Windows Firewall",  command=f._sync_fw_all)
        fwm.add_command(label="Sync all Domains → Hosts file",    command=f._sync_hosts_all)
        fwm.add_command(label="Sync EVERYTHING",                   command=f._sync_everything)
        fwm.add_separator()
        fwm.add_command(label="Remove ALL Issu's Firewall rules",  command=f._remove_all_fw_rules)
        fwm.add_command(label="Remove ALL Issu's Hosts entries",   command=f._remove_all_hosts)
        bar.add_cascade(label="Firewall / Hosts", menu=fwm)

        hm = tk.Menu(bar, tearoff=False, bg=C["panel"], fg=C["text"],
                     activebackground=C["select_bg"])
        hm.add_command(label="How to use…",           command=f._show_help)
        hm.add_separator()
        hm.add_command(label="Open log file",         command=lambda: open_path(LOG_FILE))
        hm.add_command(label="Open crash log",        command=lambda: open_path(CRASH_FILE))
        hm.add_command(label="Open hosts backup",
                       command=lambda: open_path(HOSTS_BACKUP)
                       if os.path.exists(HOSTS_BACKUP)
                       else messagebox.showinfo("No backup", "No hosts backup found yet."))
        hm.add_command(label="Open hosts file",       command=lambda: open_path(HOSTS_FILE))
        hm.add_command(label="Open Helpfiles folder", command=lambda: open_path(HELPFILES_DIR))
        hm.add_separator()
        hm.add_command(label="About",                 command=f._show_about)
        bar.add_cascade(label="Help", menu=hm)

    def _on_close(self):
        self._frame.save_state(geometry=self.geometry())
        log_info("Application closed.")
        self.destroy()


# *************** DEL 18 – PUBLIC API ***************
def launch_app(blocklist_path: str = None):
    """
    Open Issu's Firewall Manager as a standalone window.

    Parameters
    ----------
    blocklist_path : str | None
        Optional path to a JSON blocklist file to pre-load.
        If None, uses the default path in /Helpfiles/0---Settings/.

    Blocking – runs mainloop() and returns only after window is closed.

    Example (as module)
    --------------------
        from issu_firewall import launch_app
        launch_app()
        launch_app("C:/mylists/custom.json")

    Hub / notebook embedding
    -------------------------
        import issu_firewall
        frame = issu_firewall.EditorFrame(self.notebook)
    """
    # AppUserModelID måste sättas INNAN tk.Tk() skapas (IssusFirewall ärver tk.Tk)
    try:
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
            "LarsIssuOlsson.FirewallAdding.1"
        )
    except Exception:
        pass

    app = IssusFirewall(initial_blocklist=blocklist_path)

    # after(0) = första ticken efter mainloop startar — tkinter hinner inte
    # skriva över ikonen som den gör vid ett direkt anrop i __init__.
    app.after(0, lambda: _set_window_icon(app))

    app.mainloop()


# *************** DEL 19 – ENTRY POINT (standalone) ***************
if __name__ == "__main__":
    import sys as _sys
    _initial = _sys.argv[1] if len(_sys.argv) > 1 else None
    launch_app(_initial)
